xref: /freebsd/contrib/sqlite3/sqlite3.c (revision a812392203d7c4c3f0db9d8a0f3391374c49c71f)
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.8.7.2.  By combining all the individual C code files into this
4 ** single large file, the entire code can be compiled as a single translation
5 ** unit.  This allows many compilers to do optimizations that would not be
6 ** possible if the files were compiled separately.  Performance improvements
7 ** of 5% or more are commonly seen when SQLite is compiled as a single
8 ** translation unit.
9 **
10 ** This file is all you need to compile SQLite.  To use SQLite in other
11 ** programs, you need this file and the "sqlite3.h" header file that defines
12 ** the programming interface to the SQLite library.  (If you do not have
13 ** the "sqlite3.h" header file at hand, you will find a copy embedded within
14 ** the text of this file.  Search for "Begin file sqlite3.h" to find the start
15 ** of the embedded sqlite3.h header file.) Additional code files may be needed
16 ** if you want a wrapper to interface SQLite with your choice of programming
17 ** language. The code for the "sqlite3" command-line shell is also in a
18 ** separate file. This file contains only code for the core SQLite library.
19 */
20 #define SQLITE_CORE 1
21 #define SQLITE_AMALGAMATION 1
22 #ifndef SQLITE_PRIVATE
23 # define SQLITE_PRIVATE static
24 #endif
25 #ifndef SQLITE_API
26 # define SQLITE_API
27 #endif
28 /************** Begin file sqliteInt.h ***************************************/
29 /*
30 ** 2001 September 15
31 **
32 ** The author disclaims copyright to this source code.  In place of
33 ** a legal notice, here is a blessing:
34 **
35 **    May you do good and not evil.
36 **    May you find forgiveness for yourself and forgive others.
37 **    May you share freely, never taking more than you give.
38 **
39 *************************************************************************
40 ** Internal interface definitions for SQLite.
41 **
42 */
43 #ifndef _SQLITEINT_H_
44 #define _SQLITEINT_H_
45 
46 /*
47 ** These #defines should enable >2GB file support on POSIX if the
48 ** underlying operating system supports it.  If the OS lacks
49 ** large file support, or if the OS is windows, these should be no-ops.
50 **
51 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
52 ** system #includes.  Hence, this block of code must be the very first
53 ** code in all source files.
54 **
55 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
56 ** on the compiler command line.  This is necessary if you are compiling
57 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
58 ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
59 ** without this option, LFS is enable.  But LFS does not exist in the kernel
60 ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
61 ** portability you should omit LFS.
62 **
63 ** The previous paragraph was written in 2005.  (This paragraph is written
64 ** on 2008-11-28.) These days, all Linux kernels support large files, so
65 ** you should probably leave LFS enabled.  But some embedded platforms might
66 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
67 **
68 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
69 */
70 #ifndef SQLITE_DISABLE_LFS
71 # define _LARGE_FILE       1
72 # ifndef _FILE_OFFSET_BITS
73 #   define _FILE_OFFSET_BITS 64
74 # endif
75 # define _LARGEFILE_SOURCE 1
76 #endif
77 
78 /* Needed for various definitions... */
79 #if defined(__GNUC__) && !defined(_GNU_SOURCE)
80 # define _GNU_SOURCE
81 #endif
82 
83 #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
84 # define _BSD_SOURCE
85 #endif
86 
87 /*
88 ** For MinGW, check to see if we can include the header file containing its
89 ** version information, among other things.  Normally, this internal MinGW
90 ** header file would [only] be included automatically by other MinGW header
91 ** files; however, the contained version information is now required by this
92 ** header file to work around binary compatibility issues (see below) and
93 ** this is the only known way to reliably obtain it.  This entire #if block
94 ** would be completely unnecessary if there was any other way of detecting
95 ** MinGW via their preprocessor (e.g. if they customized their GCC to define
96 ** some MinGW-specific macros).  When compiling for MinGW, either the
97 ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
98 ** defined; otherwise, detection of conditions specific to MinGW will be
99 ** disabled.
100 */
101 #if defined(_HAVE_MINGW_H)
102 # include "mingw.h"
103 #elif defined(_HAVE__MINGW_H)
104 # include "_mingw.h"
105 #endif
106 
107 /*
108 ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
109 ** define is required to maintain binary compatibility with the MSVC runtime
110 ** library in use (e.g. for Windows XP).
111 */
112 #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
113     defined(_WIN32) && !defined(_WIN64) && \
114     defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
115     defined(__MSVCRT__)
116 # define _USE_32BIT_TIME_T
117 #endif
118 
119 /* The public SQLite interface.  The _FILE_OFFSET_BITS macro must appear
120 ** first in QNX.  Also, the _USE_32BIT_TIME_T macro must appear first for
121 ** MinGW.
122 */
123 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
124 /************** Begin file sqlite3.h *****************************************/
125 /*
126 ** 2001 September 15
127 **
128 ** The author disclaims copyright to this source code.  In place of
129 ** a legal notice, here is a blessing:
130 **
131 **    May you do good and not evil.
132 **    May you find forgiveness for yourself and forgive others.
133 **    May you share freely, never taking more than you give.
134 **
135 *************************************************************************
136 ** This header file defines the interface that the SQLite library
137 ** presents to client programs.  If a C-function, structure, datatype,
138 ** or constant definition does not appear in this file, then it is
139 ** not a published API of SQLite, is subject to change without
140 ** notice, and should not be referenced by programs that use SQLite.
141 **
142 ** Some of the definitions that are in this file are marked as
143 ** "experimental".  Experimental interfaces are normally new
144 ** features recently added to SQLite.  We do not anticipate changes
145 ** to experimental interfaces but reserve the right to make minor changes
146 ** if experience from use "in the wild" suggest such changes are prudent.
147 **
148 ** The official C-language API documentation for SQLite is derived
149 ** from comments in this file.  This file is the authoritative source
150 ** on how SQLite interfaces are suppose to operate.
151 **
152 ** The name of this file under configuration management is "sqlite.h.in".
153 ** The makefile makes some minor changes to this file (such as inserting
154 ** the version number) and changes its name to "sqlite3.h" as
155 ** part of the build process.
156 */
157 #ifndef _SQLITE3_H_
158 #define _SQLITE3_H_
159 #include <stdarg.h>     /* Needed for the definition of va_list */
160 
161 /*
162 ** Make sure we can call this stuff from C++.
163 */
164 #if 0
165 extern "C" {
166 #endif
167 
168 
169 /*
170 ** Add the ability to override 'extern'
171 */
172 #ifndef SQLITE_EXTERN
173 # define SQLITE_EXTERN extern
174 #endif
175 
176 #ifndef SQLITE_API
177 # define SQLITE_API
178 #endif
179 
180 
181 /*
182 ** These no-op macros are used in front of interfaces to mark those
183 ** interfaces as either deprecated or experimental.  New applications
184 ** should not use deprecated interfaces - they are support for backwards
185 ** compatibility only.  Application writers should be aware that
186 ** experimental interfaces are subject to change in point releases.
187 **
188 ** These macros used to resolve to various kinds of compiler magic that
189 ** would generate warning messages when they were used.  But that
190 ** compiler magic ended up generating such a flurry of bug reports
191 ** that we have taken it all out and gone back to using simple
192 ** noop macros.
193 */
194 #define SQLITE_DEPRECATED
195 #define SQLITE_EXPERIMENTAL
196 
197 /*
198 ** Ensure these symbols were not defined by some previous header file.
199 */
200 #ifdef SQLITE_VERSION
201 # undef SQLITE_VERSION
202 #endif
203 #ifdef SQLITE_VERSION_NUMBER
204 # undef SQLITE_VERSION_NUMBER
205 #endif
206 
207 /*
208 ** CAPI3REF: Compile-Time Library Version Numbers
209 **
210 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
211 ** evaluates to a string literal that is the SQLite version in the
212 ** format "X.Y.Z" where X is the major version number (always 3 for
213 ** SQLite3) and Y is the minor version number and Z is the release number.)^
214 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
215 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
216 ** numbers used in [SQLITE_VERSION].)^
217 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
218 ** be larger than the release from which it is derived.  Either Y will
219 ** be held constant and Z will be incremented or else Y will be incremented
220 ** and Z will be reset to zero.
221 **
222 ** Since version 3.6.18, SQLite source code has been stored in the
223 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
224 ** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
225 ** a string which identifies a particular check-in of SQLite
226 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
227 ** string contains the date and time of the check-in (UTC) and an SHA1
228 ** hash of the entire source tree.
229 **
230 ** See also: [sqlite3_libversion()],
231 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
232 ** [sqlite_version()] and [sqlite_source_id()].
233 */
234 #define SQLITE_VERSION        "3.8.7.2"
235 #define SQLITE_VERSION_NUMBER 3008007
236 #define SQLITE_SOURCE_ID      "2014-11-18 20:57:56 2ab564bf9655b7c7b97ab85cafc8a48329b27f93"
237 
238 /*
239 ** CAPI3REF: Run-Time Library Version Numbers
240 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
241 **
242 ** These interfaces provide the same information as the [SQLITE_VERSION],
243 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
244 ** but are associated with the library instead of the header file.  ^(Cautious
245 ** programmers might include assert() statements in their application to
246 ** verify that values returned by these interfaces match the macros in
247 ** the header, and thus insure that the application is
248 ** compiled with matching library and header files.
249 **
250 ** <blockquote><pre>
251 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
252 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
253 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
254 ** </pre></blockquote>)^
255 **
256 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
257 ** macro.  ^The sqlite3_libversion() function returns a pointer to the
258 ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
259 ** function is provided for use in DLLs since DLL users usually do not have
260 ** direct access to string constants within the DLL.  ^The
261 ** sqlite3_libversion_number() function returns an integer equal to
262 ** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns
263 ** a pointer to a string constant whose value is the same as the
264 ** [SQLITE_SOURCE_ID] C preprocessor macro.
265 **
266 ** See also: [sqlite_version()] and [sqlite_source_id()].
267 */
268 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
269 SQLITE_API const char *sqlite3_libversion(void);
270 SQLITE_API const char *sqlite3_sourceid(void);
271 SQLITE_API int sqlite3_libversion_number(void);
272 
273 /*
274 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
275 **
276 ** ^The sqlite3_compileoption_used() function returns 0 or 1
277 ** indicating whether the specified option was defined at
278 ** compile time.  ^The SQLITE_ prefix may be omitted from the
279 ** option name passed to sqlite3_compileoption_used().
280 **
281 ** ^The sqlite3_compileoption_get() function allows iterating
282 ** over the list of options that were defined at compile time by
283 ** returning the N-th compile time option string.  ^If N is out of range,
284 ** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_
285 ** prefix is omitted from any strings returned by
286 ** sqlite3_compileoption_get().
287 **
288 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
289 ** and sqlite3_compileoption_get() may be omitted by specifying the
290 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
291 **
292 ** See also: SQL functions [sqlite_compileoption_used()] and
293 ** [sqlite_compileoption_get()] and the [compile_options pragma].
294 */
295 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
296 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
297 SQLITE_API const char *sqlite3_compileoption_get(int N);
298 #endif
299 
300 /*
301 ** CAPI3REF: Test To See If The Library Is Threadsafe
302 **
303 ** ^The sqlite3_threadsafe() function returns zero if and only if
304 ** SQLite was compiled with mutexing code omitted due to the
305 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
306 **
307 ** SQLite can be compiled with or without mutexes.  When
308 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
309 ** are enabled and SQLite is threadsafe.  When the
310 ** [SQLITE_THREADSAFE] macro is 0,
311 ** the mutexes are omitted.  Without the mutexes, it is not safe
312 ** to use SQLite concurrently from more than one thread.
313 **
314 ** Enabling mutexes incurs a measurable performance penalty.
315 ** So if speed is of utmost importance, it makes sense to disable
316 ** the mutexes.  But for maximum safety, mutexes should be enabled.
317 ** ^The default behavior is for mutexes to be enabled.
318 **
319 ** This interface can be used by an application to make sure that the
320 ** version of SQLite that it is linking against was compiled with
321 ** the desired setting of the [SQLITE_THREADSAFE] macro.
322 **
323 ** This interface only reports on the compile-time mutex setting
324 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
325 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
326 ** can be fully or partially disabled using a call to [sqlite3_config()]
327 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
328 ** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
329 ** sqlite3_threadsafe() function shows only the compile-time setting of
330 ** thread safety, not any run-time changes to that setting made by
331 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
332 ** is unchanged by calls to sqlite3_config().)^
333 **
334 ** See the [threading mode] documentation for additional information.
335 */
336 SQLITE_API int sqlite3_threadsafe(void);
337 
338 /*
339 ** CAPI3REF: Database Connection Handle
340 ** KEYWORDS: {database connection} {database connections}
341 **
342 ** Each open SQLite database is represented by a pointer to an instance of
343 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
344 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
345 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
346 ** and [sqlite3_close_v2()] are its destructors.  There are many other
347 ** interfaces (such as
348 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
349 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
350 ** sqlite3 object.
351 */
352 typedef struct sqlite3 sqlite3;
353 
354 /*
355 ** CAPI3REF: 64-Bit Integer Types
356 ** KEYWORDS: sqlite_int64 sqlite_uint64
357 **
358 ** Because there is no cross-platform way to specify 64-bit integer types
359 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
360 **
361 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
362 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
363 ** compatibility only.
364 **
365 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
366 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
367 ** sqlite3_uint64 and sqlite_uint64 types can store integer values
368 ** between 0 and +18446744073709551615 inclusive.
369 */
370 #ifdef SQLITE_INT64_TYPE
371   typedef SQLITE_INT64_TYPE sqlite_int64;
372   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
373 #elif defined(_MSC_VER) || defined(__BORLANDC__)
374   typedef __int64 sqlite_int64;
375   typedef unsigned __int64 sqlite_uint64;
376 #else
377   typedef long long int sqlite_int64;
378   typedef unsigned long long int sqlite_uint64;
379 #endif
380 typedef sqlite_int64 sqlite3_int64;
381 typedef sqlite_uint64 sqlite3_uint64;
382 
383 /*
384 ** If compiling for a processor that lacks floating point support,
385 ** substitute integer for floating-point.
386 */
387 #ifdef SQLITE_OMIT_FLOATING_POINT
388 # define double sqlite3_int64
389 #endif
390 
391 /*
392 ** CAPI3REF: Closing A Database Connection
393 **
394 ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
395 ** for the [sqlite3] object.
396 ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
397 ** the [sqlite3] object is successfully destroyed and all associated
398 ** resources are deallocated.
399 **
400 ** ^If the database connection is associated with unfinalized prepared
401 ** statements or unfinished sqlite3_backup objects then sqlite3_close()
402 ** will leave the database connection open and return [SQLITE_BUSY].
403 ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
404 ** and/or unfinished sqlite3_backups, then the database connection becomes
405 ** an unusable "zombie" which will automatically be deallocated when the
406 ** last prepared statement is finalized or the last sqlite3_backup is
407 ** finished.  The sqlite3_close_v2() interface is intended for use with
408 ** host languages that are garbage collected, and where the order in which
409 ** destructors are called is arbitrary.
410 **
411 ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
412 ** [sqlite3_blob_close | close] all [BLOB handles], and
413 ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
414 ** with the [sqlite3] object prior to attempting to close the object.  ^If
415 ** sqlite3_close_v2() is called on a [database connection] that still has
416 ** outstanding [prepared statements], [BLOB handles], and/or
417 ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
418 ** of resources is deferred until all [prepared statements], [BLOB handles],
419 ** and [sqlite3_backup] objects are also destroyed.
420 **
421 ** ^If an [sqlite3] object is destroyed while a transaction is open,
422 ** the transaction is automatically rolled back.
423 **
424 ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
425 ** must be either a NULL
426 ** pointer or an [sqlite3] object pointer obtained
427 ** from [sqlite3_open()], [sqlite3_open16()], or
428 ** [sqlite3_open_v2()], and not previously closed.
429 ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
430 ** argument is a harmless no-op.
431 */
432 SQLITE_API int sqlite3_close(sqlite3*);
433 SQLITE_API int sqlite3_close_v2(sqlite3*);
434 
435 /*
436 ** The type for a callback function.
437 ** This is legacy and deprecated.  It is included for historical
438 ** compatibility and is not documented.
439 */
440 typedef int (*sqlite3_callback)(void*,int,char**, char**);
441 
442 /*
443 ** CAPI3REF: One-Step Query Execution Interface
444 **
445 ** The sqlite3_exec() interface is a convenience wrapper around
446 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
447 ** that allows an application to run multiple statements of SQL
448 ** without having to use a lot of C code.
449 **
450 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
451 ** semicolon-separate SQL statements passed into its 2nd argument,
452 ** in the context of the [database connection] passed in as its 1st
453 ** argument.  ^If the callback function of the 3rd argument to
454 ** sqlite3_exec() is not NULL, then it is invoked for each result row
455 ** coming out of the evaluated SQL statements.  ^The 4th argument to
456 ** sqlite3_exec() is relayed through to the 1st argument of each
457 ** callback invocation.  ^If the callback pointer to sqlite3_exec()
458 ** is NULL, then no callback is ever invoked and result rows are
459 ** ignored.
460 **
461 ** ^If an error occurs while evaluating the SQL statements passed into
462 ** sqlite3_exec(), then execution of the current statement stops and
463 ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
464 ** is not NULL then any error message is written into memory obtained
465 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
466 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
467 ** on error message strings returned through the 5th parameter of
468 ** of sqlite3_exec() after the error message string is no longer needed.
469 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
470 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
471 ** NULL before returning.
472 **
473 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
474 ** routine returns SQLITE_ABORT without invoking the callback again and
475 ** without running any subsequent SQL statements.
476 **
477 ** ^The 2nd argument to the sqlite3_exec() callback function is the
478 ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
479 ** callback is an array of pointers to strings obtained as if from
480 ** [sqlite3_column_text()], one for each column.  ^If an element of a
481 ** result row is NULL then the corresponding string pointer for the
482 ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
483 ** sqlite3_exec() callback is an array of pointers to strings where each
484 ** entry represents the name of corresponding result column as obtained
485 ** from [sqlite3_column_name()].
486 **
487 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
488 ** to an empty string, or a pointer that contains only whitespace and/or
489 ** SQL comments, then no SQL statements are evaluated and the database
490 ** is not changed.
491 **
492 ** Restrictions:
493 **
494 ** <ul>
495 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
496 **      is a valid and open [database connection].
497 ** <li> The application must not close the [database connection] specified by
498 **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
499 ** <li> The application must not modify the SQL statement text passed into
500 **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
501 ** </ul>
502 */
503 SQLITE_API int sqlite3_exec(
504   sqlite3*,                                  /* An open database */
505   const char *sql,                           /* SQL to be evaluated */
506   int (*callback)(void*,int,char**,char**),  /* Callback function */
507   void *,                                    /* 1st argument to callback */
508   char **errmsg                              /* Error msg written here */
509 );
510 
511 /*
512 ** CAPI3REF: Result Codes
513 ** KEYWORDS: {result code definitions}
514 **
515 ** Many SQLite functions return an integer result code from the set shown
516 ** here in order to indicate success or failure.
517 **
518 ** New error codes may be added in future versions of SQLite.
519 **
520 ** See also: [extended result code definitions]
521 */
522 #define SQLITE_OK           0   /* Successful result */
523 /* beginning-of-error-codes */
524 #define SQLITE_ERROR        1   /* SQL error or missing database */
525 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
526 #define SQLITE_PERM         3   /* Access permission denied */
527 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
528 #define SQLITE_BUSY         5   /* The database file is locked */
529 #define SQLITE_LOCKED       6   /* A table in the database is locked */
530 #define SQLITE_NOMEM        7   /* A malloc() failed */
531 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
532 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
533 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
534 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
535 #define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
536 #define SQLITE_FULL        13   /* Insertion failed because database is full */
537 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
538 #define SQLITE_PROTOCOL    15   /* Database lock protocol error */
539 #define SQLITE_EMPTY       16   /* Database is empty */
540 #define SQLITE_SCHEMA      17   /* The database schema changed */
541 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
542 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
543 #define SQLITE_MISMATCH    20   /* Data type mismatch */
544 #define SQLITE_MISUSE      21   /* Library used incorrectly */
545 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
546 #define SQLITE_AUTH        23   /* Authorization denied */
547 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
548 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
549 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
550 #define SQLITE_NOTICE      27   /* Notifications from sqlite3_log() */
551 #define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */
552 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
553 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
554 /* end-of-error-codes */
555 
556 /*
557 ** CAPI3REF: Extended Result Codes
558 ** KEYWORDS: {extended result code definitions}
559 **
560 ** In its default configuration, SQLite API routines return one of 30 integer
561 ** [result codes].  However, experience has shown that many of
562 ** these result codes are too coarse-grained.  They do not provide as
563 ** much information about problems as programmers might like.  In an effort to
564 ** address this, newer versions of SQLite (version 3.3.8 and later) include
565 ** support for additional result codes that provide more detailed information
566 ** about errors. These [extended result codes] are enabled or disabled
567 ** on a per database connection basis using the
568 ** [sqlite3_extended_result_codes()] API.  Or, the extended code for
569 ** the most recent error can be obtained using
570 ** [sqlite3_extended_errcode()].
571 */
572 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
573 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
574 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
575 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
576 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
577 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
578 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
579 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
580 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
581 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
582 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
583 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
584 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
585 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
586 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
587 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
588 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
589 #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
590 #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
591 #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
592 #define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
593 #define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
594 #define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))
595 #define SQLITE_IOERR_MMAP              (SQLITE_IOERR | (24<<8))
596 #define SQLITE_IOERR_GETTEMPPATH       (SQLITE_IOERR | (25<<8))
597 #define SQLITE_IOERR_CONVPATH          (SQLITE_IOERR | (26<<8))
598 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
599 #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
600 #define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))
601 #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
602 #define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
603 #define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
604 #define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
605 #define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
606 #define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
607 #define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
608 #define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
609 #define SQLITE_READONLY_DBMOVED        (SQLITE_READONLY | (4<<8))
610 #define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
611 #define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))
612 #define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))
613 #define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))
614 #define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))
615 #define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))
616 #define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))
617 #define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))
618 #define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
619 #define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
620 #define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))
621 #define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
622 #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
623 #define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
624 #define SQLITE_AUTH_USER               (SQLITE_AUTH | (1<<8))
625 
626 /*
627 ** CAPI3REF: Flags For File Open Operations
628 **
629 ** These bit values are intended for use in the
630 ** 3rd parameter to the [sqlite3_open_v2()] interface and
631 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
632 */
633 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
634 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
635 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
636 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
637 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
638 #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
639 #define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
640 #define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
641 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
642 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
643 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
644 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
645 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
646 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
647 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
648 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
649 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
650 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
651 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
652 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
653 
654 /* Reserved:                         0x00F00000 */
655 
656 /*
657 ** CAPI3REF: Device Characteristics
658 **
659 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
660 ** object returns an integer which is a vector of these
661 ** bit values expressing I/O characteristics of the mass storage
662 ** device that holds the file that the [sqlite3_io_methods]
663 ** refers to.
664 **
665 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
666 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
667 ** mean that writes of blocks that are nnn bytes in size and
668 ** are aligned to an address which is an integer multiple of
669 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
670 ** that when data is appended to a file, the data is appended
671 ** first then the size of the file is extended, never the other
672 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
673 ** information is written to disk in the same order as calls
674 ** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
675 ** after reboot following a crash or power loss, the only bytes in a
676 ** file that were written at the application level might have changed
677 ** and that adjacent bytes, even bytes within the same sector are
678 ** guaranteed to be unchanged.  The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
679 ** flag indicate that a file cannot be deleted when open.  The
680 ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
681 ** read-only media and cannot be changed even by processes with
682 ** elevated privileges.
683 */
684 #define SQLITE_IOCAP_ATOMIC                 0x00000001
685 #define SQLITE_IOCAP_ATOMIC512              0x00000002
686 #define SQLITE_IOCAP_ATOMIC1K               0x00000004
687 #define SQLITE_IOCAP_ATOMIC2K               0x00000008
688 #define SQLITE_IOCAP_ATOMIC4K               0x00000010
689 #define SQLITE_IOCAP_ATOMIC8K               0x00000020
690 #define SQLITE_IOCAP_ATOMIC16K              0x00000040
691 #define SQLITE_IOCAP_ATOMIC32K              0x00000080
692 #define SQLITE_IOCAP_ATOMIC64K              0x00000100
693 #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
694 #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
695 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
696 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
697 #define SQLITE_IOCAP_IMMUTABLE              0x00002000
698 
699 /*
700 ** CAPI3REF: File Locking Levels
701 **
702 ** SQLite uses one of these integer values as the second
703 ** argument to calls it makes to the xLock() and xUnlock() methods
704 ** of an [sqlite3_io_methods] object.
705 */
706 #define SQLITE_LOCK_NONE          0
707 #define SQLITE_LOCK_SHARED        1
708 #define SQLITE_LOCK_RESERVED      2
709 #define SQLITE_LOCK_PENDING       3
710 #define SQLITE_LOCK_EXCLUSIVE     4
711 
712 /*
713 ** CAPI3REF: Synchronization Type Flags
714 **
715 ** When SQLite invokes the xSync() method of an
716 ** [sqlite3_io_methods] object it uses a combination of
717 ** these integer values as the second argument.
718 **
719 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
720 ** sync operation only needs to flush data to mass storage.  Inode
721 ** information need not be flushed. If the lower four bits of the flag
722 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
723 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
724 ** to use Mac OS X style fullsync instead of fsync().
725 **
726 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
727 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
728 ** settings.  The [synchronous pragma] determines when calls to the
729 ** xSync VFS method occur and applies uniformly across all platforms.
730 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
731 ** energetic or rigorous or forceful the sync operations are and
732 ** only make a difference on Mac OSX for the default SQLite code.
733 ** (Third-party VFS implementations might also make the distinction
734 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
735 ** operating systems natively supported by SQLite, only Mac OSX
736 ** cares about the difference.)
737 */
738 #define SQLITE_SYNC_NORMAL        0x00002
739 #define SQLITE_SYNC_FULL          0x00003
740 #define SQLITE_SYNC_DATAONLY      0x00010
741 
742 /*
743 ** CAPI3REF: OS Interface Open File Handle
744 **
745 ** An [sqlite3_file] object represents an open file in the
746 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
747 ** implementations will
748 ** want to subclass this object by appending additional fields
749 ** for their own use.  The pMethods entry is a pointer to an
750 ** [sqlite3_io_methods] object that defines methods for performing
751 ** I/O operations on the open file.
752 */
753 typedef struct sqlite3_file sqlite3_file;
754 struct sqlite3_file {
755   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
756 };
757 
758 /*
759 ** CAPI3REF: OS Interface File Virtual Methods Object
760 **
761 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
762 ** [sqlite3_file] object (or, more commonly, a subclass of the
763 ** [sqlite3_file] object) with a pointer to an instance of this object.
764 ** This object defines the methods used to perform various operations
765 ** against the open file represented by the [sqlite3_file] object.
766 **
767 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
768 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
769 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
770 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
771 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
772 ** to NULL.
773 **
774 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
775 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
776 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
777 ** flag may be ORed in to indicate that only the data of the file
778 ** and not its inode needs to be synced.
779 **
780 ** The integer values to xLock() and xUnlock() are one of
781 ** <ul>
782 ** <li> [SQLITE_LOCK_NONE],
783 ** <li> [SQLITE_LOCK_SHARED],
784 ** <li> [SQLITE_LOCK_RESERVED],
785 ** <li> [SQLITE_LOCK_PENDING], or
786 ** <li> [SQLITE_LOCK_EXCLUSIVE].
787 ** </ul>
788 ** xLock() increases the lock. xUnlock() decreases the lock.
789 ** The xCheckReservedLock() method checks whether any database connection,
790 ** either in this process or in some other process, is holding a RESERVED,
791 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
792 ** if such a lock exists and false otherwise.
793 **
794 ** The xFileControl() method is a generic interface that allows custom
795 ** VFS implementations to directly control an open file using the
796 ** [sqlite3_file_control()] interface.  The second "op" argument is an
797 ** integer opcode.  The third argument is a generic pointer intended to
798 ** point to a structure that may contain arguments or space in which to
799 ** write return values.  Potential uses for xFileControl() might be
800 ** functions to enable blocking locks with timeouts, to change the
801 ** locking strategy (for example to use dot-file locks), to inquire
802 ** about the status of a lock, or to break stale locks.  The SQLite
803 ** core reserves all opcodes less than 100 for its own use.
804 ** A [file control opcodes | list of opcodes] less than 100 is available.
805 ** Applications that define a custom xFileControl method should use opcodes
806 ** greater than 100 to avoid conflicts.  VFS implementations should
807 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
808 ** recognize.
809 **
810 ** The xSectorSize() method returns the sector size of the
811 ** device that underlies the file.  The sector size is the
812 ** minimum write that can be performed without disturbing
813 ** other bytes in the file.  The xDeviceCharacteristics()
814 ** method returns a bit vector describing behaviors of the
815 ** underlying device:
816 **
817 ** <ul>
818 ** <li> [SQLITE_IOCAP_ATOMIC]
819 ** <li> [SQLITE_IOCAP_ATOMIC512]
820 ** <li> [SQLITE_IOCAP_ATOMIC1K]
821 ** <li> [SQLITE_IOCAP_ATOMIC2K]
822 ** <li> [SQLITE_IOCAP_ATOMIC4K]
823 ** <li> [SQLITE_IOCAP_ATOMIC8K]
824 ** <li> [SQLITE_IOCAP_ATOMIC16K]
825 ** <li> [SQLITE_IOCAP_ATOMIC32K]
826 ** <li> [SQLITE_IOCAP_ATOMIC64K]
827 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
828 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
829 ** </ul>
830 **
831 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
832 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
833 ** mean that writes of blocks that are nnn bytes in size and
834 ** are aligned to an address which is an integer multiple of
835 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
836 ** that when data is appended to a file, the data is appended
837 ** first then the size of the file is extended, never the other
838 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
839 ** information is written to disk in the same order as calls
840 ** to xWrite().
841 **
842 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
843 ** in the unread portions of the buffer with zeros.  A VFS that
844 ** fails to zero-fill short reads might seem to work.  However,
845 ** failure to zero-fill short reads will eventually lead to
846 ** database corruption.
847 */
848 typedef struct sqlite3_io_methods sqlite3_io_methods;
849 struct sqlite3_io_methods {
850   int iVersion;
851   int (*xClose)(sqlite3_file*);
852   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
853   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
854   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
855   int (*xSync)(sqlite3_file*, int flags);
856   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
857   int (*xLock)(sqlite3_file*, int);
858   int (*xUnlock)(sqlite3_file*, int);
859   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
860   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
861   int (*xSectorSize)(sqlite3_file*);
862   int (*xDeviceCharacteristics)(sqlite3_file*);
863   /* Methods above are valid for version 1 */
864   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
865   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
866   void (*xShmBarrier)(sqlite3_file*);
867   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
868   /* Methods above are valid for version 2 */
869   int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
870   int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
871   /* Methods above are valid for version 3 */
872   /* Additional methods may be added in future releases */
873 };
874 
875 /*
876 ** CAPI3REF: Standard File Control Opcodes
877 ** KEYWORDS: {file control opcodes} {file control opcode}
878 **
879 ** These integer constants are opcodes for the xFileControl method
880 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
881 ** interface.
882 **
883 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
884 ** opcode causes the xFileControl method to write the current state of
885 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
886 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
887 ** into an integer that the pArg argument points to. This capability
888 ** is used during testing and only needs to be supported when SQLITE_TEST
889 ** is defined.
890 ** <ul>
891 ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
892 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
893 ** layer a hint of how large the database file will grow to be during the
894 ** current transaction.  This hint is not guaranteed to be accurate but it
895 ** is often close.  The underlying VFS might choose to preallocate database
896 ** file space based on this hint in order to help writes to the database
897 ** file run faster.
898 **
899 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
900 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
901 ** extends and truncates the database file in chunks of a size specified
902 ** by the user. The fourth argument to [sqlite3_file_control()] should
903 ** point to an integer (type int) containing the new chunk-size to use
904 ** for the nominated database. Allocating database file space in large
905 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
906 ** improve performance on some systems.
907 **
908 ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
909 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
910 ** to the [sqlite3_file] object associated with a particular database
911 ** connection.  See the [sqlite3_file_control()] documentation for
912 ** additional information.
913 **
914 ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
915 ** No longer in use.
916 **
917 ** <li>[[SQLITE_FCNTL_SYNC]]
918 ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
919 ** sent to the VFS immediately before the xSync method is invoked on a
920 ** database file descriptor. Or, if the xSync method is not invoked
921 ** because the user has configured SQLite with
922 ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
923 ** of the xSync method. In most cases, the pointer argument passed with
924 ** this file-control is NULL. However, if the database file is being synced
925 ** as part of a multi-database commit, the argument points to a nul-terminated
926 ** string containing the transactions master-journal file name. VFSes that
927 ** do not need this signal should silently ignore this opcode. Applications
928 ** should not call [sqlite3_file_control()] with this opcode as doing so may
929 ** disrupt the operation of the specialized VFSes that do require it.
930 **
931 ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
932 ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
933 ** and sent to the VFS after a transaction has been committed immediately
934 ** but before the database is unlocked. VFSes that do not need this signal
935 ** should silently ignore this opcode. Applications should not call
936 ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
937 ** operation of the specialized VFSes that do require it.
938 **
939 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
940 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
941 ** retry counts and intervals for certain disk I/O operations for the
942 ** windows [VFS] in order to provide robustness in the presence of
943 ** anti-virus programs.  By default, the windows VFS will retry file read,
944 ** file write, and file delete operations up to 10 times, with a delay
945 ** of 25 milliseconds before the first retry and with the delay increasing
946 ** by an additional 25 milliseconds with each subsequent retry.  This
947 ** opcode allows these two values (10 retries and 25 milliseconds of delay)
948 ** to be adjusted.  The values are changed for all database connections
949 ** within the same process.  The argument is a pointer to an array of two
950 ** integers where the first integer i the new retry count and the second
951 ** integer is the delay.  If either integer is negative, then the setting
952 ** is not changed but instead the prior value of that setting is written
953 ** into the array entry, allowing the current retry settings to be
954 ** interrogated.  The zDbName parameter is ignored.
955 **
956 ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
957 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
958 ** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
959 ** write ahead log and shared memory files used for transaction control
960 ** are automatically deleted when the latest connection to the database
961 ** closes.  Setting persistent WAL mode causes those files to persist after
962 ** close.  Persisting the files is useful when other processes that do not
963 ** have write permission on the directory containing the database file want
964 ** to read the database file, as the WAL and shared memory files must exist
965 ** in order for the database to be readable.  The fourth parameter to
966 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
967 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
968 ** WAL mode.  If the integer is -1, then it is overwritten with the current
969 ** WAL persistence setting.
970 **
971 ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
972 ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
973 ** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
974 ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
975 ** xDeviceCharacteristics methods. The fourth parameter to
976 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
977 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
978 ** mode.  If the integer is -1, then it is overwritten with the current
979 ** zero-damage mode setting.
980 **
981 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
982 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
983 ** a write transaction to indicate that, unless it is rolled back for some
984 ** reason, the entire database file will be overwritten by the current
985 ** transaction. This is used by VACUUM operations.
986 **
987 ** <li>[[SQLITE_FCNTL_VFSNAME]]
988 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
989 ** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
990 ** final bottom-level VFS are written into memory obtained from
991 ** [sqlite3_malloc()] and the result is stored in the char* variable
992 ** that the fourth parameter of [sqlite3_file_control()] points to.
993 ** The caller is responsible for freeing the memory when done.  As with
994 ** all file-control actions, there is no guarantee that this will actually
995 ** do anything.  Callers should initialize the char* variable to a NULL
996 ** pointer in case this file-control is not implemented.  This file-control
997 ** is intended for diagnostic use only.
998 **
999 ** <li>[[SQLITE_FCNTL_PRAGMA]]
1000 ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1001 ** file control is sent to the open [sqlite3_file] object corresponding
1002 ** to the database file to which the pragma statement refers. ^The argument
1003 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1004 ** pointers to strings (char**) in which the second element of the array
1005 ** is the name of the pragma and the third element is the argument to the
1006 ** pragma or NULL if the pragma has no argument.  ^The handler for an
1007 ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1008 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1009 ** or the equivalent and that string will become the result of the pragma or
1010 ** the error message if the pragma fails. ^If the
1011 ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1012 ** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
1013 ** file control returns [SQLITE_OK], then the parser assumes that the
1014 ** VFS has handled the PRAGMA itself and the parser generates a no-op
1015 ** prepared statement.  ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1016 ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1017 ** that the VFS encountered an error while handling the [PRAGMA] and the
1018 ** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
1019 ** file control occurs at the beginning of pragma statement analysis and so
1020 ** it is able to override built-in [PRAGMA] statements.
1021 **
1022 ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1023 ** ^The [SQLITE_FCNTL_BUSYHANDLER]
1024 ** file-control may be invoked by SQLite on the database file handle
1025 ** shortly after it is opened in order to provide a custom VFS with access
1026 ** to the connections busy-handler callback. The argument is of type (void **)
1027 ** - an array of two (void *) values. The first (void *) actually points
1028 ** to a function of type (int (*)(void *)). In order to invoke the connections
1029 ** busy-handler, this function should be invoked with the second (void *) in
1030 ** the array as the only argument. If it returns non-zero, then the operation
1031 ** should be retried. If it returns zero, the custom VFS should abandon the
1032 ** current operation.
1033 **
1034 ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1035 ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1036 ** to have SQLite generate a
1037 ** temporary filename using the same algorithm that is followed to generate
1038 ** temporary filenames for TEMP tables and other internal uses.  The
1039 ** argument should be a char** which will be filled with the filename
1040 ** written into memory obtained from [sqlite3_malloc()].  The caller should
1041 ** invoke [sqlite3_free()] on the result to avoid a memory leak.
1042 **
1043 ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
1044 ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
1045 ** maximum number of bytes that will be used for memory-mapped I/O.
1046 ** The argument is a pointer to a value of type sqlite3_int64 that
1047 ** is an advisory maximum number of bytes in the file to memory map.  The
1048 ** pointer is overwritten with the old value.  The limit is not changed if
1049 ** the value originally pointed to is negative, and so the current limit
1050 ** can be queried by passing in a pointer to a negative number.  This
1051 ** file-control is used internally to implement [PRAGMA mmap_size].
1052 **
1053 ** <li>[[SQLITE_FCNTL_TRACE]]
1054 ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
1055 ** to the VFS about what the higher layers of the SQLite stack are doing.
1056 ** This file control is used by some VFS activity tracing [shims].
1057 ** The argument is a zero-terminated string.  Higher layers in the
1058 ** SQLite stack may generate instances of this file control if
1059 ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
1060 **
1061 ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
1062 ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
1063 ** pointer to an integer and it writes a boolean into that integer depending
1064 ** on whether or not the file has been renamed, moved, or deleted since it
1065 ** was first opened.
1066 **
1067 ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
1068 ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging.  This
1069 ** opcode causes the xFileControl method to swap the file handle with the one
1070 ** pointed to by the pArg argument.  This capability is used during testing
1071 ** and only needs to be supported when SQLITE_TEST is defined.
1072 **
1073 ** </ul>
1074 */
1075 #define SQLITE_FCNTL_LOCKSTATE               1
1076 #define SQLITE_GET_LOCKPROXYFILE             2
1077 #define SQLITE_SET_LOCKPROXYFILE             3
1078 #define SQLITE_LAST_ERRNO                    4
1079 #define SQLITE_FCNTL_SIZE_HINT               5
1080 #define SQLITE_FCNTL_CHUNK_SIZE              6
1081 #define SQLITE_FCNTL_FILE_POINTER            7
1082 #define SQLITE_FCNTL_SYNC_OMITTED            8
1083 #define SQLITE_FCNTL_WIN32_AV_RETRY          9
1084 #define SQLITE_FCNTL_PERSIST_WAL            10
1085 #define SQLITE_FCNTL_OVERWRITE              11
1086 #define SQLITE_FCNTL_VFSNAME                12
1087 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
1088 #define SQLITE_FCNTL_PRAGMA                 14
1089 #define SQLITE_FCNTL_BUSYHANDLER            15
1090 #define SQLITE_FCNTL_TEMPFILENAME           16
1091 #define SQLITE_FCNTL_MMAP_SIZE              18
1092 #define SQLITE_FCNTL_TRACE                  19
1093 #define SQLITE_FCNTL_HAS_MOVED              20
1094 #define SQLITE_FCNTL_SYNC                   21
1095 #define SQLITE_FCNTL_COMMIT_PHASETWO        22
1096 #define SQLITE_FCNTL_WIN32_SET_HANDLE       23
1097 
1098 /*
1099 ** CAPI3REF: Mutex Handle
1100 **
1101 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1102 ** abstract type for a mutex object.  The SQLite core never looks
1103 ** at the internal representation of an [sqlite3_mutex].  It only
1104 ** deals with pointers to the [sqlite3_mutex] object.
1105 **
1106 ** Mutexes are created using [sqlite3_mutex_alloc()].
1107 */
1108 typedef struct sqlite3_mutex sqlite3_mutex;
1109 
1110 /*
1111 ** CAPI3REF: OS Interface Object
1112 **
1113 ** An instance of the sqlite3_vfs object defines the interface between
1114 ** the SQLite core and the underlying operating system.  The "vfs"
1115 ** in the name of the object stands for "virtual file system".  See
1116 ** the [VFS | VFS documentation] for further information.
1117 **
1118 ** The value of the iVersion field is initially 1 but may be larger in
1119 ** future versions of SQLite.  Additional fields may be appended to this
1120 ** object when the iVersion value is increased.  Note that the structure
1121 ** of the sqlite3_vfs object changes in the transaction between
1122 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1123 ** modified.
1124 **
1125 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1126 ** structure used by this VFS.  mxPathname is the maximum length of
1127 ** a pathname in this VFS.
1128 **
1129 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1130 ** the pNext pointer.  The [sqlite3_vfs_register()]
1131 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1132 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1133 ** searches the list.  Neither the application code nor the VFS
1134 ** implementation should use the pNext pointer.
1135 **
1136 ** The pNext field is the only field in the sqlite3_vfs
1137 ** structure that SQLite will ever modify.  SQLite will only access
1138 ** or modify this field while holding a particular static mutex.
1139 ** The application should never modify anything within the sqlite3_vfs
1140 ** object once the object has been registered.
1141 **
1142 ** The zName field holds the name of the VFS module.  The name must
1143 ** be unique across all VFS modules.
1144 **
1145 ** [[sqlite3_vfs.xOpen]]
1146 ** ^SQLite guarantees that the zFilename parameter to xOpen
1147 ** is either a NULL pointer or string obtained
1148 ** from xFullPathname() with an optional suffix added.
1149 ** ^If a suffix is added to the zFilename parameter, it will
1150 ** consist of a single "-" character followed by no more than
1151 ** 11 alphanumeric and/or "-" characters.
1152 ** ^SQLite further guarantees that
1153 ** the string will be valid and unchanged until xClose() is
1154 ** called. Because of the previous sentence,
1155 ** the [sqlite3_file] can safely store a pointer to the
1156 ** filename if it needs to remember the filename for some reason.
1157 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1158 ** must invent its own temporary name for the file.  ^Whenever the
1159 ** xFilename parameter is NULL it will also be the case that the
1160 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1161 **
1162 ** The flags argument to xOpen() includes all bits set in
1163 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1164 ** or [sqlite3_open16()] is used, then flags includes at least
1165 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1166 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1167 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1168 **
1169 ** ^(SQLite will also add one of the following flags to the xOpen()
1170 ** call, depending on the object being opened:
1171 **
1172 ** <ul>
1173 ** <li>  [SQLITE_OPEN_MAIN_DB]
1174 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1175 ** <li>  [SQLITE_OPEN_TEMP_DB]
1176 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1177 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1178 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1179 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1180 ** <li>  [SQLITE_OPEN_WAL]
1181 ** </ul>)^
1182 **
1183 ** The file I/O implementation can use the object type flags to
1184 ** change the way it deals with files.  For example, an application
1185 ** that does not care about crash recovery or rollback might make
1186 ** the open of a journal file a no-op.  Writes to this journal would
1187 ** also be no-ops, and any attempt to read the journal would return
1188 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1189 ** file will be doing page-aligned sector reads and writes in a random
1190 ** order and set up its I/O subsystem accordingly.
1191 **
1192 ** SQLite might also add one of the following flags to the xOpen method:
1193 **
1194 ** <ul>
1195 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1196 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1197 ** </ul>
1198 **
1199 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1200 ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1201 ** will be set for TEMP databases and their journals, transient
1202 ** databases, and subjournals.
1203 **
1204 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1205 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1206 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1207 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1208 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1209 ** be created, and that it is an error if it already exists.
1210 ** It is <i>not</i> used to indicate the file should be opened
1211 ** for exclusive access.
1212 **
1213 ** ^At least szOsFile bytes of memory are allocated by SQLite
1214 ** to hold the  [sqlite3_file] structure passed as the third
1215 ** argument to xOpen.  The xOpen method does not have to
1216 ** allocate the structure; it should just fill it in.  Note that
1217 ** the xOpen method must set the sqlite3_file.pMethods to either
1218 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1219 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1220 ** element will be valid after xOpen returns regardless of the success
1221 ** or failure of the xOpen call.
1222 **
1223 ** [[sqlite3_vfs.xAccess]]
1224 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1225 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1226 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1227 ** to test whether a file is at least readable.   The file can be a
1228 ** directory.
1229 **
1230 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1231 ** output buffer xFullPathname.  The exact size of the output buffer
1232 ** is also passed as a parameter to both  methods. If the output buffer
1233 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1234 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1235 ** to prevent this by setting mxPathname to a sufficiently large value.
1236 **
1237 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1238 ** interfaces are not strictly a part of the filesystem, but they are
1239 ** included in the VFS structure for completeness.
1240 ** The xRandomness() function attempts to return nBytes bytes
1241 ** of good-quality randomness into zOut.  The return value is
1242 ** the actual number of bytes of randomness obtained.
1243 ** The xSleep() method causes the calling thread to sleep for at
1244 ** least the number of microseconds given.  ^The xCurrentTime()
1245 ** method returns a Julian Day Number for the current date and time as
1246 ** a floating point value.
1247 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1248 ** Day Number multiplied by 86400000 (the number of milliseconds in
1249 ** a 24-hour day).
1250 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1251 ** date and time if that method is available (if iVersion is 2 or
1252 ** greater and the function pointer is not NULL) and will fall back
1253 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1254 **
1255 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1256 ** are not used by the SQLite core.  These optional interfaces are provided
1257 ** by some VFSes to facilitate testing of the VFS code. By overriding
1258 ** system calls with functions under its control, a test program can
1259 ** simulate faults and error conditions that would otherwise be difficult
1260 ** or impossible to induce.  The set of system calls that can be overridden
1261 ** varies from one VFS to another, and from one version of the same VFS to the
1262 ** next.  Applications that use these interfaces must be prepared for any
1263 ** or all of these interfaces to be NULL or for their behavior to change
1264 ** from one release to the next.  Applications must not attempt to access
1265 ** any of these methods if the iVersion of the VFS is less than 3.
1266 */
1267 typedef struct sqlite3_vfs sqlite3_vfs;
1268 typedef void (*sqlite3_syscall_ptr)(void);
1269 struct sqlite3_vfs {
1270   int iVersion;            /* Structure version number (currently 3) */
1271   int szOsFile;            /* Size of subclassed sqlite3_file */
1272   int mxPathname;          /* Maximum file pathname length */
1273   sqlite3_vfs *pNext;      /* Next registered VFS */
1274   const char *zName;       /* Name of this virtual file system */
1275   void *pAppData;          /* Pointer to application-specific data */
1276   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1277                int flags, int *pOutFlags);
1278   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1279   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1280   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1281   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1282   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1283   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1284   void (*xDlClose)(sqlite3_vfs*, void*);
1285   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1286   int (*xSleep)(sqlite3_vfs*, int microseconds);
1287   int (*xCurrentTime)(sqlite3_vfs*, double*);
1288   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1289   /*
1290   ** The methods above are in version 1 of the sqlite_vfs object
1291   ** definition.  Those that follow are added in version 2 or later
1292   */
1293   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1294   /*
1295   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1296   ** Those below are for version 3 and greater.
1297   */
1298   int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1299   sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1300   const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1301   /*
1302   ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1303   ** New fields may be appended in figure versions.  The iVersion
1304   ** value will increment whenever this happens.
1305   */
1306 };
1307 
1308 /*
1309 ** CAPI3REF: Flags for the xAccess VFS method
1310 **
1311 ** These integer constants can be used as the third parameter to
1312 ** the xAccess method of an [sqlite3_vfs] object.  They determine
1313 ** what kind of permissions the xAccess method is looking for.
1314 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1315 ** simply checks whether the file exists.
1316 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1317 ** checks whether the named directory is both readable and writable
1318 ** (in other words, if files can be added, removed, and renamed within
1319 ** the directory).
1320 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1321 ** [temp_store_directory pragma], though this could change in a future
1322 ** release of SQLite.
1323 ** With SQLITE_ACCESS_READ, the xAccess method
1324 ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1325 ** currently unused, though it might be used in a future release of
1326 ** SQLite.
1327 */
1328 #define SQLITE_ACCESS_EXISTS    0
1329 #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1330 #define SQLITE_ACCESS_READ      2   /* Unused */
1331 
1332 /*
1333 ** CAPI3REF: Flags for the xShmLock VFS method
1334 **
1335 ** These integer constants define the various locking operations
1336 ** allowed by the xShmLock method of [sqlite3_io_methods].  The
1337 ** following are the only legal combinations of flags to the
1338 ** xShmLock method:
1339 **
1340 ** <ul>
1341 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1342 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1343 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1344 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1345 ** </ul>
1346 **
1347 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1348 ** was given no the corresponding lock.
1349 **
1350 ** The xShmLock method can transition between unlocked and SHARED or
1351 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1352 ** and EXCLUSIVE.
1353 */
1354 #define SQLITE_SHM_UNLOCK       1
1355 #define SQLITE_SHM_LOCK         2
1356 #define SQLITE_SHM_SHARED       4
1357 #define SQLITE_SHM_EXCLUSIVE    8
1358 
1359 /*
1360 ** CAPI3REF: Maximum xShmLock index
1361 **
1362 ** The xShmLock method on [sqlite3_io_methods] may use values
1363 ** between 0 and this upper bound as its "offset" argument.
1364 ** The SQLite core will never attempt to acquire or release a
1365 ** lock outside of this range
1366 */
1367 #define SQLITE_SHM_NLOCK        8
1368 
1369 
1370 /*
1371 ** CAPI3REF: Initialize The SQLite Library
1372 **
1373 ** ^The sqlite3_initialize() routine initializes the
1374 ** SQLite library.  ^The sqlite3_shutdown() routine
1375 ** deallocates any resources that were allocated by sqlite3_initialize().
1376 ** These routines are designed to aid in process initialization and
1377 ** shutdown on embedded systems.  Workstation applications using
1378 ** SQLite normally do not need to invoke either of these routines.
1379 **
1380 ** A call to sqlite3_initialize() is an "effective" call if it is
1381 ** the first time sqlite3_initialize() is invoked during the lifetime of
1382 ** the process, or if it is the first time sqlite3_initialize() is invoked
1383 ** following a call to sqlite3_shutdown().  ^(Only an effective call
1384 ** of sqlite3_initialize() does any initialization.  All other calls
1385 ** are harmless no-ops.)^
1386 **
1387 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1388 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1389 ** an effective call to sqlite3_shutdown() does any deinitialization.
1390 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1391 **
1392 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1393 ** is not.  The sqlite3_shutdown() interface must only be called from a
1394 ** single thread.  All open [database connections] must be closed and all
1395 ** other SQLite resources must be deallocated prior to invoking
1396 ** sqlite3_shutdown().
1397 **
1398 ** Among other things, ^sqlite3_initialize() will invoke
1399 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1400 ** will invoke sqlite3_os_end().
1401 **
1402 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1403 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1404 ** the library (perhaps it is unable to allocate a needed resource such
1405 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1406 **
1407 ** ^The sqlite3_initialize() routine is called internally by many other
1408 ** SQLite interfaces so that an application usually does not need to
1409 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1410 ** calls sqlite3_initialize() so the SQLite library will be automatically
1411 ** initialized when [sqlite3_open()] is called if it has not be initialized
1412 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1413 ** compile-time option, then the automatic calls to sqlite3_initialize()
1414 ** are omitted and the application must call sqlite3_initialize() directly
1415 ** prior to using any other SQLite interface.  For maximum portability,
1416 ** it is recommended that applications always invoke sqlite3_initialize()
1417 ** directly prior to using any other SQLite interface.  Future releases
1418 ** of SQLite may require this.  In other words, the behavior exhibited
1419 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1420 ** default behavior in some future release of SQLite.
1421 **
1422 ** The sqlite3_os_init() routine does operating-system specific
1423 ** initialization of the SQLite library.  The sqlite3_os_end()
1424 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1425 ** performed by these routines include allocation or deallocation
1426 ** of static resources, initialization of global variables,
1427 ** setting up a default [sqlite3_vfs] module, or setting up
1428 ** a default configuration using [sqlite3_config()].
1429 **
1430 ** The application should never invoke either sqlite3_os_init()
1431 ** or sqlite3_os_end() directly.  The application should only invoke
1432 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1433 ** interface is called automatically by sqlite3_initialize() and
1434 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1435 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1436 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1437 ** When [custom builds | built for other platforms]
1438 ** (using the [SQLITE_OS_OTHER=1] compile-time
1439 ** option) the application must supply a suitable implementation for
1440 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1441 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1442 ** must return [SQLITE_OK] on success and some other [error code] upon
1443 ** failure.
1444 */
1445 SQLITE_API int sqlite3_initialize(void);
1446 SQLITE_API int sqlite3_shutdown(void);
1447 SQLITE_API int sqlite3_os_init(void);
1448 SQLITE_API int sqlite3_os_end(void);
1449 
1450 /*
1451 ** CAPI3REF: Configuring The SQLite Library
1452 **
1453 ** The sqlite3_config() interface is used to make global configuration
1454 ** changes to SQLite in order to tune SQLite to the specific needs of
1455 ** the application.  The default configuration is recommended for most
1456 ** applications and so this routine is usually not necessary.  It is
1457 ** provided to support rare applications with unusual needs.
1458 **
1459 ** The sqlite3_config() interface is not threadsafe.  The application
1460 ** must insure that no other SQLite interfaces are invoked by other
1461 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1462 ** may only be invoked prior to library initialization using
1463 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1464 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1465 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1466 ** Note, however, that ^sqlite3_config() can be called as part of the
1467 ** implementation of an application-defined [sqlite3_os_init()].
1468 **
1469 ** The first argument to sqlite3_config() is an integer
1470 ** [configuration option] that determines
1471 ** what property of SQLite is to be configured.  Subsequent arguments
1472 ** vary depending on the [configuration option]
1473 ** in the first argument.
1474 **
1475 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1476 ** ^If the option is unknown or SQLite is unable to set the option
1477 ** then this routine returns a non-zero [error code].
1478 */
1479 SQLITE_API int sqlite3_config(int, ...);
1480 
1481 /*
1482 ** CAPI3REF: Configure database connections
1483 **
1484 ** The sqlite3_db_config() interface is used to make configuration
1485 ** changes to a [database connection].  The interface is similar to
1486 ** [sqlite3_config()] except that the changes apply to a single
1487 ** [database connection] (specified in the first argument).
1488 **
1489 ** The second argument to sqlite3_db_config(D,V,...)  is the
1490 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1491 ** that indicates what aspect of the [database connection] is being configured.
1492 ** Subsequent arguments vary depending on the configuration verb.
1493 **
1494 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1495 ** the call is considered successful.
1496 */
1497 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1498 
1499 /*
1500 ** CAPI3REF: Memory Allocation Routines
1501 **
1502 ** An instance of this object defines the interface between SQLite
1503 ** and low-level memory allocation routines.
1504 **
1505 ** This object is used in only one place in the SQLite interface.
1506 ** A pointer to an instance of this object is the argument to
1507 ** [sqlite3_config()] when the configuration option is
1508 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1509 ** By creating an instance of this object
1510 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1511 ** during configuration, an application can specify an alternative
1512 ** memory allocation subsystem for SQLite to use for all of its
1513 ** dynamic memory needs.
1514 **
1515 ** Note that SQLite comes with several [built-in memory allocators]
1516 ** that are perfectly adequate for the overwhelming majority of applications
1517 ** and that this object is only useful to a tiny minority of applications
1518 ** with specialized memory allocation requirements.  This object is
1519 ** also used during testing of SQLite in order to specify an alternative
1520 ** memory allocator that simulates memory out-of-memory conditions in
1521 ** order to verify that SQLite recovers gracefully from such
1522 ** conditions.
1523 **
1524 ** The xMalloc, xRealloc, and xFree methods must work like the
1525 ** malloc(), realloc() and free() functions from the standard C library.
1526 ** ^SQLite guarantees that the second argument to
1527 ** xRealloc is always a value returned by a prior call to xRoundup.
1528 **
1529 ** xSize should return the allocated size of a memory allocation
1530 ** previously obtained from xMalloc or xRealloc.  The allocated size
1531 ** is always at least as big as the requested size but may be larger.
1532 **
1533 ** The xRoundup method returns what would be the allocated size of
1534 ** a memory allocation given a particular requested size.  Most memory
1535 ** allocators round up memory allocations at least to the next multiple
1536 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1537 ** Every memory allocation request coming in through [sqlite3_malloc()]
1538 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
1539 ** that causes the corresponding memory allocation to fail.
1540 **
1541 ** The xInit method initializes the memory allocator.  For example,
1542 ** it might allocate any require mutexes or initialize internal data
1543 ** structures.  The xShutdown method is invoked (indirectly) by
1544 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1545 ** by xInit.  The pAppData pointer is used as the only parameter to
1546 ** xInit and xShutdown.
1547 **
1548 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1549 ** the xInit method, so the xInit method need not be threadsafe.  The
1550 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1551 ** not need to be threadsafe either.  For all other methods, SQLite
1552 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1553 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1554 ** it is by default) and so the methods are automatically serialized.
1555 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1556 ** methods must be threadsafe or else make their own arrangements for
1557 ** serialization.
1558 **
1559 ** SQLite will never invoke xInit() more than once without an intervening
1560 ** call to xShutdown().
1561 */
1562 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1563 struct sqlite3_mem_methods {
1564   void *(*xMalloc)(int);         /* Memory allocation function */
1565   void (*xFree)(void*);          /* Free a prior allocation */
1566   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1567   int (*xSize)(void*);           /* Return the size of an allocation */
1568   int (*xRoundup)(int);          /* Round up request size to allocation size */
1569   int (*xInit)(void*);           /* Initialize the memory allocator */
1570   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1571   void *pAppData;                /* Argument to xInit() and xShutdown() */
1572 };
1573 
1574 /*
1575 ** CAPI3REF: Configuration Options
1576 ** KEYWORDS: {configuration option}
1577 **
1578 ** These constants are the available integer configuration options that
1579 ** can be passed as the first argument to the [sqlite3_config()] interface.
1580 **
1581 ** New configuration options may be added in future releases of SQLite.
1582 ** Existing configuration options might be discontinued.  Applications
1583 ** should check the return code from [sqlite3_config()] to make sure that
1584 ** the call worked.  The [sqlite3_config()] interface will return a
1585 ** non-zero [error code] if a discontinued or unsupported configuration option
1586 ** is invoked.
1587 **
1588 ** <dl>
1589 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1590 ** <dd>There are no arguments to this option.  ^This option sets the
1591 ** [threading mode] to Single-thread.  In other words, it disables
1592 ** all mutexing and puts SQLite into a mode where it can only be used
1593 ** by a single thread.   ^If SQLite is compiled with
1594 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1595 ** it is not possible to change the [threading mode] from its default
1596 ** value of Single-thread and so [sqlite3_config()] will return
1597 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1598 ** configuration option.</dd>
1599 **
1600 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1601 ** <dd>There are no arguments to this option.  ^This option sets the
1602 ** [threading mode] to Multi-thread.  In other words, it disables
1603 ** mutexing on [database connection] and [prepared statement] objects.
1604 ** The application is responsible for serializing access to
1605 ** [database connections] and [prepared statements].  But other mutexes
1606 ** are enabled so that SQLite will be safe to use in a multi-threaded
1607 ** environment as long as no two threads attempt to use the same
1608 ** [database connection] at the same time.  ^If SQLite is compiled with
1609 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1610 ** it is not possible to set the Multi-thread [threading mode] and
1611 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1612 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1613 **
1614 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1615 ** <dd>There are no arguments to this option.  ^This option sets the
1616 ** [threading mode] to Serialized. In other words, this option enables
1617 ** all mutexes including the recursive
1618 ** mutexes on [database connection] and [prepared statement] objects.
1619 ** In this mode (which is the default when SQLite is compiled with
1620 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1621 ** to [database connections] and [prepared statements] so that the
1622 ** application is free to use the same [database connection] or the
1623 ** same [prepared statement] in different threads at the same time.
1624 ** ^If SQLite is compiled with
1625 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1626 ** it is not possible to set the Serialized [threading mode] and
1627 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1628 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1629 **
1630 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
1631 ** <dd> ^(This option takes a single argument which is a pointer to an
1632 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1633 ** alternative low-level memory allocation routines to be used in place of
1634 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1635 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1636 ** before the [sqlite3_config()] call returns.</dd>
1637 **
1638 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
1639 ** <dd> ^(This option takes a single argument which is a pointer to an
1640 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1641 ** structure is filled with the currently defined memory allocation routines.)^
1642 ** This option can be used to overload the default memory allocation
1643 ** routines with a wrapper that simulations memory allocation failure or
1644 ** tracks memory usage, for example. </dd>
1645 **
1646 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1647 ** <dd> ^This option takes single argument of type int, interpreted as a
1648 ** boolean, which enables or disables the collection of memory allocation
1649 ** statistics. ^(When memory allocation statistics are disabled, the
1650 ** following SQLite interfaces become non-operational:
1651 **   <ul>
1652 **   <li> [sqlite3_memory_used()]
1653 **   <li> [sqlite3_memory_highwater()]
1654 **   <li> [sqlite3_soft_heap_limit64()]
1655 **   <li> [sqlite3_status()]
1656 **   </ul>)^
1657 ** ^Memory allocation statistics are enabled by default unless SQLite is
1658 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1659 ** allocation statistics are disabled by default.
1660 ** </dd>
1661 **
1662 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
1663 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1664 ** scratch memory.  There are three arguments:  A pointer an 8-byte
1665 ** aligned memory buffer from which the scratch allocations will be
1666 ** drawn, the size of each scratch allocation (sz),
1667 ** and the maximum number of scratch allocations (N).  The sz
1668 ** argument must be a multiple of 16.
1669 ** The first argument must be a pointer to an 8-byte aligned buffer
1670 ** of at least sz*N bytes of memory.
1671 ** ^SQLite will use no more than two scratch buffers per thread.  So
1672 ** N should be set to twice the expected maximum number of threads.
1673 ** ^SQLite will never require a scratch buffer that is more than 6
1674 ** times the database page size. ^If SQLite needs needs additional
1675 ** scratch memory beyond what is provided by this configuration option, then
1676 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1677 **
1678 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
1679 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1680 ** the database page cache with the default page cache implementation.
1681 ** This configuration should not be used if an application-define page
1682 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
1683 ** There are three arguments to this option: A pointer to 8-byte aligned
1684 ** memory, the size of each page buffer (sz), and the number of pages (N).
1685 ** The sz argument should be the size of the largest database page
1686 ** (a power of two between 512 and 32768) plus a little extra for each
1687 ** page header.  ^The page header size is 20 to 40 bytes depending on
1688 ** the host architecture.  ^It is harmless, apart from the wasted memory,
1689 ** to make sz a little too large.  The first
1690 ** argument should point to an allocation of at least sz*N bytes of memory.
1691 ** ^SQLite will use the memory provided by the first argument to satisfy its
1692 ** memory needs for the first N pages that it adds to cache.  ^If additional
1693 ** page cache memory is needed beyond what is provided by this option, then
1694 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1695 ** The pointer in the first argument must
1696 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1697 ** will be undefined.</dd>
1698 **
1699 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
1700 ** <dd> ^This option specifies a static memory buffer that SQLite will use
1701 ** for all of its dynamic memory allocation needs beyond those provided
1702 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1703 ** There are three arguments: An 8-byte aligned pointer to the memory,
1704 ** the number of bytes in the memory buffer, and the minimum allocation size.
1705 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1706 ** to using its default memory allocator (the system malloc() implementation),
1707 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1708 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1709 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1710 ** allocator is engaged to handle all of SQLites memory allocation needs.
1711 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1712 ** boundary or subsequent behavior of SQLite will be undefined.
1713 ** The minimum allocation size is capped at 2**12. Reasonable values
1714 ** for the minimum allocation size are 2**5 through 2**8.</dd>
1715 **
1716 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
1717 ** <dd> ^(This option takes a single argument which is a pointer to an
1718 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1719 ** alternative low-level mutex routines to be used in place
1720 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
1721 ** content of the [sqlite3_mutex_methods] structure before the call to
1722 ** [sqlite3_config()] returns. ^If SQLite is compiled with
1723 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1724 ** the entire mutexing subsystem is omitted from the build and hence calls to
1725 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1726 ** return [SQLITE_ERROR].</dd>
1727 **
1728 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
1729 ** <dd> ^(This option takes a single argument which is a pointer to an
1730 ** instance of the [sqlite3_mutex_methods] structure.  The
1731 ** [sqlite3_mutex_methods]
1732 ** structure is filled with the currently defined mutex routines.)^
1733 ** This option can be used to overload the default mutex allocation
1734 ** routines with a wrapper used to track mutex usage for performance
1735 ** profiling or testing, for example.   ^If SQLite is compiled with
1736 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1737 ** the entire mutexing subsystem is omitted from the build and hence calls to
1738 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1739 ** return [SQLITE_ERROR].</dd>
1740 **
1741 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1742 ** <dd> ^(This option takes two arguments that determine the default
1743 ** memory allocation for the lookaside memory allocator on each
1744 ** [database connection].  The first argument is the
1745 ** size of each lookaside buffer slot and the second is the number of
1746 ** slots allocated to each database connection.)^  ^(This option sets the
1747 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1748 ** verb to [sqlite3_db_config()] can be used to change the lookaside
1749 ** configuration on individual connections.)^ </dd>
1750 **
1751 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
1752 ** <dd> ^(This option takes a single argument which is a pointer to
1753 ** an [sqlite3_pcache_methods2] object.  This object specifies the interface
1754 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
1755 ** object and uses it for page cache memory allocations.</dd>
1756 **
1757 ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
1758 ** <dd> ^(This option takes a single argument which is a pointer to an
1759 ** [sqlite3_pcache_methods2] object.  SQLite copies of the current
1760 ** page cache implementation into that object.)^ </dd>
1761 **
1762 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
1763 ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
1764 ** global [error log].
1765 ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1766 ** function with a call signature of void(*)(void*,int,const char*),
1767 ** and a pointer to void. ^If the function pointer is not NULL, it is
1768 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
1769 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
1770 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
1771 ** passed through as the first parameter to the application-defined logger
1772 ** function whenever that function is invoked.  ^The second parameter to
1773 ** the logger function is a copy of the first parameter to the corresponding
1774 ** [sqlite3_log()] call and is intended to be a [result code] or an
1775 ** [extended result code].  ^The third parameter passed to the logger is
1776 ** log message after formatting via [sqlite3_snprintf()].
1777 ** The SQLite logging interface is not reentrant; the logger function
1778 ** supplied by the application must not invoke any SQLite interface.
1779 ** In a multi-threaded application, the application-defined logger
1780 ** function must be threadsafe. </dd>
1781 **
1782 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
1783 ** <dd>^(This option takes a single argument of type int. If non-zero, then
1784 ** URI handling is globally enabled. If the parameter is zero, then URI handling
1785 ** is globally disabled.)^ ^If URI handling is globally enabled, all filenames
1786 ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
1787 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
1788 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
1789 ** connection is opened. ^If it is globally disabled, filenames are
1790 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
1791 ** database connection is opened. ^(By default, URI handling is globally
1792 ** disabled. The default value may be changed by compiling with the
1793 ** [SQLITE_USE_URI] symbol defined.)^
1794 **
1795 ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
1796 ** <dd>^This option takes a single integer argument which is interpreted as
1797 ** a boolean in order to enable or disable the use of covering indices for
1798 ** full table scans in the query optimizer.  ^The default setting is determined
1799 ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
1800 ** if that compile-time option is omitted.
1801 ** The ability to disable the use of covering indices for full table scans
1802 ** is because some incorrectly coded legacy applications might malfunction
1803 ** when the optimization is enabled.  Providing the ability to
1804 ** disable the optimization allows the older, buggy application code to work
1805 ** without change even with newer versions of SQLite.
1806 **
1807 ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
1808 ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
1809 ** <dd> These options are obsolete and should not be used by new code.
1810 ** They are retained for backwards compatibility but are now no-ops.
1811 ** </dd>
1812 **
1813 ** [[SQLITE_CONFIG_SQLLOG]]
1814 ** <dt>SQLITE_CONFIG_SQLLOG
1815 ** <dd>This option is only available if sqlite is compiled with the
1816 ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
1817 ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
1818 ** The second should be of type (void*). The callback is invoked by the library
1819 ** in three separate circumstances, identified by the value passed as the
1820 ** fourth parameter. If the fourth parameter is 0, then the database connection
1821 ** passed as the second argument has just been opened. The third argument
1822 ** points to a buffer containing the name of the main database file. If the
1823 ** fourth parameter is 1, then the SQL statement that the third parameter
1824 ** points to has just been executed. Or, if the fourth parameter is 2, then
1825 ** the connection being passed as the second parameter is being closed. The
1826 ** third parameter is passed NULL In this case.  An example of using this
1827 ** configuration option can be seen in the "test_sqllog.c" source file in
1828 ** the canonical SQLite source tree.</dd>
1829 **
1830 ** [[SQLITE_CONFIG_MMAP_SIZE]]
1831 ** <dt>SQLITE_CONFIG_MMAP_SIZE
1832 ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
1833 ** that are the default mmap size limit (the default setting for
1834 ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
1835 ** ^The default setting can be overridden by each database connection using
1836 ** either the [PRAGMA mmap_size] command, or by using the
1837 ** [SQLITE_FCNTL_MMAP_SIZE] file control.  ^(The maximum allowed mmap size
1838 ** cannot be changed at run-time.  Nor may the maximum allowed mmap size
1839 ** exceed the compile-time maximum mmap size set by the
1840 ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
1841 ** ^If either argument to this option is negative, then that argument is
1842 ** changed to its compile-time default.
1843 **
1844 ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
1845 ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
1846 ** <dd>^This option is only available if SQLite is compiled for Windows
1847 ** with the [SQLITE_WIN32_MALLOC] pre-processor macro defined.
1848 ** SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
1849 ** that specifies the maximum size of the created heap.
1850 ** </dl>
1851 */
1852 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1853 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1854 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1855 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1856 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1857 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1858 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
1859 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
1860 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
1861 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
1862 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
1863 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
1864 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
1865 #define SQLITE_CONFIG_PCACHE       14  /* no-op */
1866 #define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
1867 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
1868 #define SQLITE_CONFIG_URI          17  /* int */
1869 #define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
1870 #define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
1871 #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
1872 #define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
1873 #define SQLITE_CONFIG_MMAP_SIZE    22  /* sqlite3_int64, sqlite3_int64 */
1874 #define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */
1875 
1876 /*
1877 ** CAPI3REF: Database Connection Configuration Options
1878 **
1879 ** These constants are the available integer configuration options that
1880 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
1881 **
1882 ** New configuration options may be added in future releases of SQLite.
1883 ** Existing configuration options might be discontinued.  Applications
1884 ** should check the return code from [sqlite3_db_config()] to make sure that
1885 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
1886 ** non-zero [error code] if a discontinued or unsupported configuration option
1887 ** is invoked.
1888 **
1889 ** <dl>
1890 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
1891 ** <dd> ^This option takes three additional arguments that determine the
1892 ** [lookaside memory allocator] configuration for the [database connection].
1893 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
1894 ** pointer to a memory buffer to use for lookaside memory.
1895 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
1896 ** may be NULL in which case SQLite will allocate the
1897 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
1898 ** size of each lookaside buffer slot.  ^The third argument is the number of
1899 ** slots.  The size of the buffer in the first argument must be greater than
1900 ** or equal to the product of the second and third arguments.  The buffer
1901 ** must be aligned to an 8-byte boundary.  ^If the second argument to
1902 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
1903 ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
1904 ** configuration for a database connection can only be changed when that
1905 ** connection is not currently using lookaside memory, or in other words
1906 ** when the "current value" returned by
1907 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
1908 ** Any attempt to change the lookaside memory configuration when lookaside
1909 ** memory is in use leaves the configuration unchanged and returns
1910 ** [SQLITE_BUSY].)^</dd>
1911 **
1912 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
1913 ** <dd> ^This option is used to enable or disable the enforcement of
1914 ** [foreign key constraints].  There should be two additional arguments.
1915 ** The first argument is an integer which is 0 to disable FK enforcement,
1916 ** positive to enable FK enforcement or negative to leave FK enforcement
1917 ** unchanged.  The second parameter is a pointer to an integer into which
1918 ** is written 0 or 1 to indicate whether FK enforcement is off or on
1919 ** following this call.  The second parameter may be a NULL pointer, in
1920 ** which case the FK enforcement setting is not reported back. </dd>
1921 **
1922 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
1923 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
1924 ** There should be two additional arguments.
1925 ** The first argument is an integer which is 0 to disable triggers,
1926 ** positive to enable triggers or negative to leave the setting unchanged.
1927 ** The second parameter is a pointer to an integer into which
1928 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
1929 ** following this call.  The second parameter may be a NULL pointer, in
1930 ** which case the trigger setting is not reported back. </dd>
1931 **
1932 ** </dl>
1933 */
1934 #define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
1935 #define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
1936 #define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
1937 
1938 
1939 /*
1940 ** CAPI3REF: Enable Or Disable Extended Result Codes
1941 **
1942 ** ^The sqlite3_extended_result_codes() routine enables or disables the
1943 ** [extended result codes] feature of SQLite. ^The extended result
1944 ** codes are disabled by default for historical compatibility.
1945 */
1946 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
1947 
1948 /*
1949 ** CAPI3REF: Last Insert Rowid
1950 **
1951 ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
1952 ** has a unique 64-bit signed
1953 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
1954 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
1955 ** names are not also used by explicitly declared columns. ^If
1956 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
1957 ** is another alias for the rowid.
1958 **
1959 ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the
1960 ** most recent successful [INSERT] into a rowid table or [virtual table]
1961 ** on database connection D.
1962 ** ^Inserts into [WITHOUT ROWID] tables are not recorded.
1963 ** ^If no successful [INSERT]s into rowid tables
1964 ** have ever occurred on the database connection D,
1965 ** then sqlite3_last_insert_rowid(D) returns zero.
1966 **
1967 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
1968 ** method, then this routine will return the [rowid] of the inserted
1969 ** row as long as the trigger or virtual table method is running.
1970 ** But once the trigger or virtual table method ends, the value returned
1971 ** by this routine reverts to what it was before the trigger or virtual
1972 ** table method began.)^
1973 **
1974 ** ^An [INSERT] that fails due to a constraint violation is not a
1975 ** successful [INSERT] and does not change the value returned by this
1976 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
1977 ** and INSERT OR ABORT make no changes to the return value of this
1978 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
1979 ** encounters a constraint violation, it does not fail.  The
1980 ** INSERT continues to completion after deleting rows that caused
1981 ** the constraint problem so INSERT OR REPLACE will always change
1982 ** the return value of this interface.)^
1983 **
1984 ** ^For the purposes of this routine, an [INSERT] is considered to
1985 ** be successful even if it is subsequently rolled back.
1986 **
1987 ** This function is accessible to SQL statements via the
1988 ** [last_insert_rowid() SQL function].
1989 **
1990 ** If a separate thread performs a new [INSERT] on the same
1991 ** database connection while the [sqlite3_last_insert_rowid()]
1992 ** function is running and thus changes the last insert [rowid],
1993 ** then the value returned by [sqlite3_last_insert_rowid()] is
1994 ** unpredictable and might not equal either the old or the new
1995 ** last insert [rowid].
1996 */
1997 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
1998 
1999 /*
2000 ** CAPI3REF: Count The Number Of Rows Modified
2001 **
2002 ** ^This function returns the number of database rows that were changed
2003 ** or inserted or deleted by the most recently completed SQL statement
2004 ** on the [database connection] specified by the first parameter.
2005 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2006 ** or [DELETE] statement are counted.  Auxiliary changes caused by
2007 ** triggers or [foreign key actions] are not counted.)^ Use the
2008 ** [sqlite3_total_changes()] function to find the total number of changes
2009 ** including changes caused by triggers and foreign key actions.
2010 **
2011 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2012 ** are not counted.  Only real table changes are counted.
2013 **
2014 ** ^(A "row change" is a change to a single row of a single table
2015 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2016 ** are changed as side effects of [REPLACE] constraint resolution,
2017 ** rollback, ABORT processing, [DROP TABLE], or by any other
2018 ** mechanisms do not count as direct row changes.)^
2019 **
2020 ** A "trigger context" is a scope of execution that begins and
2021 ** ends with the script of a [CREATE TRIGGER | trigger].
2022 ** Most SQL statements are
2023 ** evaluated outside of any trigger.  This is the "top level"
2024 ** trigger context.  If a trigger fires from the top level, a
2025 ** new trigger context is entered for the duration of that one
2026 ** trigger.  Subtriggers create subcontexts for their duration.
2027 **
2028 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2029 ** not create a new trigger context.
2030 **
2031 ** ^This function returns the number of direct row changes in the
2032 ** most recent INSERT, UPDATE, or DELETE statement within the same
2033 ** trigger context.
2034 **
2035 ** ^Thus, when called from the top level, this function returns the
2036 ** number of changes in the most recent INSERT, UPDATE, or DELETE
2037 ** that also occurred at the top level.  ^(Within the body of a trigger,
2038 ** the sqlite3_changes() interface can be called to find the number of
2039 ** changes in the most recently completed INSERT, UPDATE, or DELETE
2040 ** statement within the body of the same trigger.
2041 ** However, the number returned does not include changes
2042 ** caused by subtriggers since those have their own context.)^
2043 **
2044 ** See also the [sqlite3_total_changes()] interface, the
2045 ** [count_changes pragma], and the [changes() SQL function].
2046 **
2047 ** If a separate thread makes changes on the same database connection
2048 ** while [sqlite3_changes()] is running then the value returned
2049 ** is unpredictable and not meaningful.
2050 */
2051 SQLITE_API int sqlite3_changes(sqlite3*);
2052 
2053 /*
2054 ** CAPI3REF: Total Number Of Rows Modified
2055 **
2056 ** ^This function returns the number of row changes caused by [INSERT],
2057 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2058 ** ^(The count returned by sqlite3_total_changes() includes all changes
2059 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
2060 ** [foreign key actions]. However,
2061 ** the count does not include changes used to implement [REPLACE] constraints,
2062 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2063 ** count does not include rows of views that fire an [INSTEAD OF trigger],
2064 ** though if the INSTEAD OF trigger makes changes of its own, those changes
2065 ** are counted.)^
2066 ** ^The sqlite3_total_changes() function counts the changes as soon as
2067 ** the statement that makes them is completed (when the statement handle
2068 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2069 **
2070 ** See also the [sqlite3_changes()] interface, the
2071 ** [count_changes pragma], and the [total_changes() SQL function].
2072 **
2073 ** If a separate thread makes changes on the same database connection
2074 ** while [sqlite3_total_changes()] is running then the value
2075 ** returned is unpredictable and not meaningful.
2076 */
2077 SQLITE_API int sqlite3_total_changes(sqlite3*);
2078 
2079 /*
2080 ** CAPI3REF: Interrupt A Long-Running Query
2081 **
2082 ** ^This function causes any pending database operation to abort and
2083 ** return at its earliest opportunity. This routine is typically
2084 ** called in response to a user action such as pressing "Cancel"
2085 ** or Ctrl-C where the user wants a long query operation to halt
2086 ** immediately.
2087 **
2088 ** ^It is safe to call this routine from a thread different from the
2089 ** thread that is currently running the database operation.  But it
2090 ** is not safe to call this routine with a [database connection] that
2091 ** is closed or might close before sqlite3_interrupt() returns.
2092 **
2093 ** ^If an SQL operation is very nearly finished at the time when
2094 ** sqlite3_interrupt() is called, then it might not have an opportunity
2095 ** to be interrupted and might continue to completion.
2096 **
2097 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2098 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2099 ** that is inside an explicit transaction, then the entire transaction
2100 ** will be rolled back automatically.
2101 **
2102 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2103 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
2104 ** that are started after the sqlite3_interrupt() call and before the
2105 ** running statements reaches zero are interrupted as if they had been
2106 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2107 ** that are started after the running statement count reaches zero are
2108 ** not effected by the sqlite3_interrupt().
2109 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2110 ** SQL statements is a no-op and has no effect on SQL statements
2111 ** that are started after the sqlite3_interrupt() call returns.
2112 **
2113 ** If the database connection closes while [sqlite3_interrupt()]
2114 ** is running then bad things will likely happen.
2115 */
2116 SQLITE_API void sqlite3_interrupt(sqlite3*);
2117 
2118 /*
2119 ** CAPI3REF: Determine If An SQL Statement Is Complete
2120 **
2121 ** These routines are useful during command-line input to determine if the
2122 ** currently entered text seems to form a complete SQL statement or
2123 ** if additional input is needed before sending the text into
2124 ** SQLite for parsing.  ^These routines return 1 if the input string
2125 ** appears to be a complete SQL statement.  ^A statement is judged to be
2126 ** complete if it ends with a semicolon token and is not a prefix of a
2127 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2128 ** string literals or quoted identifier names or comments are not
2129 ** independent tokens (they are part of the token in which they are
2130 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
2131 ** and comments that follow the final semicolon are ignored.
2132 **
2133 ** ^These routines return 0 if the statement is incomplete.  ^If a
2134 ** memory allocation fails, then SQLITE_NOMEM is returned.
2135 **
2136 ** ^These routines do not parse the SQL statements thus
2137 ** will not detect syntactically incorrect SQL.
2138 **
2139 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2140 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2141 ** automatically by sqlite3_complete16().  If that initialization fails,
2142 ** then the return value from sqlite3_complete16() will be non-zero
2143 ** regardless of whether or not the input SQL is complete.)^
2144 **
2145 ** The input to [sqlite3_complete()] must be a zero-terminated
2146 ** UTF-8 string.
2147 **
2148 ** The input to [sqlite3_complete16()] must be a zero-terminated
2149 ** UTF-16 string in native byte order.
2150 */
2151 SQLITE_API int sqlite3_complete(const char *sql);
2152 SQLITE_API int sqlite3_complete16(const void *sql);
2153 
2154 /*
2155 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2156 **
2157 ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
2158 ** that might be invoked with argument P whenever
2159 ** an attempt is made to access a database table associated with
2160 ** [database connection] D when another thread
2161 ** or process has the table locked.
2162 ** The sqlite3_busy_handler() interface is used to implement
2163 ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
2164 **
2165 ** ^If the busy callback is NULL, then [SQLITE_BUSY]
2166 ** is returned immediately upon encountering the lock.  ^If the busy callback
2167 ** is not NULL, then the callback might be invoked with two arguments.
2168 **
2169 ** ^The first argument to the busy handler is a copy of the void* pointer which
2170 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
2171 ** the busy handler callback is the number of times that the busy handler has
2172 ** been invoked for the same locking event.  ^If the
2173 ** busy callback returns 0, then no additional attempts are made to
2174 ** access the database and [SQLITE_BUSY] is returned
2175 ** to the application.
2176 ** ^If the callback returns non-zero, then another attempt
2177 ** is made to access the database and the cycle repeats.
2178 **
2179 ** The presence of a busy handler does not guarantee that it will be invoked
2180 ** when there is lock contention. ^If SQLite determines that invoking the busy
2181 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2182 ** to the application instead of invoking the
2183 ** busy handler.
2184 ** Consider a scenario where one process is holding a read lock that
2185 ** it is trying to promote to a reserved lock and
2186 ** a second process is holding a reserved lock that it is trying
2187 ** to promote to an exclusive lock.  The first process cannot proceed
2188 ** because it is blocked by the second and the second process cannot
2189 ** proceed because it is blocked by the first.  If both processes
2190 ** invoke the busy handlers, neither will make any progress.  Therefore,
2191 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2192 ** will induce the first process to release its read lock and allow
2193 ** the second process to proceed.
2194 **
2195 ** ^The default busy callback is NULL.
2196 **
2197 ** ^(There can only be a single busy handler defined for each
2198 ** [database connection].  Setting a new busy handler clears any
2199 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2200 ** or evaluating [PRAGMA busy_timeout=N] will change the
2201 ** busy handler and thus clear any previously set busy handler.
2202 **
2203 ** The busy callback should not take any actions which modify the
2204 ** database connection that invoked the busy handler.  In other words,
2205 ** the busy handler is not reentrant.  Any such actions
2206 ** result in undefined behavior.
2207 **
2208 ** A busy handler must not close the database connection
2209 ** or [prepared statement] that invoked the busy handler.
2210 */
2211 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2212 
2213 /*
2214 ** CAPI3REF: Set A Busy Timeout
2215 **
2216 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2217 ** for a specified amount of time when a table is locked.  ^The handler
2218 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2219 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2220 ** the handler returns 0 which causes [sqlite3_step()] to return
2221 ** [SQLITE_BUSY].
2222 **
2223 ** ^Calling this routine with an argument less than or equal to zero
2224 ** turns off all busy handlers.
2225 **
2226 ** ^(There can only be a single busy handler for a particular
2227 ** [database connection] at any given moment.  If another busy handler
2228 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2229 ** this routine, that other busy handler is cleared.)^
2230 **
2231 ** See also:  [PRAGMA busy_timeout]
2232 */
2233 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2234 
2235 /*
2236 ** CAPI3REF: Convenience Routines For Running Queries
2237 **
2238 ** This is a legacy interface that is preserved for backwards compatibility.
2239 ** Use of this interface is not recommended.
2240 **
2241 ** Definition: A <b>result table</b> is memory data structure created by the
2242 ** [sqlite3_get_table()] interface.  A result table records the
2243 ** complete query results from one or more queries.
2244 **
2245 ** The table conceptually has a number of rows and columns.  But
2246 ** these numbers are not part of the result table itself.  These
2247 ** numbers are obtained separately.  Let N be the number of rows
2248 ** and M be the number of columns.
2249 **
2250 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2251 ** There are (N+1)*M elements in the array.  The first M pointers point
2252 ** to zero-terminated strings that  contain the names of the columns.
2253 ** The remaining entries all point to query results.  NULL values result
2254 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2255 ** string representation as returned by [sqlite3_column_text()].
2256 **
2257 ** A result table might consist of one or more memory allocations.
2258 ** It is not safe to pass a result table directly to [sqlite3_free()].
2259 ** A result table should be deallocated using [sqlite3_free_table()].
2260 **
2261 ** ^(As an example of the result table format, suppose a query result
2262 ** is as follows:
2263 **
2264 ** <blockquote><pre>
2265 **        Name        | Age
2266 **        -----------------------
2267 **        Alice       | 43
2268 **        Bob         | 28
2269 **        Cindy       | 21
2270 ** </pre></blockquote>
2271 **
2272 ** There are two column (M==2) and three rows (N==3).  Thus the
2273 ** result table has 8 entries.  Suppose the result table is stored
2274 ** in an array names azResult.  Then azResult holds this content:
2275 **
2276 ** <blockquote><pre>
2277 **        azResult&#91;0] = "Name";
2278 **        azResult&#91;1] = "Age";
2279 **        azResult&#91;2] = "Alice";
2280 **        azResult&#91;3] = "43";
2281 **        azResult&#91;4] = "Bob";
2282 **        azResult&#91;5] = "28";
2283 **        azResult&#91;6] = "Cindy";
2284 **        azResult&#91;7] = "21";
2285 ** </pre></blockquote>)^
2286 **
2287 ** ^The sqlite3_get_table() function evaluates one or more
2288 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2289 ** string of its 2nd parameter and returns a result table to the
2290 ** pointer given in its 3rd parameter.
2291 **
2292 ** After the application has finished with the result from sqlite3_get_table(),
2293 ** it must pass the result table pointer to sqlite3_free_table() in order to
2294 ** release the memory that was malloced.  Because of the way the
2295 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2296 ** function must not try to call [sqlite3_free()] directly.  Only
2297 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2298 **
2299 ** The sqlite3_get_table() interface is implemented as a wrapper around
2300 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2301 ** to any internal data structures of SQLite.  It uses only the public
2302 ** interface defined here.  As a consequence, errors that occur in the
2303 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2304 ** reflected in subsequent calls to [sqlite3_errcode()] or
2305 ** [sqlite3_errmsg()].
2306 */
2307 SQLITE_API int sqlite3_get_table(
2308   sqlite3 *db,          /* An open database */
2309   const char *zSql,     /* SQL to be evaluated */
2310   char ***pazResult,    /* Results of the query */
2311   int *pnRow,           /* Number of result rows written here */
2312   int *pnColumn,        /* Number of result columns written here */
2313   char **pzErrmsg       /* Error msg written here */
2314 );
2315 SQLITE_API void sqlite3_free_table(char **result);
2316 
2317 /*
2318 ** CAPI3REF: Formatted String Printing Functions
2319 **
2320 ** These routines are work-alikes of the "printf()" family of functions
2321 ** from the standard C library.
2322 **
2323 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2324 ** results into memory obtained from [sqlite3_malloc()].
2325 ** The strings returned by these two routines should be
2326 ** released by [sqlite3_free()].  ^Both routines return a
2327 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2328 ** memory to hold the resulting string.
2329 **
2330 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2331 ** the standard C library.  The result is written into the
2332 ** buffer supplied as the second parameter whose size is given by
2333 ** the first parameter. Note that the order of the
2334 ** first two parameters is reversed from snprintf().)^  This is an
2335 ** historical accident that cannot be fixed without breaking
2336 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2337 ** returns a pointer to its buffer instead of the number of
2338 ** characters actually written into the buffer.)^  We admit that
2339 ** the number of characters written would be a more useful return
2340 ** value but we cannot change the implementation of sqlite3_snprintf()
2341 ** now without breaking compatibility.
2342 **
2343 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2344 ** guarantees that the buffer is always zero-terminated.  ^The first
2345 ** parameter "n" is the total size of the buffer, including space for
2346 ** the zero terminator.  So the longest string that can be completely
2347 ** written will be n-1 characters.
2348 **
2349 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2350 **
2351 ** These routines all implement some additional formatting
2352 ** options that are useful for constructing SQL statements.
2353 ** All of the usual printf() formatting options apply.  In addition, there
2354 ** is are "%q", "%Q", and "%z" options.
2355 **
2356 ** ^(The %q option works like %s in that it substitutes a nul-terminated
2357 ** string from the argument list.  But %q also doubles every '\'' character.
2358 ** %q is designed for use inside a string literal.)^  By doubling each '\''
2359 ** character it escapes that character and allows it to be inserted into
2360 ** the string.
2361 **
2362 ** For example, assume the string variable zText contains text as follows:
2363 **
2364 ** <blockquote><pre>
2365 **  char *zText = "It's a happy day!";
2366 ** </pre></blockquote>
2367 **
2368 ** One can use this text in an SQL statement as follows:
2369 **
2370 ** <blockquote><pre>
2371 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2372 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2373 **  sqlite3_free(zSQL);
2374 ** </pre></blockquote>
2375 **
2376 ** Because the %q format string is used, the '\'' character in zText
2377 ** is escaped and the SQL generated is as follows:
2378 **
2379 ** <blockquote><pre>
2380 **  INSERT INTO table1 VALUES('It''s a happy day!')
2381 ** </pre></blockquote>
2382 **
2383 ** This is correct.  Had we used %s instead of %q, the generated SQL
2384 ** would have looked like this:
2385 **
2386 ** <blockquote><pre>
2387 **  INSERT INTO table1 VALUES('It's a happy day!');
2388 ** </pre></blockquote>
2389 **
2390 ** This second example is an SQL syntax error.  As a general rule you should
2391 ** always use %q instead of %s when inserting text into a string literal.
2392 **
2393 ** ^(The %Q option works like %q except it also adds single quotes around
2394 ** the outside of the total string.  Additionally, if the parameter in the
2395 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2396 ** single quotes).)^  So, for example, one could say:
2397 **
2398 ** <blockquote><pre>
2399 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2400 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2401 **  sqlite3_free(zSQL);
2402 ** </pre></blockquote>
2403 **
2404 ** The code above will render a correct SQL statement in the zSQL
2405 ** variable even if the zText variable is a NULL pointer.
2406 **
2407 ** ^(The "%z" formatting option works like "%s" but with the
2408 ** addition that after the string has been read and copied into
2409 ** the result, [sqlite3_free()] is called on the input string.)^
2410 */
2411 SQLITE_API char *sqlite3_mprintf(const char*,...);
2412 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2413 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2414 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2415 
2416 /*
2417 ** CAPI3REF: Memory Allocation Subsystem
2418 **
2419 ** The SQLite core uses these three routines for all of its own
2420 ** internal memory allocation needs. "Core" in the previous sentence
2421 ** does not include operating-system specific VFS implementation.  The
2422 ** Windows VFS uses native malloc() and free() for some operations.
2423 **
2424 ** ^The sqlite3_malloc() routine returns a pointer to a block
2425 ** of memory at least N bytes in length, where N is the parameter.
2426 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2427 ** memory, it returns a NULL pointer.  ^If the parameter N to
2428 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2429 ** a NULL pointer.
2430 **
2431 ** ^The sqlite3_malloc64(N) routine works just like
2432 ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
2433 ** of a signed 32-bit integer.
2434 **
2435 ** ^Calling sqlite3_free() with a pointer previously returned
2436 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2437 ** that it might be reused.  ^The sqlite3_free() routine is
2438 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2439 ** to sqlite3_free() is harmless.  After being freed, memory
2440 ** should neither be read nor written.  Even reading previously freed
2441 ** memory might result in a segmentation fault or other severe error.
2442 ** Memory corruption, a segmentation fault, or other severe error
2443 ** might result if sqlite3_free() is called with a non-NULL pointer that
2444 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2445 **
2446 ** ^The sqlite3_realloc(X,N) interface attempts to resize a
2447 ** prior memory allocation X to be at least N bytes.
2448 ** ^If the X parameter to sqlite3_realloc(X,N)
2449 ** is a NULL pointer then its behavior is identical to calling
2450 ** sqlite3_malloc(N).
2451 ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
2452 ** negative then the behavior is exactly the same as calling
2453 ** sqlite3_free(X).
2454 ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
2455 ** of at least N bytes in size or NULL if insufficient memory is available.
2456 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2457 ** of the prior allocation are copied into the beginning of buffer returned
2458 ** by sqlite3_realloc(X,N) and the prior allocation is freed.
2459 ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
2460 ** prior allocation is not freed.
2461 **
2462 ** ^The sqlite3_realloc64(X,N) interfaces works the same as
2463 ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
2464 ** of a 32-bit signed integer.
2465 **
2466 ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
2467 ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
2468 ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
2469 ** ^The value returned by sqlite3_msize(X) might be larger than the number
2470 ** of bytes requested when X was allocated.  ^If X is a NULL pointer then
2471 ** sqlite3_msize(X) returns zero.  If X points to something that is not
2472 ** the beginning of memory allocation, or if it points to a formerly
2473 ** valid memory allocation that has now been freed, then the behavior
2474 ** of sqlite3_msize(X) is undefined and possibly harmful.
2475 **
2476 ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
2477 ** sqlite3_malloc64(), and sqlite3_realloc64()
2478 ** is always aligned to at least an 8 byte boundary, or to a
2479 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2480 ** option is used.
2481 **
2482 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2483 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2484 ** implementation of these routines to be omitted.  That capability
2485 ** is no longer provided.  Only built-in memory allocators can be used.
2486 **
2487 ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
2488 ** the system malloc() and free() directly when converting
2489 ** filenames between the UTF-8 encoding used by SQLite
2490 ** and whatever filename encoding is used by the particular Windows
2491 ** installation.  Memory allocation errors were detected, but
2492 ** they were reported back as [SQLITE_CANTOPEN] or
2493 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2494 **
2495 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2496 ** must be either NULL or else pointers obtained from a prior
2497 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2498 ** not yet been released.
2499 **
2500 ** The application must not read or write any part of
2501 ** a block of memory after it has been released using
2502 ** [sqlite3_free()] or [sqlite3_realloc()].
2503 */
2504 SQLITE_API void *sqlite3_malloc(int);
2505 SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
2506 SQLITE_API void *sqlite3_realloc(void*, int);
2507 SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
2508 SQLITE_API void sqlite3_free(void*);
2509 SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
2510 
2511 /*
2512 ** CAPI3REF: Memory Allocator Statistics
2513 **
2514 ** SQLite provides these two interfaces for reporting on the status
2515 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2516 ** routines, which form the built-in memory allocation subsystem.
2517 **
2518 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2519 ** of memory currently outstanding (malloced but not freed).
2520 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2521 ** value of [sqlite3_memory_used()] since the high-water mark
2522 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2523 ** [sqlite3_memory_highwater()] include any overhead
2524 ** added by SQLite in its implementation of [sqlite3_malloc()],
2525 ** but not overhead added by the any underlying system library
2526 ** routines that [sqlite3_malloc()] may call.
2527 **
2528 ** ^The memory high-water mark is reset to the current value of
2529 ** [sqlite3_memory_used()] if and only if the parameter to
2530 ** [sqlite3_memory_highwater()] is true.  ^The value returned
2531 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2532 ** prior to the reset.
2533 */
2534 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2535 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2536 
2537 /*
2538 ** CAPI3REF: Pseudo-Random Number Generator
2539 **
2540 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2541 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2542 ** already uses the largest possible [ROWID].  The PRNG is also used for
2543 ** the build-in random() and randomblob() SQL functions.  This interface allows
2544 ** applications to access the same PRNG for other purposes.
2545 **
2546 ** ^A call to this routine stores N bytes of randomness into buffer P.
2547 ** ^If N is less than one, then P can be a NULL pointer.
2548 **
2549 ** ^If this routine has not been previously called or if the previous
2550 ** call had N less than one, then the PRNG is seeded using randomness
2551 ** obtained from the xRandomness method of the default [sqlite3_vfs] object.
2552 ** ^If the previous call to this routine had an N of 1 or more then
2553 ** the pseudo-randomness is generated
2554 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2555 ** method.
2556 */
2557 SQLITE_API void sqlite3_randomness(int N, void *P);
2558 
2559 /*
2560 ** CAPI3REF: Compile-Time Authorization Callbacks
2561 **
2562 ** ^This routine registers an authorizer callback with a particular
2563 ** [database connection], supplied in the first argument.
2564 ** ^The authorizer callback is invoked as SQL statements are being compiled
2565 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2566 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2567 ** points during the compilation process, as logic is being created
2568 ** to perform various actions, the authorizer callback is invoked to
2569 ** see if those actions are allowed.  ^The authorizer callback should
2570 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2571 ** specific action but allow the SQL statement to continue to be
2572 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2573 ** rejected with an error.  ^If the authorizer callback returns
2574 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2575 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2576 ** the authorizer will fail with an error message.
2577 **
2578 ** When the callback returns [SQLITE_OK], that means the operation
2579 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2580 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2581 ** authorizer will fail with an error message explaining that
2582 ** access is denied.
2583 **
2584 ** ^The first parameter to the authorizer callback is a copy of the third
2585 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2586 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2587 ** the particular action to be authorized. ^The third through sixth parameters
2588 ** to the callback are zero-terminated strings that contain additional
2589 ** details about the action to be authorized.
2590 **
2591 ** ^If the action code is [SQLITE_READ]
2592 ** and the callback returns [SQLITE_IGNORE] then the
2593 ** [prepared statement] statement is constructed to substitute
2594 ** a NULL value in place of the table column that would have
2595 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2596 ** return can be used to deny an untrusted user access to individual
2597 ** columns of a table.
2598 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2599 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2600 ** [truncate optimization] is disabled and all rows are deleted individually.
2601 **
2602 ** An authorizer is used when [sqlite3_prepare | preparing]
2603 ** SQL statements from an untrusted source, to ensure that the SQL statements
2604 ** do not try to access data they are not allowed to see, or that they do not
2605 ** try to execute malicious statements that damage the database.  For
2606 ** example, an application may allow a user to enter arbitrary
2607 ** SQL queries for evaluation by a database.  But the application does
2608 ** not want the user to be able to make arbitrary changes to the
2609 ** database.  An authorizer could then be put in place while the
2610 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2611 ** disallows everything except [SELECT] statements.
2612 **
2613 ** Applications that need to process SQL from untrusted sources
2614 ** might also consider lowering resource limits using [sqlite3_limit()]
2615 ** and limiting database size using the [max_page_count] [PRAGMA]
2616 ** in addition to using an authorizer.
2617 **
2618 ** ^(Only a single authorizer can be in place on a database connection
2619 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2620 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2621 ** The authorizer is disabled by default.
2622 **
2623 ** The authorizer callback must not do anything that will modify
2624 ** the database connection that invoked the authorizer callback.
2625 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2626 ** database connections for the meaning of "modify" in this paragraph.
2627 **
2628 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2629 ** statement might be re-prepared during [sqlite3_step()] due to a
2630 ** schema change.  Hence, the application should ensure that the
2631 ** correct authorizer callback remains in place during the [sqlite3_step()].
2632 **
2633 ** ^Note that the authorizer callback is invoked only during
2634 ** [sqlite3_prepare()] or its variants.  Authorization is not
2635 ** performed during statement evaluation in [sqlite3_step()], unless
2636 ** as stated in the previous paragraph, sqlite3_step() invokes
2637 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2638 */
2639 SQLITE_API int sqlite3_set_authorizer(
2640   sqlite3*,
2641   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2642   void *pUserData
2643 );
2644 
2645 /*
2646 ** CAPI3REF: Authorizer Return Codes
2647 **
2648 ** The [sqlite3_set_authorizer | authorizer callback function] must
2649 ** return either [SQLITE_OK] or one of these two constants in order
2650 ** to signal SQLite whether or not the action is permitted.  See the
2651 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2652 ** information.
2653 **
2654 ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
2655 ** returned from the [sqlite3_vtab_on_conflict()] interface.
2656 */
2657 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2658 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2659 
2660 /*
2661 ** CAPI3REF: Authorizer Action Codes
2662 **
2663 ** The [sqlite3_set_authorizer()] interface registers a callback function
2664 ** that is invoked to authorize certain SQL statement actions.  The
2665 ** second parameter to the callback is an integer code that specifies
2666 ** what action is being authorized.  These are the integer action codes that
2667 ** the authorizer callback may be passed.
2668 **
2669 ** These action code values signify what kind of operation is to be
2670 ** authorized.  The 3rd and 4th parameters to the authorization
2671 ** callback function will be parameters or NULL depending on which of these
2672 ** codes is used as the second parameter.  ^(The 5th parameter to the
2673 ** authorizer callback is the name of the database ("main", "temp",
2674 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2675 ** is the name of the inner-most trigger or view that is responsible for
2676 ** the access attempt or NULL if this access attempt is directly from
2677 ** top-level SQL code.
2678 */
2679 /******************************************* 3rd ************ 4th ***********/
2680 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2681 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2682 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2683 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2684 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2685 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2686 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2687 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2688 #define SQLITE_DELETE                9   /* Table Name      NULL            */
2689 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2690 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2691 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2692 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2693 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2694 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2695 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2696 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2697 #define SQLITE_INSERT               18   /* Table Name      NULL            */
2698 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2699 #define SQLITE_READ                 20   /* Table Name      Column Name     */
2700 #define SQLITE_SELECT               21   /* NULL            NULL            */
2701 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2702 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2703 #define SQLITE_ATTACH               24   /* Filename        NULL            */
2704 #define SQLITE_DETACH               25   /* Database Name   NULL            */
2705 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2706 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
2707 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2708 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2709 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2710 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2711 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2712 #define SQLITE_COPY                  0   /* No longer used */
2713 #define SQLITE_RECURSIVE            33   /* NULL            NULL            */
2714 
2715 /*
2716 ** CAPI3REF: Tracing And Profiling Functions
2717 **
2718 ** These routines register callback functions that can be used for
2719 ** tracing and profiling the execution of SQL statements.
2720 **
2721 ** ^The callback function registered by sqlite3_trace() is invoked at
2722 ** various times when an SQL statement is being run by [sqlite3_step()].
2723 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2724 ** SQL statement text as the statement first begins executing.
2725 ** ^(Additional sqlite3_trace() callbacks might occur
2726 ** as each triggered subprogram is entered.  The callbacks for triggers
2727 ** contain a UTF-8 SQL comment that identifies the trigger.)^
2728 **
2729 ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
2730 ** the length of [bound parameter] expansion in the output of sqlite3_trace().
2731 **
2732 ** ^The callback function registered by sqlite3_profile() is invoked
2733 ** as each SQL statement finishes.  ^The profile callback contains
2734 ** the original statement text and an estimate of wall-clock time
2735 ** of how long that statement took to run.  ^The profile callback
2736 ** time is in units of nanoseconds, however the current implementation
2737 ** is only capable of millisecond resolution so the six least significant
2738 ** digits in the time are meaningless.  Future versions of SQLite
2739 ** might provide greater resolution on the profiler callback.  The
2740 ** sqlite3_profile() function is considered experimental and is
2741 ** subject to change in future versions of SQLite.
2742 */
2743 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2744 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2745    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2746 
2747 /*
2748 ** CAPI3REF: Query Progress Callbacks
2749 **
2750 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2751 ** function X to be invoked periodically during long running calls to
2752 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2753 ** database connection D.  An example use for this
2754 ** interface is to keep a GUI updated during a large query.
2755 **
2756 ** ^The parameter P is passed through as the only parameter to the
2757 ** callback function X.  ^The parameter N is the approximate number of
2758 ** [virtual machine instructions] that are evaluated between successive
2759 ** invocations of the callback X.  ^If N is less than one then the progress
2760 ** handler is disabled.
2761 **
2762 ** ^Only a single progress handler may be defined at one time per
2763 ** [database connection]; setting a new progress handler cancels the
2764 ** old one.  ^Setting parameter X to NULL disables the progress handler.
2765 ** ^The progress handler is also disabled by setting N to a value less
2766 ** than 1.
2767 **
2768 ** ^If the progress callback returns non-zero, the operation is
2769 ** interrupted.  This feature can be used to implement a
2770 ** "Cancel" button on a GUI progress dialog box.
2771 **
2772 ** The progress handler callback must not do anything that will modify
2773 ** the database connection that invoked the progress handler.
2774 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2775 ** database connections for the meaning of "modify" in this paragraph.
2776 **
2777 */
2778 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2779 
2780 /*
2781 ** CAPI3REF: Opening A New Database Connection
2782 **
2783 ** ^These routines open an SQLite database file as specified by the
2784 ** filename argument. ^The filename argument is interpreted as UTF-8 for
2785 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2786 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
2787 ** returned in *ppDb, even if an error occurs.  The only exception is that
2788 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2789 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2790 ** object.)^ ^(If the database is opened (and/or created) successfully, then
2791 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2792 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2793 ** an English language description of the error following a failure of any
2794 ** of the sqlite3_open() routines.
2795 **
2796 ** ^The default encoding will be UTF-8 for databases created using
2797 ** sqlite3_open() or sqlite3_open_v2().  ^The default encoding for databases
2798 ** created using sqlite3_open16() will be UTF-16 in the native byte order.
2799 **
2800 ** Whether or not an error occurs when it is opened, resources
2801 ** associated with the [database connection] handle should be released by
2802 ** passing it to [sqlite3_close()] when it is no longer required.
2803 **
2804 ** The sqlite3_open_v2() interface works like sqlite3_open()
2805 ** except that it accepts two additional parameters for additional control
2806 ** over the new database connection.  ^(The flags parameter to
2807 ** sqlite3_open_v2() can take one of
2808 ** the following three values, optionally combined with the
2809 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2810 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
2811 **
2812 ** <dl>
2813 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2814 ** <dd>The database is opened in read-only mode.  If the database does not
2815 ** already exist, an error is returned.</dd>)^
2816 **
2817 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2818 ** <dd>The database is opened for reading and writing if possible, or reading
2819 ** only if the file is write protected by the operating system.  In either
2820 ** case the database must already exist, otherwise an error is returned.</dd>)^
2821 **
2822 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2823 ** <dd>The database is opened for reading and writing, and is created if
2824 ** it does not already exist. This is the behavior that is always used for
2825 ** sqlite3_open() and sqlite3_open16().</dd>)^
2826 ** </dl>
2827 **
2828 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2829 ** combinations shown above optionally combined with other
2830 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
2831 ** then the behavior is undefined.
2832 **
2833 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2834 ** opens in the multi-thread [threading mode] as long as the single-thread
2835 ** mode has not been set at compile-time or start-time.  ^If the
2836 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2837 ** in the serialized [threading mode] unless single-thread was
2838 ** previously selected at compile-time or start-time.
2839 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2840 ** eligible to use [shared cache mode], regardless of whether or not shared
2841 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
2842 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2843 ** participate in [shared cache mode] even if it is enabled.
2844 **
2845 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
2846 ** [sqlite3_vfs] object that defines the operating system interface that
2847 ** the new database connection should use.  ^If the fourth parameter is
2848 ** a NULL pointer then the default [sqlite3_vfs] object is used.
2849 **
2850 ** ^If the filename is ":memory:", then a private, temporary in-memory database
2851 ** is created for the connection.  ^This in-memory database will vanish when
2852 ** the database connection is closed.  Future versions of SQLite might
2853 ** make use of additional special filenames that begin with the ":" character.
2854 ** It is recommended that when a database filename actually does begin with
2855 ** a ":" character you should prefix the filename with a pathname such as
2856 ** "./" to avoid ambiguity.
2857 **
2858 ** ^If the filename is an empty string, then a private, temporary
2859 ** on-disk database will be created.  ^This private database will be
2860 ** automatically deleted as soon as the database connection is closed.
2861 **
2862 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
2863 **
2864 ** ^If [URI filename] interpretation is enabled, and the filename argument
2865 ** begins with "file:", then the filename is interpreted as a URI. ^URI
2866 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
2867 ** set in the fourth argument to sqlite3_open_v2(), or if it has
2868 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
2869 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
2870 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
2871 ** by default, but future releases of SQLite might enable URI filename
2872 ** interpretation by default.  See "[URI filenames]" for additional
2873 ** information.
2874 **
2875 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
2876 ** authority, then it must be either an empty string or the string
2877 ** "localhost". ^If the authority is not an empty string or "localhost", an
2878 ** error is returned to the caller. ^The fragment component of a URI, if
2879 ** present, is ignored.
2880 **
2881 ** ^SQLite uses the path component of the URI as the name of the disk file
2882 ** which contains the database. ^If the path begins with a '/' character,
2883 ** then it is interpreted as an absolute path. ^If the path does not begin
2884 ** with a '/' (meaning that the authority section is omitted from the URI)
2885 ** then the path is interpreted as a relative path.
2886 ** ^(On windows, the first component of an absolute path
2887 ** is a drive specification (e.g. "C:").)^
2888 **
2889 ** [[core URI query parameters]]
2890 ** The query component of a URI may contain parameters that are interpreted
2891 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
2892 ** SQLite and its built-in [VFSes] interpret the
2893 ** following query parameters:
2894 **
2895 ** <ul>
2896 **   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
2897 **     a VFS object that provides the operating system interface that should
2898 **     be used to access the database file on disk. ^If this option is set to
2899 **     an empty string the default VFS object is used. ^Specifying an unknown
2900 **     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
2901 **     present, then the VFS specified by the option takes precedence over
2902 **     the value passed as the fourth parameter to sqlite3_open_v2().
2903 **
2904 **   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
2905 **     "rwc", or "memory". Attempting to set it to any other value is
2906 **     an error)^.
2907 **     ^If "ro" is specified, then the database is opened for read-only
2908 **     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
2909 **     third argument to sqlite3_open_v2(). ^If the mode option is set to
2910 **     "rw", then the database is opened for read-write (but not create)
2911 **     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
2912 **     been set. ^Value "rwc" is equivalent to setting both
2913 **     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
2914 **     set to "memory" then a pure [in-memory database] that never reads
2915 **     or writes from disk is used. ^It is an error to specify a value for
2916 **     the mode parameter that is less restrictive than that specified by
2917 **     the flags passed in the third parameter to sqlite3_open_v2().
2918 **
2919 **   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
2920 **     "private". ^Setting it to "shared" is equivalent to setting the
2921 **     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
2922 **     sqlite3_open_v2(). ^Setting the cache parameter to "private" is
2923 **     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
2924 **     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
2925 **     a URI filename, its value overrides any behavior requested by setting
2926 **     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
2927 **
2928 **  <li> <b>psow</b>: ^The psow parameter indicates whether or not the
2929 **     [powersafe overwrite] property does or does not apply to the
2930 **     storage media on which the database file resides.
2931 **
2932 **  <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
2933 **     which if set disables file locking in rollback journal modes.  This
2934 **     is useful for accessing a database on a filesystem that does not
2935 **     support locking.  Caution:  Database corruption might result if two
2936 **     or more processes write to the same database and any one of those
2937 **     processes uses nolock=1.
2938 **
2939 **  <li> <b>immutable</b>: ^The immutable parameter is a boolean query
2940 **     parameter that indicates that the database file is stored on
2941 **     read-only media.  ^When immutable is set, SQLite assumes that the
2942 **     database file cannot be changed, even by a process with higher
2943 **     privilege, and so the database is opened read-only and all locking
2944 **     and change detection is disabled.  Caution: Setting the immutable
2945 **     property on a database file that does in fact change can result
2946 **     in incorrect query results and/or [SQLITE_CORRUPT] errors.
2947 **     See also: [SQLITE_IOCAP_IMMUTABLE].
2948 **
2949 ** </ul>
2950 **
2951 ** ^Specifying an unknown parameter in the query component of a URI is not an
2952 ** error.  Future versions of SQLite might understand additional query
2953 ** parameters.  See "[query parameters with special meaning to SQLite]" for
2954 ** additional information.
2955 **
2956 ** [[URI filename examples]] <h3>URI filename examples</h3>
2957 **
2958 ** <table border="1" align=center cellpadding=5>
2959 ** <tr><th> URI filenames <th> Results
2960 ** <tr><td> file:data.db <td>
2961 **          Open the file "data.db" in the current directory.
2962 ** <tr><td> file:/home/fred/data.db<br>
2963 **          file:///home/fred/data.db <br>
2964 **          file://localhost/home/fred/data.db <br> <td>
2965 **          Open the database file "/home/fred/data.db".
2966 ** <tr><td> file://darkstar/home/fred/data.db <td>
2967 **          An error. "darkstar" is not a recognized authority.
2968 ** <tr><td style="white-space:nowrap">
2969 **          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
2970 **     <td> Windows only: Open the file "data.db" on fred's desktop on drive
2971 **          C:. Note that the %20 escaping in this example is not strictly
2972 **          necessary - space characters can be used literally
2973 **          in URI filenames.
2974 ** <tr><td> file:data.db?mode=ro&cache=private <td>
2975 **          Open file "data.db" in the current directory for read-only access.
2976 **          Regardless of whether or not shared-cache mode is enabled by
2977 **          default, use a private cache.
2978 ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
2979 **          Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
2980 **          that uses dot-files in place of posix advisory locking.
2981 ** <tr><td> file:data.db?mode=readonly <td>
2982 **          An error. "readonly" is not a valid option for the "mode" parameter.
2983 ** </table>
2984 **
2985 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
2986 ** query components of a URI. A hexadecimal escape sequence consists of a
2987 ** percent sign - "%" - followed by exactly two hexadecimal digits
2988 ** specifying an octet value. ^Before the path or query components of a
2989 ** URI filename are interpreted, they are encoded using UTF-8 and all
2990 ** hexadecimal escape sequences replaced by a single byte containing the
2991 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
2992 ** the results are undefined.
2993 **
2994 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
2995 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
2996 ** codepage is currently defined.  Filenames containing international
2997 ** characters must be converted to UTF-8 prior to passing them into
2998 ** sqlite3_open() or sqlite3_open_v2().
2999 **
3000 ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
3001 ** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
3002 ** features that require the use of temporary files may fail.
3003 **
3004 ** See also: [sqlite3_temp_directory]
3005 */
3006 SQLITE_API int sqlite3_open(
3007   const char *filename,   /* Database filename (UTF-8) */
3008   sqlite3 **ppDb          /* OUT: SQLite db handle */
3009 );
3010 SQLITE_API int sqlite3_open16(
3011   const void *filename,   /* Database filename (UTF-16) */
3012   sqlite3 **ppDb          /* OUT: SQLite db handle */
3013 );
3014 SQLITE_API int sqlite3_open_v2(
3015   const char *filename,   /* Database filename (UTF-8) */
3016   sqlite3 **ppDb,         /* OUT: SQLite db handle */
3017   int flags,              /* Flags */
3018   const char *zVfs        /* Name of VFS module to use */
3019 );
3020 
3021 /*
3022 ** CAPI3REF: Obtain Values For URI Parameters
3023 **
3024 ** These are utility routines, useful to VFS implementations, that check
3025 ** to see if a database file was a URI that contained a specific query
3026 ** parameter, and if so obtains the value of that query parameter.
3027 **
3028 ** If F is the database filename pointer passed into the xOpen() method of
3029 ** a VFS implementation when the flags parameter to xOpen() has one or
3030 ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
3031 ** P is the name of the query parameter, then
3032 ** sqlite3_uri_parameter(F,P) returns the value of the P
3033 ** parameter if it exists or a NULL pointer if P does not appear as a
3034 ** query parameter on F.  If P is a query parameter of F
3035 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3036 ** a pointer to an empty string.
3037 **
3038 ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3039 ** parameter and returns true (1) or false (0) according to the value
3040 ** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3041 ** value of query parameter P is one of "yes", "true", or "on" in any
3042 ** case or if the value begins with a non-zero number.  The
3043 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3044 ** query parameter P is one of "no", "false", or "off" in any case or
3045 ** if the value begins with a numeric zero.  If P is not a query
3046 ** parameter on F or if the value of P is does not match any of the
3047 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3048 **
3049 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3050 ** 64-bit signed integer and returns that integer, or D if P does not
3051 ** exist.  If the value of P is something other than an integer, then
3052 ** zero is returned.
3053 **
3054 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3055 ** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
3056 ** is not a database file pathname pointer that SQLite passed into the xOpen
3057 ** VFS method, then the behavior of this routine is undefined and probably
3058 ** undesirable.
3059 */
3060 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3061 SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
3062 SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
3063 
3064 
3065 /*
3066 ** CAPI3REF: Error Codes And Messages
3067 **
3068 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
3069 ** [extended result code] for the most recent failed sqlite3_* API call
3070 ** associated with a [database connection]. If a prior API call failed
3071 ** but the most recent API call succeeded, the return value from
3072 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
3073 ** interface is the same except that it always returns the
3074 ** [extended result code] even when extended result codes are
3075 ** disabled.
3076 **
3077 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3078 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3079 ** ^(Memory to hold the error message string is managed internally.
3080 ** The application does not need to worry about freeing the result.
3081 ** However, the error string might be overwritten or deallocated by
3082 ** subsequent calls to other SQLite interface functions.)^
3083 **
3084 ** ^The sqlite3_errstr() interface returns the English-language text
3085 ** that describes the [result code], as UTF-8.
3086 ** ^(Memory to hold the error message string is managed internally
3087 ** and must not be freed by the application)^.
3088 **
3089 ** When the serialized [threading mode] is in use, it might be the
3090 ** case that a second error occurs on a separate thread in between
3091 ** the time of the first error and the call to these interfaces.
3092 ** When that happens, the second error will be reported since these
3093 ** interfaces always report the most recent result.  To avoid
3094 ** this, each thread can obtain exclusive use of the [database connection] D
3095 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3096 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3097 ** all calls to the interfaces listed here are completed.
3098 **
3099 ** If an interface fails with SQLITE_MISUSE, that means the interface
3100 ** was invoked incorrectly by the application.  In that case, the
3101 ** error code and message may or may not be set.
3102 */
3103 SQLITE_API int sqlite3_errcode(sqlite3 *db);
3104 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3105 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3106 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3107 SQLITE_API const char *sqlite3_errstr(int);
3108 
3109 /*
3110 ** CAPI3REF: SQL Statement Object
3111 ** KEYWORDS: {prepared statement} {prepared statements}
3112 **
3113 ** An instance of this object represents a single SQL statement.
3114 ** This object is variously known as a "prepared statement" or a
3115 ** "compiled SQL statement" or simply as a "statement".
3116 **
3117 ** The life of a statement object goes something like this:
3118 **
3119 ** <ol>
3120 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
3121 **      function.
3122 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3123 **      interfaces.
3124 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3125 ** <li> Reset the statement using [sqlite3_reset()] then go back
3126 **      to step 2.  Do this zero or more times.
3127 ** <li> Destroy the object using [sqlite3_finalize()].
3128 ** </ol>
3129 **
3130 ** Refer to documentation on individual methods above for additional
3131 ** information.
3132 */
3133 typedef struct sqlite3_stmt sqlite3_stmt;
3134 
3135 /*
3136 ** CAPI3REF: Run-time Limits
3137 **
3138 ** ^(This interface allows the size of various constructs to be limited
3139 ** on a connection by connection basis.  The first parameter is the
3140 ** [database connection] whose limit is to be set or queried.  The
3141 ** second parameter is one of the [limit categories] that define a
3142 ** class of constructs to be size limited.  The third parameter is the
3143 ** new limit for that construct.)^
3144 **
3145 ** ^If the new limit is a negative number, the limit is unchanged.
3146 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
3147 ** [limits | hard upper bound]
3148 ** set at compile-time by a C preprocessor macro called
3149 ** [limits | SQLITE_MAX_<i>NAME</i>].
3150 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3151 ** ^Attempts to increase a limit above its hard upper bound are
3152 ** silently truncated to the hard upper bound.
3153 **
3154 ** ^Regardless of whether or not the limit was changed, the
3155 ** [sqlite3_limit()] interface returns the prior value of the limit.
3156 ** ^Hence, to find the current value of a limit without changing it,
3157 ** simply invoke this interface with the third parameter set to -1.
3158 **
3159 ** Run-time limits are intended for use in applications that manage
3160 ** both their own internal database and also databases that are controlled
3161 ** by untrusted external sources.  An example application might be a
3162 ** web browser that has its own databases for storing history and
3163 ** separate databases controlled by JavaScript applications downloaded
3164 ** off the Internet.  The internal databases can be given the
3165 ** large, default limits.  Databases managed by external sources can
3166 ** be given much smaller limits designed to prevent a denial of service
3167 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3168 ** interface to further control untrusted SQL.  The size of the database
3169 ** created by an untrusted script can be contained using the
3170 ** [max_page_count] [PRAGMA].
3171 **
3172 ** New run-time limit categories may be added in future releases.
3173 */
3174 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3175 
3176 /*
3177 ** CAPI3REF: Run-Time Limit Categories
3178 ** KEYWORDS: {limit category} {*limit categories}
3179 **
3180 ** These constants define various performance limits
3181 ** that can be lowered at run-time using [sqlite3_limit()].
3182 ** The synopsis of the meanings of the various limits is shown below.
3183 ** Additional information is available at [limits | Limits in SQLite].
3184 **
3185 ** <dl>
3186 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3187 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3188 **
3189 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3190 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3191 **
3192 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3193 ** <dd>The maximum number of columns in a table definition or in the
3194 ** result set of a [SELECT] or the maximum number of columns in an index
3195 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3196 **
3197 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3198 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3199 **
3200 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3201 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3202 **
3203 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3204 ** <dd>The maximum number of instructions in a virtual machine program
3205 ** used to implement an SQL statement.  This limit is not currently
3206 ** enforced, though that might be added in some future release of
3207 ** SQLite.</dd>)^
3208 **
3209 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3210 ** <dd>The maximum number of arguments on a function.</dd>)^
3211 **
3212 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3213 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3214 **
3215 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3216 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3217 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3218 ** [GLOB] operators.</dd>)^
3219 **
3220 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3221 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3222 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3223 **
3224 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3225 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3226 **
3227 ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
3228 ** <dd>The maximum number of auxiliary worker threads that a single
3229 ** [prepared statement] may start.</dd>)^
3230 ** </dl>
3231 */
3232 #define SQLITE_LIMIT_LENGTH                    0
3233 #define SQLITE_LIMIT_SQL_LENGTH                1
3234 #define SQLITE_LIMIT_COLUMN                    2
3235 #define SQLITE_LIMIT_EXPR_DEPTH                3
3236 #define SQLITE_LIMIT_COMPOUND_SELECT           4
3237 #define SQLITE_LIMIT_VDBE_OP                   5
3238 #define SQLITE_LIMIT_FUNCTION_ARG              6
3239 #define SQLITE_LIMIT_ATTACHED                  7
3240 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3241 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
3242 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
3243 #define SQLITE_LIMIT_WORKER_THREADS           11
3244 
3245 /*
3246 ** CAPI3REF: Compiling An SQL Statement
3247 ** KEYWORDS: {SQL statement compiler}
3248 **
3249 ** To execute an SQL query, it must first be compiled into a byte-code
3250 ** program using one of these routines.
3251 **
3252 ** The first argument, "db", is a [database connection] obtained from a
3253 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3254 ** [sqlite3_open16()].  The database connection must not have been closed.
3255 **
3256 ** The second argument, "zSql", is the statement to be compiled, encoded
3257 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3258 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3259 ** use UTF-16.
3260 **
3261 ** ^If the nByte argument is less than zero, then zSql is read up to the
3262 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
3263 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
3264 ** zSql string ends at either the first '\000' or '\u0000' character or
3265 ** the nByte-th byte, whichever comes first. If the caller knows
3266 ** that the supplied string is nul-terminated, then there is a small
3267 ** performance advantage to be gained by passing an nByte parameter that
3268 ** is equal to the number of bytes in the input string <i>including</i>
3269 ** the nul-terminator bytes as this saves SQLite from having to
3270 ** make a copy of the input string.
3271 **
3272 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3273 ** past the end of the first SQL statement in zSql.  These routines only
3274 ** compile the first statement in zSql, so *pzTail is left pointing to
3275 ** what remains uncompiled.
3276 **
3277 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3278 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3279 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
3280 ** string or a comment) then *ppStmt is set to NULL.
3281 ** The calling procedure is responsible for deleting the compiled
3282 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3283 ** ppStmt may not be NULL.
3284 **
3285 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3286 ** otherwise an [error code] is returned.
3287 **
3288 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3289 ** recommended for all new programs. The two older interfaces are retained
3290 ** for backwards compatibility, but their use is discouraged.
3291 ** ^In the "v2" interfaces, the prepared statement
3292 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3293 ** original SQL text. This causes the [sqlite3_step()] interface to
3294 ** behave differently in three ways:
3295 **
3296 ** <ol>
3297 ** <li>
3298 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3299 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3300 ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
3301 ** retries will occur before sqlite3_step() gives up and returns an error.
3302 ** </li>
3303 **
3304 ** <li>
3305 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3306 ** [error codes] or [extended error codes].  ^The legacy behavior was that
3307 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3308 ** and the application would have to make a second call to [sqlite3_reset()]
3309 ** in order to find the underlying cause of the problem. With the "v2" prepare
3310 ** interfaces, the underlying reason for the error is returned immediately.
3311 ** </li>
3312 **
3313 ** <li>
3314 ** ^If the specific value bound to [parameter | host parameter] in the
3315 ** WHERE clause might influence the choice of query plan for a statement,
3316 ** then the statement will be automatically recompiled, as if there had been
3317 ** a schema change, on the first  [sqlite3_step()] call following any change
3318 ** to the [sqlite3_bind_text | bindings] of that [parameter].
3319 ** ^The specific value of WHERE-clause [parameter] might influence the
3320 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3321 ** or [GLOB] operator or if the parameter is compared to an indexed column
3322 ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3323 ** </li>
3324 ** </ol>
3325 */
3326 SQLITE_API int sqlite3_prepare(
3327   sqlite3 *db,            /* Database handle */
3328   const char *zSql,       /* SQL statement, UTF-8 encoded */
3329   int nByte,              /* Maximum length of zSql in bytes. */
3330   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3331   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3332 );
3333 SQLITE_API int sqlite3_prepare_v2(
3334   sqlite3 *db,            /* Database handle */
3335   const char *zSql,       /* SQL statement, UTF-8 encoded */
3336   int nByte,              /* Maximum length of zSql in bytes. */
3337   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3338   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3339 );
3340 SQLITE_API int sqlite3_prepare16(
3341   sqlite3 *db,            /* Database handle */
3342   const void *zSql,       /* SQL statement, UTF-16 encoded */
3343   int nByte,              /* Maximum length of zSql in bytes. */
3344   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3345   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3346 );
3347 SQLITE_API int sqlite3_prepare16_v2(
3348   sqlite3 *db,            /* Database handle */
3349   const void *zSql,       /* SQL statement, UTF-16 encoded */
3350   int nByte,              /* Maximum length of zSql in bytes. */
3351   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3352   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3353 );
3354 
3355 /*
3356 ** CAPI3REF: Retrieving Statement SQL
3357 **
3358 ** ^This interface can be used to retrieve a saved copy of the original
3359 ** SQL text used to create a [prepared statement] if that statement was
3360 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3361 */
3362 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3363 
3364 /*
3365 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3366 **
3367 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3368 ** and only if the [prepared statement] X makes no direct changes to
3369 ** the content of the database file.
3370 **
3371 ** Note that [application-defined SQL functions] or
3372 ** [virtual tables] might change the database indirectly as a side effect.
3373 ** ^(For example, if an application defines a function "eval()" that
3374 ** calls [sqlite3_exec()], then the following SQL statement would
3375 ** change the database file through side-effects:
3376 **
3377 ** <blockquote><pre>
3378 **    SELECT eval('DELETE FROM t1') FROM t2;
3379 ** </pre></blockquote>
3380 **
3381 ** But because the [SELECT] statement does not change the database file
3382 ** directly, sqlite3_stmt_readonly() would still return true.)^
3383 **
3384 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3385 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3386 ** since the statements themselves do not actually modify the database but
3387 ** rather they control the timing of when other statements modify the
3388 ** database.  ^The [ATTACH] and [DETACH] statements also cause
3389 ** sqlite3_stmt_readonly() to return true since, while those statements
3390 ** change the configuration of a database connection, they do not make
3391 ** changes to the content of the database files on disk.
3392 */
3393 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3394 
3395 /*
3396 ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3397 **
3398 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3399 ** [prepared statement] S has been stepped at least once using
3400 ** [sqlite3_step(S)] but has not run to completion and/or has not
3401 ** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
3402 ** interface returns false if S is a NULL pointer.  If S is not a
3403 ** NULL pointer and is not a pointer to a valid [prepared statement]
3404 ** object, then the behavior is undefined and probably undesirable.
3405 **
3406 ** This interface can be used in combination [sqlite3_next_stmt()]
3407 ** to locate all prepared statements associated with a database
3408 ** connection that are in need of being reset.  This can be used,
3409 ** for example, in diagnostic routines to search for prepared
3410 ** statements that are holding a transaction open.
3411 */
3412 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
3413 
3414 /*
3415 ** CAPI3REF: Dynamically Typed Value Object
3416 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3417 **
3418 ** SQLite uses the sqlite3_value object to represent all values
3419 ** that can be stored in a database table. SQLite uses dynamic typing
3420 ** for the values it stores.  ^Values stored in sqlite3_value objects
3421 ** can be integers, floating point values, strings, BLOBs, or NULL.
3422 **
3423 ** An sqlite3_value object may be either "protected" or "unprotected".
3424 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3425 ** will accept either a protected or an unprotected sqlite3_value.
3426 ** Every interface that accepts sqlite3_value arguments specifies
3427 ** whether or not it requires a protected sqlite3_value.
3428 **
3429 ** The terms "protected" and "unprotected" refer to whether or not
3430 ** a mutex is held.  An internal mutex is held for a protected
3431 ** sqlite3_value object but no mutex is held for an unprotected
3432 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3433 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3434 ** or if SQLite is run in one of reduced mutex modes
3435 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3436 ** then there is no distinction between protected and unprotected
3437 ** sqlite3_value objects and they can be used interchangeably.  However,
3438 ** for maximum code portability it is recommended that applications
3439 ** still make the distinction between protected and unprotected
3440 ** sqlite3_value objects even when not strictly required.
3441 **
3442 ** ^The sqlite3_value objects that are passed as parameters into the
3443 ** implementation of [application-defined SQL functions] are protected.
3444 ** ^The sqlite3_value object returned by
3445 ** [sqlite3_column_value()] is unprotected.
3446 ** Unprotected sqlite3_value objects may only be used with
3447 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3448 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3449 ** interfaces require protected sqlite3_value objects.
3450 */
3451 typedef struct Mem sqlite3_value;
3452 
3453 /*
3454 ** CAPI3REF: SQL Function Context Object
3455 **
3456 ** The context in which an SQL function executes is stored in an
3457 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
3458 ** is always first parameter to [application-defined SQL functions].
3459 ** The application-defined SQL function implementation will pass this
3460 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3461 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3462 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3463 ** and/or [sqlite3_set_auxdata()].
3464 */
3465 typedef struct sqlite3_context sqlite3_context;
3466 
3467 /*
3468 ** CAPI3REF: Binding Values To Prepared Statements
3469 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3470 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3471 **
3472 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3473 ** literals may be replaced by a [parameter] that matches one of following
3474 ** templates:
3475 **
3476 ** <ul>
3477 ** <li>  ?
3478 ** <li>  ?NNN
3479 ** <li>  :VVV
3480 ** <li>  @VVV
3481 ** <li>  $VVV
3482 ** </ul>
3483 **
3484 ** In the templates above, NNN represents an integer literal,
3485 ** and VVV represents an alphanumeric identifier.)^  ^The values of these
3486 ** parameters (also called "host parameter names" or "SQL parameters")
3487 ** can be set using the sqlite3_bind_*() routines defined here.
3488 **
3489 ** ^The first argument to the sqlite3_bind_*() routines is always
3490 ** a pointer to the [sqlite3_stmt] object returned from
3491 ** [sqlite3_prepare_v2()] or its variants.
3492 **
3493 ** ^The second argument is the index of the SQL parameter to be set.
3494 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3495 ** SQL parameter is used more than once, second and subsequent
3496 ** occurrences have the same index as the first occurrence.
3497 ** ^The index for named parameters can be looked up using the
3498 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3499 ** for "?NNN" parameters is the value of NNN.
3500 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3501 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3502 **
3503 ** ^The third argument is the value to bind to the parameter.
3504 ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3505 ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
3506 ** is ignored and the end result is the same as sqlite3_bind_null().
3507 **
3508 ** ^(In those routines that have a fourth argument, its value is the
3509 ** number of bytes in the parameter.  To be clear: the value is the
3510 ** number of <u>bytes</u> in the value, not the number of characters.)^
3511 ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3512 ** is negative, then the length of the string is
3513 ** the number of bytes up to the first zero terminator.
3514 ** If the fourth parameter to sqlite3_bind_blob() is negative, then
3515 ** the behavior is undefined.
3516 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
3517 ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
3518 ** that parameter must be the byte offset
3519 ** where the NUL terminator would occur assuming the string were NUL
3520 ** terminated.  If any NUL characters occur at byte offsets less than
3521 ** the value of the fourth parameter then the resulting string value will
3522 ** contain embedded NULs.  The result of expressions involving strings
3523 ** with embedded NULs is undefined.
3524 **
3525 ** ^The fifth argument to the BLOB and string binding interfaces
3526 ** is a destructor used to dispose of the BLOB or
3527 ** string after SQLite has finished with it.  ^The destructor is called
3528 ** to dispose of the BLOB or string even if the call to bind API fails.
3529 ** ^If the fifth argument is
3530 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3531 ** information is in static, unmanaged space and does not need to be freed.
3532 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3533 ** SQLite makes its own private copy of the data immediately, before
3534 ** the sqlite3_bind_*() routine returns.
3535 **
3536 ** ^The sixth argument to sqlite3_bind_text64() must be one of
3537 ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
3538 ** to specify the encoding of the text in the third parameter.  If
3539 ** the sixth argument to sqlite3_bind_text64() is not one of the
3540 ** allowed values shown above, or if the text encoding is different
3541 ** from the encoding specified by the sixth parameter, then the behavior
3542 ** is undefined.
3543 **
3544 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3545 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3546 ** (just an integer to hold its size) while it is being processed.
3547 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3548 ** content is later written using
3549 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3550 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3551 **
3552 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3553 ** for the [prepared statement] or with a prepared statement for which
3554 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3555 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3556 ** routine is passed a [prepared statement] that has been finalized, the
3557 ** result is undefined and probably harmful.
3558 **
3559 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3560 ** ^Unbound parameters are interpreted as NULL.
3561 **
3562 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3563 ** [error code] if anything goes wrong.
3564 ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
3565 ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
3566 ** [SQLITE_MAX_LENGTH].
3567 ** ^[SQLITE_RANGE] is returned if the parameter
3568 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3569 **
3570 ** See also: [sqlite3_bind_parameter_count()],
3571 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3572 */
3573 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3574 SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
3575                         void(*)(void*));
3576 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3577 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3578 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3579 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3580 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
3581 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3582 SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
3583                          void(*)(void*), unsigned char encoding);
3584 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3585 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3586 
3587 /*
3588 ** CAPI3REF: Number Of SQL Parameters
3589 **
3590 ** ^This routine can be used to find the number of [SQL parameters]
3591 ** in a [prepared statement].  SQL parameters are tokens of the
3592 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3593 ** placeholders for values that are [sqlite3_bind_blob | bound]
3594 ** to the parameters at a later time.
3595 **
3596 ** ^(This routine actually returns the index of the largest (rightmost)
3597 ** parameter. For all forms except ?NNN, this will correspond to the
3598 ** number of unique parameters.  If parameters of the ?NNN form are used,
3599 ** there may be gaps in the list.)^
3600 **
3601 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3602 ** [sqlite3_bind_parameter_name()], and
3603 ** [sqlite3_bind_parameter_index()].
3604 */
3605 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3606 
3607 /*
3608 ** CAPI3REF: Name Of A Host Parameter
3609 **
3610 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3611 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3612 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3613 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3614 ** respectively.
3615 ** In other words, the initial ":" or "$" or "@" or "?"
3616 ** is included as part of the name.)^
3617 ** ^Parameters of the form "?" without a following integer have no name
3618 ** and are referred to as "nameless" or "anonymous parameters".
3619 **
3620 ** ^The first host parameter has an index of 1, not 0.
3621 **
3622 ** ^If the value N is out of range or if the N-th parameter is
3623 ** nameless, then NULL is returned.  ^The returned string is
3624 ** always in UTF-8 encoding even if the named parameter was
3625 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3626 ** [sqlite3_prepare16_v2()].
3627 **
3628 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3629 ** [sqlite3_bind_parameter_count()], and
3630 ** [sqlite3_bind_parameter_index()].
3631 */
3632 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3633 
3634 /*
3635 ** CAPI3REF: Index Of A Parameter With A Given Name
3636 **
3637 ** ^Return the index of an SQL parameter given its name.  ^The
3638 ** index value returned is suitable for use as the second
3639 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3640 ** is returned if no matching parameter is found.  ^The parameter
3641 ** name must be given in UTF-8 even if the original statement
3642 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3643 **
3644 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3645 ** [sqlite3_bind_parameter_count()], and
3646 ** [sqlite3_bind_parameter_index()].
3647 */
3648 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3649 
3650 /*
3651 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3652 **
3653 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3654 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3655 ** ^Use this routine to reset all host parameters to NULL.
3656 */
3657 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3658 
3659 /*
3660 ** CAPI3REF: Number Of Columns In A Result Set
3661 **
3662 ** ^Return the number of columns in the result set returned by the
3663 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3664 ** statement that does not return data (for example an [UPDATE]).
3665 **
3666 ** See also: [sqlite3_data_count()]
3667 */
3668 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3669 
3670 /*
3671 ** CAPI3REF: Column Names In A Result Set
3672 **
3673 ** ^These routines return the name assigned to a particular column
3674 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3675 ** interface returns a pointer to a zero-terminated UTF-8 string
3676 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3677 ** UTF-16 string.  ^The first parameter is the [prepared statement]
3678 ** that implements the [SELECT] statement. ^The second parameter is the
3679 ** column number.  ^The leftmost column is number 0.
3680 **
3681 ** ^The returned string pointer is valid until either the [prepared statement]
3682 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3683 ** reprepared by the first call to [sqlite3_step()] for a particular run
3684 ** or until the next call to
3685 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3686 **
3687 ** ^If sqlite3_malloc() fails during the processing of either routine
3688 ** (for example during a conversion from UTF-8 to UTF-16) then a
3689 ** NULL pointer is returned.
3690 **
3691 ** ^The name of a result column is the value of the "AS" clause for
3692 ** that column, if there is an AS clause.  If there is no AS clause
3693 ** then the name of the column is unspecified and may change from
3694 ** one release of SQLite to the next.
3695 */
3696 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3697 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3698 
3699 /*
3700 ** CAPI3REF: Source Of Data In A Query Result
3701 **
3702 ** ^These routines provide a means to determine the database, table, and
3703 ** table column that is the origin of a particular result column in
3704 ** [SELECT] statement.
3705 ** ^The name of the database or table or column can be returned as
3706 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3707 ** the database name, the _table_ routines return the table name, and
3708 ** the origin_ routines return the column name.
3709 ** ^The returned string is valid until the [prepared statement] is destroyed
3710 ** using [sqlite3_finalize()] or until the statement is automatically
3711 ** reprepared by the first call to [sqlite3_step()] for a particular run
3712 ** or until the same information is requested
3713 ** again in a different encoding.
3714 **
3715 ** ^The names returned are the original un-aliased names of the
3716 ** database, table, and column.
3717 **
3718 ** ^The first argument to these interfaces is a [prepared statement].
3719 ** ^These functions return information about the Nth result column returned by
3720 ** the statement, where N is the second function argument.
3721 ** ^The left-most column is column 0 for these routines.
3722 **
3723 ** ^If the Nth column returned by the statement is an expression or
3724 ** subquery and is not a column value, then all of these functions return
3725 ** NULL.  ^These routine might also return NULL if a memory allocation error
3726 ** occurs.  ^Otherwise, they return the name of the attached database, table,
3727 ** or column that query result column was extracted from.
3728 **
3729 ** ^As with all other SQLite APIs, those whose names end with "16" return
3730 ** UTF-16 encoded strings and the other functions return UTF-8.
3731 **
3732 ** ^These APIs are only available if the library was compiled with the
3733 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3734 **
3735 ** If two or more threads call one or more of these routines against the same
3736 ** prepared statement and column at the same time then the results are
3737 ** undefined.
3738 **
3739 ** If two or more threads call one or more
3740 ** [sqlite3_column_database_name | column metadata interfaces]
3741 ** for the same [prepared statement] and result column
3742 ** at the same time then the results are undefined.
3743 */
3744 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3745 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3746 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3747 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3748 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3749 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3750 
3751 /*
3752 ** CAPI3REF: Declared Datatype Of A Query Result
3753 **
3754 ** ^(The first parameter is a [prepared statement].
3755 ** If this statement is a [SELECT] statement and the Nth column of the
3756 ** returned result set of that [SELECT] is a table column (not an
3757 ** expression or subquery) then the declared type of the table
3758 ** column is returned.)^  ^If the Nth column of the result set is an
3759 ** expression or subquery, then a NULL pointer is returned.
3760 ** ^The returned string is always UTF-8 encoded.
3761 **
3762 ** ^(For example, given the database schema:
3763 **
3764 ** CREATE TABLE t1(c1 VARIANT);
3765 **
3766 ** and the following statement to be compiled:
3767 **
3768 ** SELECT c1 + 1, c1 FROM t1;
3769 **
3770 ** this routine would return the string "VARIANT" for the second result
3771 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
3772 **
3773 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
3774 ** is declared to contain a particular type does not mean that the
3775 ** data stored in that column is of the declared type.  SQLite is
3776 ** strongly typed, but the typing is dynamic not static.  ^Type
3777 ** is associated with individual values, not with the containers
3778 ** used to hold those values.
3779 */
3780 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3781 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3782 
3783 /*
3784 ** CAPI3REF: Evaluate An SQL Statement
3785 **
3786 ** After a [prepared statement] has been prepared using either
3787 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3788 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3789 ** must be called one or more times to evaluate the statement.
3790 **
3791 ** The details of the behavior of the sqlite3_step() interface depend
3792 ** on whether the statement was prepared using the newer "v2" interface
3793 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3794 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3795 ** new "v2" interface is recommended for new applications but the legacy
3796 ** interface will continue to be supported.
3797 **
3798 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3799 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3800 ** ^With the "v2" interface, any of the other [result codes] or
3801 ** [extended result codes] might be returned as well.
3802 **
3803 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3804 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3805 ** or occurs outside of an explicit transaction, then you can retry the
3806 ** statement.  If the statement is not a [COMMIT] and occurs within an
3807 ** explicit transaction then you should rollback the transaction before
3808 ** continuing.
3809 **
3810 ** ^[SQLITE_DONE] means that the statement has finished executing
3811 ** successfully.  sqlite3_step() should not be called again on this virtual
3812 ** machine without first calling [sqlite3_reset()] to reset the virtual
3813 ** machine back to its initial state.
3814 **
3815 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3816 ** is returned each time a new row of data is ready for processing by the
3817 ** caller. The values may be accessed using the [column access functions].
3818 ** sqlite3_step() is called again to retrieve the next row of data.
3819 **
3820 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3821 ** violation) has occurred.  sqlite3_step() should not be called again on
3822 ** the VM. More information may be found by calling [sqlite3_errmsg()].
3823 ** ^With the legacy interface, a more specific error code (for example,
3824 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3825 ** can be obtained by calling [sqlite3_reset()] on the
3826 ** [prepared statement].  ^In the "v2" interface,
3827 ** the more specific error code is returned directly by sqlite3_step().
3828 **
3829 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3830 ** Perhaps it was called on a [prepared statement] that has
3831 ** already been [sqlite3_finalize | finalized] or on one that had
3832 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3833 ** be the case that the same database connection is being used by two or
3834 ** more threads at the same moment in time.
3835 **
3836 ** For all versions of SQLite up to and including 3.6.23.1, a call to
3837 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
3838 ** other than [SQLITE_ROW] before any subsequent invocation of
3839 ** sqlite3_step().  Failure to reset the prepared statement using
3840 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
3841 ** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
3842 ** calling [sqlite3_reset()] automatically in this circumstance rather
3843 ** than returning [SQLITE_MISUSE].  This is not considered a compatibility
3844 ** break because any application that ever receives an SQLITE_MISUSE error
3845 ** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
3846 ** can be used to restore the legacy behavior.
3847 **
3848 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3849 ** API always returns a generic error code, [SQLITE_ERROR], following any
3850 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
3851 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3852 ** specific [error codes] that better describes the error.
3853 ** We admit that this is a goofy design.  The problem has been fixed
3854 ** with the "v2" interface.  If you prepare all of your SQL statements
3855 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3856 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3857 ** then the more specific [error codes] are returned directly
3858 ** by sqlite3_step().  The use of the "v2" interface is recommended.
3859 */
3860 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3861 
3862 /*
3863 ** CAPI3REF: Number of columns in a result set
3864 **
3865 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
3866 ** current row of the result set of [prepared statement] P.
3867 ** ^If prepared statement P does not have results ready to return
3868 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
3869 ** interfaces) then sqlite3_data_count(P) returns 0.
3870 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
3871 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
3872 ** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
3873 ** will return non-zero if previous call to [sqlite3_step](P) returned
3874 ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
3875 ** where it always returns zero since each step of that multi-step
3876 ** pragma returns 0 columns of data.
3877 **
3878 ** See also: [sqlite3_column_count()]
3879 */
3880 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3881 
3882 /*
3883 ** CAPI3REF: Fundamental Datatypes
3884 ** KEYWORDS: SQLITE_TEXT
3885 **
3886 ** ^(Every value in SQLite has one of five fundamental datatypes:
3887 **
3888 ** <ul>
3889 ** <li> 64-bit signed integer
3890 ** <li> 64-bit IEEE floating point number
3891 ** <li> string
3892 ** <li> BLOB
3893 ** <li> NULL
3894 ** </ul>)^
3895 **
3896 ** These constants are codes for each of those types.
3897 **
3898 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3899 ** for a completely different meaning.  Software that links against both
3900 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3901 ** SQLITE_TEXT.
3902 */
3903 #define SQLITE_INTEGER  1
3904 #define SQLITE_FLOAT    2
3905 #define SQLITE_BLOB     4
3906 #define SQLITE_NULL     5
3907 #ifdef SQLITE_TEXT
3908 # undef SQLITE_TEXT
3909 #else
3910 # define SQLITE_TEXT     3
3911 #endif
3912 #define SQLITE3_TEXT     3
3913 
3914 /*
3915 ** CAPI3REF: Result Values From A Query
3916 ** KEYWORDS: {column access functions}
3917 **
3918 ** These routines form the "result set" interface.
3919 **
3920 ** ^These routines return information about a single column of the current
3921 ** result row of a query.  ^In every case the first argument is a pointer
3922 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3923 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3924 ** and the second argument is the index of the column for which information
3925 ** should be returned. ^The leftmost column of the result set has the index 0.
3926 ** ^The number of columns in the result can be determined using
3927 ** [sqlite3_column_count()].
3928 **
3929 ** If the SQL statement does not currently point to a valid row, or if the
3930 ** column index is out of range, the result is undefined.
3931 ** These routines may only be called when the most recent call to
3932 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3933 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3934 ** If any of these routines are called after [sqlite3_reset()] or
3935 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3936 ** something other than [SQLITE_ROW], the results are undefined.
3937 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3938 ** are called from a different thread while any of these routines
3939 ** are pending, then the results are undefined.
3940 **
3941 ** ^The sqlite3_column_type() routine returns the
3942 ** [SQLITE_INTEGER | datatype code] for the initial data type
3943 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
3944 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
3945 ** returned by sqlite3_column_type() is only meaningful if no type
3946 ** conversions have occurred as described below.  After a type conversion,
3947 ** the value returned by sqlite3_column_type() is undefined.  Future
3948 ** versions of SQLite may change the behavior of sqlite3_column_type()
3949 ** following a type conversion.
3950 **
3951 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3952 ** routine returns the number of bytes in that BLOB or string.
3953 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3954 ** the string to UTF-8 and then returns the number of bytes.
3955 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
3956 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3957 ** the number of bytes in that string.
3958 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
3959 **
3960 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
3961 ** routine returns the number of bytes in that BLOB or string.
3962 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
3963 ** the string to UTF-16 and then returns the number of bytes.
3964 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
3965 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
3966 ** the number of bytes in that string.
3967 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
3968 **
3969 ** ^The values returned by [sqlite3_column_bytes()] and
3970 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
3971 ** of the string.  ^For clarity: the values returned by
3972 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
3973 ** bytes in the string, not the number of characters.
3974 **
3975 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3976 ** even empty strings, are always zero-terminated.  ^The return
3977 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
3978 **
3979 ** ^The object returned by [sqlite3_column_value()] is an
3980 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
3981 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3982 ** If the [unprotected sqlite3_value] object returned by
3983 ** [sqlite3_column_value()] is used in any other way, including calls
3984 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
3985 ** or [sqlite3_value_bytes()], then the behavior is undefined.
3986 **
3987 ** These routines attempt to convert the value where appropriate.  ^For
3988 ** example, if the internal representation is FLOAT and a text result
3989 ** is requested, [sqlite3_snprintf()] is used internally to perform the
3990 ** conversion automatically.  ^(The following table details the conversions
3991 ** that are applied:
3992 **
3993 ** <blockquote>
3994 ** <table border="1">
3995 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
3996 **
3997 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
3998 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
3999 ** <tr><td>  NULL    <td>   TEXT    <td> Result is a NULL pointer
4000 ** <tr><td>  NULL    <td>   BLOB    <td> Result is a NULL pointer
4001 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
4002 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
4003 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4004 ** <tr><td>  FLOAT   <td> INTEGER   <td> [CAST] to INTEGER
4005 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4006 ** <tr><td>  FLOAT   <td>   BLOB    <td> [CAST] to BLOB
4007 ** <tr><td>  TEXT    <td> INTEGER   <td> [CAST] to INTEGER
4008 ** <tr><td>  TEXT    <td>  FLOAT    <td> [CAST] to REAL
4009 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
4010 ** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER
4011 ** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL
4012 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4013 ** </table>
4014 ** </blockquote>)^
4015 **
4016 ** The table above makes reference to standard C library functions atoi()
4017 ** and atof().  SQLite does not really use these functions.  It has its
4018 ** own equivalent internal routines.  The atoi() and atof() names are
4019 ** used in the table for brevity and because they are familiar to most
4020 ** C programmers.
4021 **
4022 ** Note that when type conversions occur, pointers returned by prior
4023 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4024 ** sqlite3_column_text16() may be invalidated.
4025 ** Type conversions and pointer invalidations might occur
4026 ** in the following cases:
4027 **
4028 ** <ul>
4029 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4030 **      sqlite3_column_text16() is called.  A zero-terminator might
4031 **      need to be added to the string.</li>
4032 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4033 **      sqlite3_column_text16() is called.  The content must be converted
4034 **      to UTF-16.</li>
4035 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4036 **      sqlite3_column_text() is called.  The content must be converted
4037 **      to UTF-8.</li>
4038 ** </ul>
4039 **
4040 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4041 ** not invalidate a prior pointer, though of course the content of the buffer
4042 ** that the prior pointer references will have been modified.  Other kinds
4043 ** of conversion are done in place when it is possible, but sometimes they
4044 ** are not possible and in those cases prior pointers are invalidated.
4045 **
4046 ** The safest and easiest to remember policy is to invoke these routines
4047 ** in one of the following ways:
4048 **
4049 ** <ul>
4050 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4051 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4052 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4053 ** </ul>
4054 **
4055 ** In other words, you should call sqlite3_column_text(),
4056 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4057 ** into the desired format, then invoke sqlite3_column_bytes() or
4058 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
4059 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4060 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4061 ** with calls to sqlite3_column_bytes().
4062 **
4063 ** ^The pointers returned are valid until a type conversion occurs as
4064 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4065 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
4066 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
4067 ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4068 ** [sqlite3_free()].
4069 **
4070 ** ^(If a memory allocation error occurs during the evaluation of any
4071 ** of these routines, a default value is returned.  The default value
4072 ** is either the integer 0, the floating point number 0.0, or a NULL
4073 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
4074 ** [SQLITE_NOMEM].)^
4075 */
4076 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4077 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4078 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4079 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4080 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
4081 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4082 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4083 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4084 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
4085 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
4086 
4087 /*
4088 ** CAPI3REF: Destroy A Prepared Statement Object
4089 **
4090 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4091 ** ^If the most recent evaluation of the statement encountered no errors
4092 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
4093 ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
4094 ** sqlite3_finalize(S) returns the appropriate [error code] or
4095 ** [extended error code].
4096 **
4097 ** ^The sqlite3_finalize(S) routine can be called at any point during
4098 ** the life cycle of [prepared statement] S:
4099 ** before statement S is ever evaluated, after
4100 ** one or more calls to [sqlite3_reset()], or after any call
4101 ** to [sqlite3_step()] regardless of whether or not the statement has
4102 ** completed execution.
4103 **
4104 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4105 **
4106 ** The application must finalize every [prepared statement] in order to avoid
4107 ** resource leaks.  It is a grievous error for the application to try to use
4108 ** a prepared statement after it has been finalized.  Any use of a prepared
4109 ** statement after it has been finalized can result in undefined and
4110 ** undesirable behavior such as segfaults and heap corruption.
4111 */
4112 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
4113 
4114 /*
4115 ** CAPI3REF: Reset A Prepared Statement Object
4116 **
4117 ** The sqlite3_reset() function is called to reset a [prepared statement]
4118 ** object back to its initial state, ready to be re-executed.
4119 ** ^Any SQL statement variables that had values bound to them using
4120 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4121 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4122 **
4123 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4124 ** back to the beginning of its program.
4125 **
4126 ** ^If the most recent call to [sqlite3_step(S)] for the
4127 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4128 ** or if [sqlite3_step(S)] has never before been called on S,
4129 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
4130 **
4131 ** ^If the most recent call to [sqlite3_step(S)] for the
4132 ** [prepared statement] S indicated an error, then
4133 ** [sqlite3_reset(S)] returns an appropriate [error code].
4134 **
4135 ** ^The [sqlite3_reset(S)] interface does not change the values
4136 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4137 */
4138 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
4139 
4140 /*
4141 ** CAPI3REF: Create Or Redefine SQL Functions
4142 ** KEYWORDS: {function creation routines}
4143 ** KEYWORDS: {application-defined SQL function}
4144 ** KEYWORDS: {application-defined SQL functions}
4145 **
4146 ** ^These functions (collectively known as "function creation routines")
4147 ** are used to add SQL functions or aggregates or to redefine the behavior
4148 ** of existing SQL functions or aggregates.  The only differences between
4149 ** these routines are the text encoding expected for
4150 ** the second parameter (the name of the function being created)
4151 ** and the presence or absence of a destructor callback for
4152 ** the application data pointer.
4153 **
4154 ** ^The first parameter is the [database connection] to which the SQL
4155 ** function is to be added.  ^If an application uses more than one database
4156 ** connection then application-defined SQL functions must be added
4157 ** to each database connection separately.
4158 **
4159 ** ^The second parameter is the name of the SQL function to be created or
4160 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
4161 ** representation, exclusive of the zero-terminator.  ^Note that the name
4162 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
4163 ** ^Any attempt to create a function with a longer name
4164 ** will result in [SQLITE_MISUSE] being returned.
4165 **
4166 ** ^The third parameter (nArg)
4167 ** is the number of arguments that the SQL function or
4168 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4169 ** aggregate may take any number of arguments between 0 and the limit
4170 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
4171 ** parameter is less than -1 or greater than 127 then the behavior is
4172 ** undefined.
4173 **
4174 ** ^The fourth parameter, eTextRep, specifies what
4175 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4176 ** its parameters.  The application should set this parameter to
4177 ** [SQLITE_UTF16LE] if the function implementation invokes
4178 ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
4179 ** implementation invokes [sqlite3_value_text16be()] on an input, or
4180 ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
4181 ** otherwise.  ^The same SQL function may be registered multiple times using
4182 ** different preferred text encodings, with different implementations for
4183 ** each encoding.
4184 ** ^When multiple implementations of the same function are available, SQLite
4185 ** will pick the one that involves the least amount of data conversion.
4186 **
4187 ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
4188 ** to signal that the function will always return the same result given
4189 ** the same inputs within a single SQL statement.  Most SQL functions are
4190 ** deterministic.  The built-in [random()] SQL function is an example of a
4191 ** function that is not deterministic.  The SQLite query planner is able to
4192 ** perform additional optimizations on deterministic functions, so use
4193 ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
4194 **
4195 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
4196 ** function can gain access to this pointer using [sqlite3_user_data()].)^
4197 **
4198 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4199 ** pointers to C-language functions that implement the SQL function or
4200 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4201 ** callback only; NULL pointers must be passed as the xStep and xFinal
4202 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4203 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4204 ** SQL function or aggregate, pass NULL pointers for all three function
4205 ** callbacks.
4206 **
4207 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4208 ** then it is destructor for the application data pointer.
4209 ** The destructor is invoked when the function is deleted, either by being
4210 ** overloaded or when the database connection closes.)^
4211 ** ^The destructor is also invoked if the call to
4212 ** sqlite3_create_function_v2() fails.
4213 ** ^When the destructor callback of the tenth parameter is invoked, it
4214 ** is passed a single argument which is a copy of the application data
4215 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4216 **
4217 ** ^It is permitted to register multiple implementations of the same
4218 ** functions with the same name but with either differing numbers of
4219 ** arguments or differing preferred text encodings.  ^SQLite will use
4220 ** the implementation that most closely matches the way in which the
4221 ** SQL function is used.  ^A function implementation with a non-negative
4222 ** nArg parameter is a better match than a function implementation with
4223 ** a negative nArg.  ^A function where the preferred text encoding
4224 ** matches the database encoding is a better
4225 ** match than a function where the encoding is different.
4226 ** ^A function where the encoding difference is between UTF16le and UTF16be
4227 ** is a closer match than a function where the encoding difference is
4228 ** between UTF8 and UTF16.
4229 **
4230 ** ^Built-in functions may be overloaded by new application-defined functions.
4231 **
4232 ** ^An application-defined function is permitted to call other
4233 ** SQLite interfaces.  However, such calls must not
4234 ** close the database connection nor finalize or reset the prepared
4235 ** statement in which the function is running.
4236 */
4237 SQLITE_API int sqlite3_create_function(
4238   sqlite3 *db,
4239   const char *zFunctionName,
4240   int nArg,
4241   int eTextRep,
4242   void *pApp,
4243   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4244   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4245   void (*xFinal)(sqlite3_context*)
4246 );
4247 SQLITE_API int sqlite3_create_function16(
4248   sqlite3 *db,
4249   const void *zFunctionName,
4250   int nArg,
4251   int eTextRep,
4252   void *pApp,
4253   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4254   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4255   void (*xFinal)(sqlite3_context*)
4256 );
4257 SQLITE_API int sqlite3_create_function_v2(
4258   sqlite3 *db,
4259   const char *zFunctionName,
4260   int nArg,
4261   int eTextRep,
4262   void *pApp,
4263   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4264   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4265   void (*xFinal)(sqlite3_context*),
4266   void(*xDestroy)(void*)
4267 );
4268 
4269 /*
4270 ** CAPI3REF: Text Encodings
4271 **
4272 ** These constant define integer codes that represent the various
4273 ** text encodings supported by SQLite.
4274 */
4275 #define SQLITE_UTF8           1
4276 #define SQLITE_UTF16LE        2
4277 #define SQLITE_UTF16BE        3
4278 #define SQLITE_UTF16          4    /* Use native byte order */
4279 #define SQLITE_ANY            5    /* Deprecated */
4280 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4281 
4282 /*
4283 ** CAPI3REF: Function Flags
4284 **
4285 ** These constants may be ORed together with the
4286 ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
4287 ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
4288 ** [sqlite3_create_function_v2()].
4289 */
4290 #define SQLITE_DETERMINISTIC    0x800
4291 
4292 /*
4293 ** CAPI3REF: Deprecated Functions
4294 ** DEPRECATED
4295 **
4296 ** These functions are [deprecated].  In order to maintain
4297 ** backwards compatibility with older code, these functions continue
4298 ** to be supported.  However, new applications should avoid
4299 ** the use of these functions.  To help encourage people to avoid
4300 ** using these functions, we are not going to tell you what they do.
4301 */
4302 #ifndef SQLITE_OMIT_DEPRECATED
4303 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4304 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4305 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4306 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4307 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4308 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
4309                       void*,sqlite3_int64);
4310 #endif
4311 
4312 /*
4313 ** CAPI3REF: Obtaining SQL Function Parameter Values
4314 **
4315 ** The C-language implementation of SQL functions and aggregates uses
4316 ** this set of interface routines to access the parameter values on
4317 ** the function or aggregate.
4318 **
4319 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4320 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4321 ** define callbacks that implement the SQL functions and aggregates.
4322 ** The 3rd parameter to these callbacks is an array of pointers to
4323 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4324 ** each parameter to the SQL function.  These routines are used to
4325 ** extract values from the [sqlite3_value] objects.
4326 **
4327 ** These routines work only with [protected sqlite3_value] objects.
4328 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4329 ** object results in undefined behavior.
4330 **
4331 ** ^These routines work just like the corresponding [column access functions]
4332 ** except that these routines take a single [protected sqlite3_value] object
4333 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4334 **
4335 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4336 ** in the native byte-order of the host machine.  ^The
4337 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4338 ** extract UTF-16 strings as big-endian and little-endian respectively.
4339 **
4340 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4341 ** numeric affinity to the value.  This means that an attempt is
4342 ** made to convert the value to an integer or floating point.  If
4343 ** such a conversion is possible without loss of information (in other
4344 ** words, if the value is a string that looks like a number)
4345 ** then the conversion is performed.  Otherwise no conversion occurs.
4346 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4347 **
4348 ** Please pay particular attention to the fact that the pointer returned
4349 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4350 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4351 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4352 ** or [sqlite3_value_text16()].
4353 **
4354 ** These routines must be called from the same thread as
4355 ** the SQL function that supplied the [sqlite3_value*] parameters.
4356 */
4357 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4358 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4359 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4360 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4361 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4362 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4363 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4364 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4365 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4366 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4367 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4368 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4369 
4370 /*
4371 ** CAPI3REF: Obtain Aggregate Function Context
4372 **
4373 ** Implementations of aggregate SQL functions use this
4374 ** routine to allocate memory for storing their state.
4375 **
4376 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
4377 ** for a particular aggregate function, SQLite
4378 ** allocates N of memory, zeroes out that memory, and returns a pointer
4379 ** to the new memory. ^On second and subsequent calls to
4380 ** sqlite3_aggregate_context() for the same aggregate function instance,
4381 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4382 ** called once for each invocation of the xStep callback and then one
4383 ** last time when the xFinal callback is invoked.  ^(When no rows match
4384 ** an aggregate query, the xStep() callback of the aggregate function
4385 ** implementation is never called and xFinal() is called exactly once.
4386 ** In those cases, sqlite3_aggregate_context() might be called for the
4387 ** first time from within xFinal().)^
4388 **
4389 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
4390 ** when first called if N is less than or equal to zero or if a memory
4391 ** allocate error occurs.
4392 **
4393 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4394 ** determined by the N parameter on first successful call.  Changing the
4395 ** value of N in subsequent call to sqlite3_aggregate_context() within
4396 ** the same aggregate function instance will not resize the memory
4397 ** allocation.)^  Within the xFinal callback, it is customary to set
4398 ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
4399 ** pointless memory allocations occur.
4400 **
4401 ** ^SQLite automatically frees the memory allocated by
4402 ** sqlite3_aggregate_context() when the aggregate query concludes.
4403 **
4404 ** The first parameter must be a copy of the
4405 ** [sqlite3_context | SQL function context] that is the first parameter
4406 ** to the xStep or xFinal callback routine that implements the aggregate
4407 ** function.
4408 **
4409 ** This routine must be called from the same thread in which
4410 ** the aggregate SQL function is running.
4411 */
4412 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4413 
4414 /*
4415 ** CAPI3REF: User Data For Functions
4416 **
4417 ** ^The sqlite3_user_data() interface returns a copy of
4418 ** the pointer that was the pUserData parameter (the 5th parameter)
4419 ** of the [sqlite3_create_function()]
4420 ** and [sqlite3_create_function16()] routines that originally
4421 ** registered the application defined function.
4422 **
4423 ** This routine must be called from the same thread in which
4424 ** the application-defined function is running.
4425 */
4426 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4427 
4428 /*
4429 ** CAPI3REF: Database Connection For Functions
4430 **
4431 ** ^The sqlite3_context_db_handle() interface returns a copy of
4432 ** the pointer to the [database connection] (the 1st parameter)
4433 ** of the [sqlite3_create_function()]
4434 ** and [sqlite3_create_function16()] routines that originally
4435 ** registered the application defined function.
4436 */
4437 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4438 
4439 /*
4440 ** CAPI3REF: Function Auxiliary Data
4441 **
4442 ** These functions may be used by (non-aggregate) SQL functions to
4443 ** associate metadata with argument values. If the same value is passed to
4444 ** multiple invocations of the same SQL function during query execution, under
4445 ** some circumstances the associated metadata may be preserved.  An example
4446 ** of where this might be useful is in a regular-expression matching
4447 ** function. The compiled version of the regular expression can be stored as
4448 ** metadata associated with the pattern string.
4449 ** Then as long as the pattern string remains the same,
4450 ** the compiled regular expression can be reused on multiple
4451 ** invocations of the same function.
4452 **
4453 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4454 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4455 ** value to the application-defined function. ^If there is no metadata
4456 ** associated with the function argument, this sqlite3_get_auxdata() interface
4457 ** returns a NULL pointer.
4458 **
4459 ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
4460 ** argument of the application-defined function.  ^Subsequent
4461 ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
4462 ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
4463 ** NULL if the metadata has been discarded.
4464 ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
4465 ** SQLite will invoke the destructor function X with parameter P exactly
4466 ** once, when the metadata is discarded.
4467 ** SQLite is free to discard the metadata at any time, including: <ul>
4468 ** <li> when the corresponding function parameter changes, or
4469 ** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
4470 **      SQL statement, or
4471 ** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
4472 ** <li> during the original sqlite3_set_auxdata() call when a memory
4473 **      allocation error occurs. </ul>)^
4474 **
4475 ** Note the last bullet in particular.  The destructor X in
4476 ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
4477 ** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()
4478 ** should be called near the end of the function implementation and the
4479 ** function implementation should not make any use of P after
4480 ** sqlite3_set_auxdata() has been called.
4481 **
4482 ** ^(In practice, metadata is preserved between function calls for
4483 ** function parameters that are compile-time constants, including literal
4484 ** values and [parameters] and expressions composed from the same.)^
4485 **
4486 ** These routines must be called from the same thread in which
4487 ** the SQL function is running.
4488 */
4489 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4490 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4491 
4492 
4493 /*
4494 ** CAPI3REF: Constants Defining Special Destructor Behavior
4495 **
4496 ** These are special values for the destructor that is passed in as the
4497 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4498 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4499 ** and will never change.  It does not need to be destroyed.  ^The
4500 ** SQLITE_TRANSIENT value means that the content will likely change in
4501 ** the near future and that SQLite should make its own private copy of
4502 ** the content before returning.
4503 **
4504 ** The typedef is necessary to work around problems in certain
4505 ** C++ compilers.
4506 */
4507 typedef void (*sqlite3_destructor_type)(void*);
4508 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4509 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4510 
4511 /*
4512 ** CAPI3REF: Setting The Result Of An SQL Function
4513 **
4514 ** These routines are used by the xFunc or xFinal callbacks that
4515 ** implement SQL functions and aggregates.  See
4516 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4517 ** for additional information.
4518 **
4519 ** These functions work very much like the [parameter binding] family of
4520 ** functions used to bind values to host parameters in prepared statements.
4521 ** Refer to the [SQL parameter] documentation for additional information.
4522 **
4523 ** ^The sqlite3_result_blob() interface sets the result from
4524 ** an application-defined function to be the BLOB whose content is pointed
4525 ** to by the second parameter and which is N bytes long where N is the
4526 ** third parameter.
4527 **
4528 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4529 ** the application-defined function to be a BLOB containing all zero
4530 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4531 **
4532 ** ^The sqlite3_result_double() interface sets the result from
4533 ** an application-defined function to be a floating point value specified
4534 ** by its 2nd argument.
4535 **
4536 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4537 ** cause the implemented SQL function to throw an exception.
4538 ** ^SQLite uses the string pointed to by the
4539 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4540 ** as the text of an error message.  ^SQLite interprets the error
4541 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4542 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4543 ** byte order.  ^If the third parameter to sqlite3_result_error()
4544 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4545 ** message all text up through the first zero character.
4546 ** ^If the third parameter to sqlite3_result_error() or
4547 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4548 ** bytes (not characters) from the 2nd parameter as the error message.
4549 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4550 ** routines make a private copy of the error message text before
4551 ** they return.  Hence, the calling function can deallocate or
4552 ** modify the text after they return without harm.
4553 ** ^The sqlite3_result_error_code() function changes the error code
4554 ** returned by SQLite as a result of an error in a function.  ^By default,
4555 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4556 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4557 **
4558 ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
4559 ** error indicating that a string or BLOB is too long to represent.
4560 **
4561 ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
4562 ** error indicating that a memory allocation failed.
4563 **
4564 ** ^The sqlite3_result_int() interface sets the return value
4565 ** of the application-defined function to be the 32-bit signed integer
4566 ** value given in the 2nd argument.
4567 ** ^The sqlite3_result_int64() interface sets the return value
4568 ** of the application-defined function to be the 64-bit signed integer
4569 ** value given in the 2nd argument.
4570 **
4571 ** ^The sqlite3_result_null() interface sets the return value
4572 ** of the application-defined function to be NULL.
4573 **
4574 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4575 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4576 ** set the return value of the application-defined function to be
4577 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4578 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4579 ** ^The sqlite3_result_text64() interface sets the return value of an
4580 ** application-defined function to be a text string in an encoding
4581 ** specified by the fifth (and last) parameter, which must be one
4582 ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
4583 ** ^SQLite takes the text result from the application from
4584 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4585 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4586 ** is negative, then SQLite takes result text from the 2nd parameter
4587 ** through the first zero character.
4588 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4589 ** is non-negative, then as many bytes (not characters) of the text
4590 ** pointed to by the 2nd parameter are taken as the application-defined
4591 ** function result.  If the 3rd parameter is non-negative, then it
4592 ** must be the byte offset into the string where the NUL terminator would
4593 ** appear if the string where NUL terminated.  If any NUL characters occur
4594 ** in the string at a byte offset that is less than the value of the 3rd
4595 ** parameter, then the resulting string will contain embedded NULs and the
4596 ** result of expressions operating on strings with embedded NULs is undefined.
4597 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4598 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4599 ** function as the destructor on the text or BLOB result when it has
4600 ** finished using that result.
4601 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4602 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4603 ** assumes that the text or BLOB result is in constant space and does not
4604 ** copy the content of the parameter nor call a destructor on the content
4605 ** when it has finished using that result.
4606 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4607 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4608 ** then SQLite makes a copy of the result into space obtained from
4609 ** from [sqlite3_malloc()] before it returns.
4610 **
4611 ** ^The sqlite3_result_value() interface sets the result of
4612 ** the application-defined function to be a copy the
4613 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4614 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4615 ** so that the [sqlite3_value] specified in the parameter may change or
4616 ** be deallocated after sqlite3_result_value() returns without harm.
4617 ** ^A [protected sqlite3_value] object may always be used where an
4618 ** [unprotected sqlite3_value] object is required, so either
4619 ** kind of [sqlite3_value] object can be used with this interface.
4620 **
4621 ** If these routines are called from within the different thread
4622 ** than the one containing the application-defined function that received
4623 ** the [sqlite3_context] pointer, the results are undefined.
4624 */
4625 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4626 SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,sqlite3_uint64,void(*)(void*));
4627 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4628 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4629 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4630 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4631 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4632 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4633 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4634 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4635 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4636 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4637 SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
4638                            void(*)(void*), unsigned char encoding);
4639 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4640 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4641 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4642 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4643 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4644 
4645 /*
4646 ** CAPI3REF: Define New Collating Sequences
4647 **
4648 ** ^These functions add, remove, or modify a [collation] associated
4649 ** with the [database connection] specified as the first argument.
4650 **
4651 ** ^The name of the collation is a UTF-8 string
4652 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4653 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4654 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4655 ** considered to be the same name.
4656 **
4657 ** ^(The third argument (eTextRep) must be one of the constants:
4658 ** <ul>
4659 ** <li> [SQLITE_UTF8],
4660 ** <li> [SQLITE_UTF16LE],
4661 ** <li> [SQLITE_UTF16BE],
4662 ** <li> [SQLITE_UTF16], or
4663 ** <li> [SQLITE_UTF16_ALIGNED].
4664 ** </ul>)^
4665 ** ^The eTextRep argument determines the encoding of strings passed
4666 ** to the collating function callback, xCallback.
4667 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4668 ** force strings to be UTF16 with native byte order.
4669 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4670 ** on an even byte address.
4671 **
4672 ** ^The fourth argument, pArg, is an application data pointer that is passed
4673 ** through as the first argument to the collating function callback.
4674 **
4675 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4676 ** ^Multiple collating functions can be registered using the same name but
4677 ** with different eTextRep parameters and SQLite will use whichever
4678 ** function requires the least amount of data transformation.
4679 ** ^If the xCallback argument is NULL then the collating function is
4680 ** deleted.  ^When all collating functions having the same name are deleted,
4681 ** that collation is no longer usable.
4682 **
4683 ** ^The collating function callback is invoked with a copy of the pArg
4684 ** application data pointer and with two strings in the encoding specified
4685 ** by the eTextRep argument.  The collating function must return an
4686 ** integer that is negative, zero, or positive
4687 ** if the first string is less than, equal to, or greater than the second,
4688 ** respectively.  A collating function must always return the same answer
4689 ** given the same inputs.  If two or more collating functions are registered
4690 ** to the same collation name (using different eTextRep values) then all
4691 ** must give an equivalent answer when invoked with equivalent strings.
4692 ** The collating function must obey the following properties for all
4693 ** strings A, B, and C:
4694 **
4695 ** <ol>
4696 ** <li> If A==B then B==A.
4697 ** <li> If A==B and B==C then A==C.
4698 ** <li> If A&lt;B THEN B&gt;A.
4699 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4700 ** </ol>
4701 **
4702 ** If a collating function fails any of the above constraints and that
4703 ** collating function is  registered and used, then the behavior of SQLite
4704 ** is undefined.
4705 **
4706 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4707 ** with the addition that the xDestroy callback is invoked on pArg when
4708 ** the collating function is deleted.
4709 ** ^Collating functions are deleted when they are overridden by later
4710 ** calls to the collation creation functions or when the
4711 ** [database connection] is closed using [sqlite3_close()].
4712 **
4713 ** ^The xDestroy callback is <u>not</u> called if the
4714 ** sqlite3_create_collation_v2() function fails.  Applications that invoke
4715 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
4716 ** check the return code and dispose of the application data pointer
4717 ** themselves rather than expecting SQLite to deal with it for them.
4718 ** This is different from every other SQLite interface.  The inconsistency
4719 ** is unfortunate but cannot be changed without breaking backwards
4720 ** compatibility.
4721 **
4722 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4723 */
4724 SQLITE_API int sqlite3_create_collation(
4725   sqlite3*,
4726   const char *zName,
4727   int eTextRep,
4728   void *pArg,
4729   int(*xCompare)(void*,int,const void*,int,const void*)
4730 );
4731 SQLITE_API int sqlite3_create_collation_v2(
4732   sqlite3*,
4733   const char *zName,
4734   int eTextRep,
4735   void *pArg,
4736   int(*xCompare)(void*,int,const void*,int,const void*),
4737   void(*xDestroy)(void*)
4738 );
4739 SQLITE_API int sqlite3_create_collation16(
4740   sqlite3*,
4741   const void *zName,
4742   int eTextRep,
4743   void *pArg,
4744   int(*xCompare)(void*,int,const void*,int,const void*)
4745 );
4746 
4747 /*
4748 ** CAPI3REF: Collation Needed Callbacks
4749 **
4750 ** ^To avoid having to register all collation sequences before a database
4751 ** can be used, a single callback function may be registered with the
4752 ** [database connection] to be invoked whenever an undefined collation
4753 ** sequence is required.
4754 **
4755 ** ^If the function is registered using the sqlite3_collation_needed() API,
4756 ** then it is passed the names of undefined collation sequences as strings
4757 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4758 ** the names are passed as UTF-16 in machine native byte order.
4759 ** ^A call to either function replaces the existing collation-needed callback.
4760 **
4761 ** ^(When the callback is invoked, the first argument passed is a copy
4762 ** of the second argument to sqlite3_collation_needed() or
4763 ** sqlite3_collation_needed16().  The second argument is the database
4764 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4765 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4766 ** sequence function required.  The fourth parameter is the name of the
4767 ** required collation sequence.)^
4768 **
4769 ** The callback function should register the desired collation using
4770 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4771 ** [sqlite3_create_collation_v2()].
4772 */
4773 SQLITE_API int sqlite3_collation_needed(
4774   sqlite3*,
4775   void*,
4776   void(*)(void*,sqlite3*,int eTextRep,const char*)
4777 );
4778 SQLITE_API int sqlite3_collation_needed16(
4779   sqlite3*,
4780   void*,
4781   void(*)(void*,sqlite3*,int eTextRep,const void*)
4782 );
4783 
4784 #ifdef SQLITE_HAS_CODEC
4785 /*
4786 ** Specify the key for an encrypted database.  This routine should be
4787 ** called right after sqlite3_open().
4788 **
4789 ** The code to implement this API is not available in the public release
4790 ** of SQLite.
4791 */
4792 SQLITE_API int sqlite3_key(
4793   sqlite3 *db,                   /* Database to be rekeyed */
4794   const void *pKey, int nKey     /* The key */
4795 );
4796 SQLITE_API int sqlite3_key_v2(
4797   sqlite3 *db,                   /* Database to be rekeyed */
4798   const char *zDbName,           /* Name of the database */
4799   const void *pKey, int nKey     /* The key */
4800 );
4801 
4802 /*
4803 ** Change the key on an open database.  If the current database is not
4804 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4805 ** database is decrypted.
4806 **
4807 ** The code to implement this API is not available in the public release
4808 ** of SQLite.
4809 */
4810 SQLITE_API int sqlite3_rekey(
4811   sqlite3 *db,                   /* Database to be rekeyed */
4812   const void *pKey, int nKey     /* The new key */
4813 );
4814 SQLITE_API int sqlite3_rekey_v2(
4815   sqlite3 *db,                   /* Database to be rekeyed */
4816   const char *zDbName,           /* Name of the database */
4817   const void *pKey, int nKey     /* The new key */
4818 );
4819 
4820 /*
4821 ** Specify the activation key for a SEE database.  Unless
4822 ** activated, none of the SEE routines will work.
4823 */
4824 SQLITE_API void sqlite3_activate_see(
4825   const char *zPassPhrase        /* Activation phrase */
4826 );
4827 #endif
4828 
4829 #ifdef SQLITE_ENABLE_CEROD
4830 /*
4831 ** Specify the activation key for a CEROD database.  Unless
4832 ** activated, none of the CEROD routines will work.
4833 */
4834 SQLITE_API void sqlite3_activate_cerod(
4835   const char *zPassPhrase        /* Activation phrase */
4836 );
4837 #endif
4838 
4839 /*
4840 ** CAPI3REF: Suspend Execution For A Short Time
4841 **
4842 ** The sqlite3_sleep() function causes the current thread to suspend execution
4843 ** for at least a number of milliseconds specified in its parameter.
4844 **
4845 ** If the operating system does not support sleep requests with
4846 ** millisecond time resolution, then the time will be rounded up to
4847 ** the nearest second. The number of milliseconds of sleep actually
4848 ** requested from the operating system is returned.
4849 **
4850 ** ^SQLite implements this interface by calling the xSleep()
4851 ** method of the default [sqlite3_vfs] object.  If the xSleep() method
4852 ** of the default VFS is not implemented correctly, or not implemented at
4853 ** all, then the behavior of sqlite3_sleep() may deviate from the description
4854 ** in the previous paragraphs.
4855 */
4856 SQLITE_API int sqlite3_sleep(int);
4857 
4858 /*
4859 ** CAPI3REF: Name Of The Folder Holding Temporary Files
4860 **
4861 ** ^(If this global variable is made to point to a string which is
4862 ** the name of a folder (a.k.a. directory), then all temporary files
4863 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4864 ** will be placed in that directory.)^  ^If this variable
4865 ** is a NULL pointer, then SQLite performs a search for an appropriate
4866 ** temporary file directory.
4867 **
4868 ** Applications are strongly discouraged from using this global variable.
4869 ** It is required to set a temporary folder on Windows Runtime (WinRT).
4870 ** But for all other platforms, it is highly recommended that applications
4871 ** neither read nor write this variable.  This global variable is a relic
4872 ** that exists for backwards compatibility of legacy applications and should
4873 ** be avoided in new projects.
4874 **
4875 ** It is not safe to read or modify this variable in more than one
4876 ** thread at a time.  It is not safe to read or modify this variable
4877 ** if a [database connection] is being used at the same time in a separate
4878 ** thread.
4879 ** It is intended that this variable be set once
4880 ** as part of process initialization and before any SQLite interface
4881 ** routines have been called and that this variable remain unchanged
4882 ** thereafter.
4883 **
4884 ** ^The [temp_store_directory pragma] may modify this variable and cause
4885 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
4886 ** the [temp_store_directory pragma] always assumes that any string
4887 ** that this variable points to is held in memory obtained from
4888 ** [sqlite3_malloc] and the pragma may attempt to free that memory
4889 ** using [sqlite3_free].
4890 ** Hence, if this variable is modified directly, either it should be
4891 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
4892 ** or else the use of the [temp_store_directory pragma] should be avoided.
4893 ** Except when requested by the [temp_store_directory pragma], SQLite
4894 ** does not free the memory that sqlite3_temp_directory points to.  If
4895 ** the application wants that memory to be freed, it must do
4896 ** so itself, taking care to only do so after all [database connection]
4897 ** objects have been destroyed.
4898 **
4899 ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
4900 ** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various
4901 ** features that require the use of temporary files may fail.  Here is an
4902 ** example of how to do this using C++ with the Windows Runtime:
4903 **
4904 ** <blockquote><pre>
4905 ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
4906 ** &nbsp;     TemporaryFolder->Path->Data();
4907 ** char zPathBuf&#91;MAX_PATH + 1&#93;;
4908 ** memset(zPathBuf, 0, sizeof(zPathBuf));
4909 ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
4910 ** &nbsp;     NULL, NULL);
4911 ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
4912 ** </pre></blockquote>
4913 */
4914 SQLITE_API char *sqlite3_temp_directory;
4915 
4916 /*
4917 ** CAPI3REF: Name Of The Folder Holding Database Files
4918 **
4919 ** ^(If this global variable is made to point to a string which is
4920 ** the name of a folder (a.k.a. directory), then all database files
4921 ** specified with a relative pathname and created or accessed by
4922 ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
4923 ** to be relative to that directory.)^ ^If this variable is a NULL
4924 ** pointer, then SQLite assumes that all database files specified
4925 ** with a relative pathname are relative to the current directory
4926 ** for the process.  Only the windows VFS makes use of this global
4927 ** variable; it is ignored by the unix VFS.
4928 **
4929 ** Changing the value of this variable while a database connection is
4930 ** open can result in a corrupt database.
4931 **
4932 ** It is not safe to read or modify this variable in more than one
4933 ** thread at a time.  It is not safe to read or modify this variable
4934 ** if a [database connection] is being used at the same time in a separate
4935 ** thread.
4936 ** It is intended that this variable be set once
4937 ** as part of process initialization and before any SQLite interface
4938 ** routines have been called and that this variable remain unchanged
4939 ** thereafter.
4940 **
4941 ** ^The [data_store_directory pragma] may modify this variable and cause
4942 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
4943 ** the [data_store_directory pragma] always assumes that any string
4944 ** that this variable points to is held in memory obtained from
4945 ** [sqlite3_malloc] and the pragma may attempt to free that memory
4946 ** using [sqlite3_free].
4947 ** Hence, if this variable is modified directly, either it should be
4948 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
4949 ** or else the use of the [data_store_directory pragma] should be avoided.
4950 */
4951 SQLITE_API char *sqlite3_data_directory;
4952 
4953 /*
4954 ** CAPI3REF: Test For Auto-Commit Mode
4955 ** KEYWORDS: {autocommit mode}
4956 **
4957 ** ^The sqlite3_get_autocommit() interface returns non-zero or
4958 ** zero if the given database connection is or is not in autocommit mode,
4959 ** respectively.  ^Autocommit mode is on by default.
4960 ** ^Autocommit mode is disabled by a [BEGIN] statement.
4961 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4962 **
4963 ** If certain kinds of errors occur on a statement within a multi-statement
4964 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
4965 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4966 ** transaction might be rolled back automatically.  The only way to
4967 ** find out whether SQLite automatically rolled back the transaction after
4968 ** an error is to use this function.
4969 **
4970 ** If another thread changes the autocommit status of the database
4971 ** connection while this routine is running, then the return value
4972 ** is undefined.
4973 */
4974 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4975 
4976 /*
4977 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
4978 **
4979 ** ^The sqlite3_db_handle interface returns the [database connection] handle
4980 ** to which a [prepared statement] belongs.  ^The [database connection]
4981 ** returned by sqlite3_db_handle is the same [database connection]
4982 ** that was the first argument
4983 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
4984 ** create the statement in the first place.
4985 */
4986 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4987 
4988 /*
4989 ** CAPI3REF: Return The Filename For A Database Connection
4990 **
4991 ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
4992 ** associated with database N of connection D.  ^The main database file
4993 ** has the name "main".  If there is no attached database N on the database
4994 ** connection D, or if database N is a temporary or in-memory database, then
4995 ** a NULL pointer is returned.
4996 **
4997 ** ^The filename returned by this function is the output of the
4998 ** xFullPathname method of the [VFS].  ^In other words, the filename
4999 ** will be an absolute pathname, even if the filename used
5000 ** to open the database originally was a URI or relative pathname.
5001 */
5002 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
5003 
5004 /*
5005 ** CAPI3REF: Determine if a database is read-only
5006 **
5007 ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
5008 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
5009 ** the name of a database on connection D.
5010 */
5011 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
5012 
5013 /*
5014 ** CAPI3REF: Find the next prepared statement
5015 **
5016 ** ^This interface returns a pointer to the next [prepared statement] after
5017 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
5018 ** then this interface returns a pointer to the first prepared statement
5019 ** associated with the database connection pDb.  ^If no prepared statement
5020 ** satisfies the conditions of this routine, it returns NULL.
5021 **
5022 ** The [database connection] pointer D in a call to
5023 ** [sqlite3_next_stmt(D,S)] must refer to an open database
5024 ** connection and in particular must not be a NULL pointer.
5025 */
5026 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5027 
5028 /*
5029 ** CAPI3REF: Commit And Rollback Notification Callbacks
5030 **
5031 ** ^The sqlite3_commit_hook() interface registers a callback
5032 ** function to be invoked whenever a transaction is [COMMIT | committed].
5033 ** ^Any callback set by a previous call to sqlite3_commit_hook()
5034 ** for the same database connection is overridden.
5035 ** ^The sqlite3_rollback_hook() interface registers a callback
5036 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
5037 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
5038 ** for the same database connection is overridden.
5039 ** ^The pArg argument is passed through to the callback.
5040 ** ^If the callback on a commit hook function returns non-zero,
5041 ** then the commit is converted into a rollback.
5042 **
5043 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
5044 ** return the P argument from the previous call of the same function
5045 ** on the same [database connection] D, or NULL for
5046 ** the first call for each function on D.
5047 **
5048 ** The commit and rollback hook callbacks are not reentrant.
5049 ** The callback implementation must not do anything that will modify
5050 ** the database connection that invoked the callback.  Any actions
5051 ** to modify the database connection must be deferred until after the
5052 ** completion of the [sqlite3_step()] call that triggered the commit
5053 ** or rollback hook in the first place.
5054 ** Note that running any other SQL statements, including SELECT statements,
5055 ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
5056 ** the database connections for the meaning of "modify" in this paragraph.
5057 **
5058 ** ^Registering a NULL function disables the callback.
5059 **
5060 ** ^When the commit hook callback routine returns zero, the [COMMIT]
5061 ** operation is allowed to continue normally.  ^If the commit hook
5062 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
5063 ** ^The rollback hook is invoked on a rollback that results from a commit
5064 ** hook returning non-zero, just as it would be with any other rollback.
5065 **
5066 ** ^For the purposes of this API, a transaction is said to have been
5067 ** rolled back if an explicit "ROLLBACK" statement is executed, or
5068 ** an error or constraint causes an implicit rollback to occur.
5069 ** ^The rollback callback is not invoked if a transaction is
5070 ** automatically rolled back because the database connection is closed.
5071 **
5072 ** See also the [sqlite3_update_hook()] interface.
5073 */
5074 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5075 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5076 
5077 /*
5078 ** CAPI3REF: Data Change Notification Callbacks
5079 **
5080 ** ^The sqlite3_update_hook() interface registers a callback function
5081 ** with the [database connection] identified by the first argument
5082 ** to be invoked whenever a row is updated, inserted or deleted in
5083 ** a rowid table.
5084 ** ^Any callback set by a previous call to this function
5085 ** for the same database connection is overridden.
5086 **
5087 ** ^The second argument is a pointer to the function to invoke when a
5088 ** row is updated, inserted or deleted in a rowid table.
5089 ** ^The first argument to the callback is a copy of the third argument
5090 ** to sqlite3_update_hook().
5091 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5092 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
5093 ** to be invoked.
5094 ** ^The third and fourth arguments to the callback contain pointers to the
5095 ** database and table name containing the affected row.
5096 ** ^The final callback parameter is the [rowid] of the row.
5097 ** ^In the case of an update, this is the [rowid] after the update takes place.
5098 **
5099 ** ^(The update hook is not invoked when internal system tables are
5100 ** modified (i.e. sqlite_master and sqlite_sequence).)^
5101 ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
5102 **
5103 ** ^In the current implementation, the update hook
5104 ** is not invoked when duplication rows are deleted because of an
5105 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
5106 ** invoked when rows are deleted using the [truncate optimization].
5107 ** The exceptions defined in this paragraph might change in a future
5108 ** release of SQLite.
5109 **
5110 ** The update hook implementation must not do anything that will modify
5111 ** the database connection that invoked the update hook.  Any actions
5112 ** to modify the database connection must be deferred until after the
5113 ** completion of the [sqlite3_step()] call that triggered the update hook.
5114 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5115 ** database connections for the meaning of "modify" in this paragraph.
5116 **
5117 ** ^The sqlite3_update_hook(D,C,P) function
5118 ** returns the P argument from the previous call
5119 ** on the same [database connection] D, or NULL for
5120 ** the first call on D.
5121 **
5122 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
5123 ** interfaces.
5124 */
5125 SQLITE_API void *sqlite3_update_hook(
5126   sqlite3*,
5127   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5128   void*
5129 );
5130 
5131 /*
5132 ** CAPI3REF: Enable Or Disable Shared Pager Cache
5133 **
5134 ** ^(This routine enables or disables the sharing of the database cache
5135 ** and schema data structures between [database connection | connections]
5136 ** to the same database. Sharing is enabled if the argument is true
5137 ** and disabled if the argument is false.)^
5138 **
5139 ** ^Cache sharing is enabled and disabled for an entire process.
5140 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5141 ** sharing was enabled or disabled for each thread separately.
5142 **
5143 ** ^(The cache sharing mode set by this interface effects all subsequent
5144 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5145 ** Existing database connections continue use the sharing mode
5146 ** that was in effect at the time they were opened.)^
5147 **
5148 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5149 ** successfully.  An [error code] is returned otherwise.)^
5150 **
5151 ** ^Shared cache is disabled by default. But this might change in
5152 ** future releases of SQLite.  Applications that care about shared
5153 ** cache setting should set it explicitly.
5154 **
5155 ** This interface is threadsafe on processors where writing a
5156 ** 32-bit integer is atomic.
5157 **
5158 ** See Also:  [SQLite Shared-Cache Mode]
5159 */
5160 SQLITE_API int sqlite3_enable_shared_cache(int);
5161 
5162 /*
5163 ** CAPI3REF: Attempt To Free Heap Memory
5164 **
5165 ** ^The sqlite3_release_memory() interface attempts to free N bytes
5166 ** of heap memory by deallocating non-essential memory allocations
5167 ** held by the database library.   Memory used to cache database
5168 ** pages to improve performance is an example of non-essential memory.
5169 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
5170 ** which might be more or less than the amount requested.
5171 ** ^The sqlite3_release_memory() routine is a no-op returning zero
5172 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5173 **
5174 ** See also: [sqlite3_db_release_memory()]
5175 */
5176 SQLITE_API int sqlite3_release_memory(int);
5177 
5178 /*
5179 ** CAPI3REF: Free Memory Used By A Database Connection
5180 **
5181 ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5182 ** memory as possible from database connection D. Unlike the
5183 ** [sqlite3_release_memory()] interface, this interface is in effect even
5184 ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5185 ** omitted.
5186 **
5187 ** See also: [sqlite3_release_memory()]
5188 */
5189 SQLITE_API int sqlite3_db_release_memory(sqlite3*);
5190 
5191 /*
5192 ** CAPI3REF: Impose A Limit On Heap Size
5193 **
5194 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5195 ** soft limit on the amount of heap memory that may be allocated by SQLite.
5196 ** ^SQLite strives to keep heap memory utilization below the soft heap
5197 ** limit by reducing the number of pages held in the page cache
5198 ** as heap memory usages approaches the limit.
5199 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
5200 ** below the limit, it will exceed the limit rather than generate
5201 ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit
5202 ** is advisory only.
5203 **
5204 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
5205 ** the soft heap limit prior to the call, or negative in the case of an
5206 ** error.  ^If the argument N is negative
5207 ** then no change is made to the soft heap limit.  Hence, the current
5208 ** size of the soft heap limit can be determined by invoking
5209 ** sqlite3_soft_heap_limit64() with a negative argument.
5210 **
5211 ** ^If the argument N is zero then the soft heap limit is disabled.
5212 **
5213 ** ^(The soft heap limit is not enforced in the current implementation
5214 ** if one or more of following conditions are true:
5215 **
5216 ** <ul>
5217 ** <li> The soft heap limit is set to zero.
5218 ** <li> Memory accounting is disabled using a combination of the
5219 **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5220 **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5221 ** <li> An alternative page cache implementation is specified using
5222 **      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5223 ** <li> The page cache allocates from its own memory pool supplied
5224 **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5225 **      from the heap.
5226 ** </ul>)^
5227 **
5228 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5229 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5230 ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5231 ** the soft heap limit is enforced on every memory allocation.  Without
5232 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5233 ** when memory is allocated by the page cache.  Testing suggests that because
5234 ** the page cache is the predominate memory user in SQLite, most
5235 ** applications will achieve adequate soft heap limit enforcement without
5236 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5237 **
5238 ** The circumstances under which SQLite will enforce the soft heap limit may
5239 ** changes in future releases of SQLite.
5240 */
5241 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
5242 
5243 /*
5244 ** CAPI3REF: Deprecated Soft Heap Limit Interface
5245 ** DEPRECATED
5246 **
5247 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5248 ** interface.  This routine is provided for historical compatibility
5249 ** only.  All new applications should use the
5250 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
5251 */
5252 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
5253 
5254 
5255 /*
5256 ** CAPI3REF: Extract Metadata About A Column Of A Table
5257 **
5258 ** ^This routine returns metadata about a specific column of a specific
5259 ** database table accessible using the [database connection] handle
5260 ** passed as the first function argument.
5261 **
5262 ** ^The column is identified by the second, third and fourth parameters to
5263 ** this function. ^The second parameter is either the name of the database
5264 ** (i.e. "main", "temp", or an attached database) containing the specified
5265 ** table or NULL. ^If it is NULL, then all attached databases are searched
5266 ** for the table using the same algorithm used by the database engine to
5267 ** resolve unqualified table references.
5268 **
5269 ** ^The third and fourth parameters to this function are the table and column
5270 ** name of the desired column, respectively. Neither of these parameters
5271 ** may be NULL.
5272 **
5273 ** ^Metadata is returned by writing to the memory locations passed as the 5th
5274 ** and subsequent parameters to this function. ^Any of these arguments may be
5275 ** NULL, in which case the corresponding element of metadata is omitted.
5276 **
5277 ** ^(<blockquote>
5278 ** <table border="1">
5279 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
5280 **
5281 ** <tr><td> 5th <td> const char* <td> Data type
5282 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5283 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5284 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5285 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
5286 ** </table>
5287 ** </blockquote>)^
5288 **
5289 ** ^The memory pointed to by the character pointers returned for the
5290 ** declaration type and collation sequence is valid only until the next
5291 ** call to any SQLite API function.
5292 **
5293 ** ^If the specified table is actually a view, an [error code] is returned.
5294 **
5295 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
5296 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5297 ** parameters are set for the explicitly declared column. ^(If there is no
5298 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
5299 ** parameters are set as follows:
5300 **
5301 ** <pre>
5302 **     data type: "INTEGER"
5303 **     collation sequence: "BINARY"
5304 **     not null: 0
5305 **     primary key: 1
5306 **     auto increment: 0
5307 ** </pre>)^
5308 **
5309 ** ^(This function may load one or more schemas from database files. If an
5310 ** error occurs during this process, or if the requested table or column
5311 ** cannot be found, an [error code] is returned and an error message left
5312 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
5313 **
5314 ** ^This API is only available if the library was compiled with the
5315 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5316 */
5317 SQLITE_API int sqlite3_table_column_metadata(
5318   sqlite3 *db,                /* Connection handle */
5319   const char *zDbName,        /* Database name or NULL */
5320   const char *zTableName,     /* Table name */
5321   const char *zColumnName,    /* Column name */
5322   char const **pzDataType,    /* OUTPUT: Declared data type */
5323   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5324   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5325   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5326   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5327 );
5328 
5329 /*
5330 ** CAPI3REF: Load An Extension
5331 **
5332 ** ^This interface loads an SQLite extension library from the named file.
5333 **
5334 ** ^The sqlite3_load_extension() interface attempts to load an
5335 ** [SQLite extension] library contained in the file zFile.  If
5336 ** the file cannot be loaded directly, attempts are made to load
5337 ** with various operating-system specific extensions added.
5338 ** So for example, if "samplelib" cannot be loaded, then names like
5339 ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
5340 ** be tried also.
5341 **
5342 ** ^The entry point is zProc.
5343 ** ^(zProc may be 0, in which case SQLite will try to come up with an
5344 ** entry point name on its own.  It first tries "sqlite3_extension_init".
5345 ** If that does not work, it constructs a name "sqlite3_X_init" where the
5346 ** X is consists of the lower-case equivalent of all ASCII alphabetic
5347 ** characters in the filename from the last "/" to the first following
5348 ** "." and omitting any initial "lib".)^
5349 ** ^The sqlite3_load_extension() interface returns
5350 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5351 ** ^If an error occurs and pzErrMsg is not 0, then the
5352 ** [sqlite3_load_extension()] interface shall attempt to
5353 ** fill *pzErrMsg with error message text stored in memory
5354 ** obtained from [sqlite3_malloc()]. The calling function
5355 ** should free this memory by calling [sqlite3_free()].
5356 **
5357 ** ^Extension loading must be enabled using
5358 ** [sqlite3_enable_load_extension()] prior to calling this API,
5359 ** otherwise an error will be returned.
5360 **
5361 ** See also the [load_extension() SQL function].
5362 */
5363 SQLITE_API int sqlite3_load_extension(
5364   sqlite3 *db,          /* Load the extension into this database connection */
5365   const char *zFile,    /* Name of the shared library containing extension */
5366   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5367   char **pzErrMsg       /* Put error message here if not 0 */
5368 );
5369 
5370 /*
5371 ** CAPI3REF: Enable Or Disable Extension Loading
5372 **
5373 ** ^So as not to open security holes in older applications that are
5374 ** unprepared to deal with [extension loading], and as a means of disabling
5375 ** [extension loading] while evaluating user-entered SQL, the following API
5376 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5377 **
5378 ** ^Extension loading is off by default.
5379 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5380 ** to turn extension loading on and call it with onoff==0 to turn
5381 ** it back off again.
5382 */
5383 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5384 
5385 /*
5386 ** CAPI3REF: Automatically Load Statically Linked Extensions
5387 **
5388 ** ^This interface causes the xEntryPoint() function to be invoked for
5389 ** each new [database connection] that is created.  The idea here is that
5390 ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
5391 ** that is to be automatically loaded into all new database connections.
5392 **
5393 ** ^(Even though the function prototype shows that xEntryPoint() takes
5394 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5395 ** arguments and expects and integer result as if the signature of the
5396 ** entry point where as follows:
5397 **
5398 ** <blockquote><pre>
5399 ** &nbsp;  int xEntryPoint(
5400 ** &nbsp;    sqlite3 *db,
5401 ** &nbsp;    const char **pzErrMsg,
5402 ** &nbsp;    const struct sqlite3_api_routines *pThunk
5403 ** &nbsp;  );
5404 ** </pre></blockquote>)^
5405 **
5406 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5407 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5408 ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
5409 ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
5410 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
5411 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5412 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5413 **
5414 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5415 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5416 ** will be called more than once for each database connection that is opened.
5417 **
5418 ** See also: [sqlite3_reset_auto_extension()]
5419 ** and [sqlite3_cancel_auto_extension()]
5420 */
5421 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
5422 
5423 /*
5424 ** CAPI3REF: Cancel Automatic Extension Loading
5425 **
5426 ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
5427 ** initialization routine X that was registered using a prior call to
5428 ** [sqlite3_auto_extension(X)].  ^The [sqlite3_cancel_auto_extension(X)]
5429 ** routine returns 1 if initialization routine X was successfully
5430 ** unregistered and it returns 0 if X was not on the list of initialization
5431 ** routines.
5432 */
5433 SQLITE_API int sqlite3_cancel_auto_extension(void (*xEntryPoint)(void));
5434 
5435 /*
5436 ** CAPI3REF: Reset Automatic Extension Loading
5437 **
5438 ** ^This interface disables all automatic extensions previously
5439 ** registered using [sqlite3_auto_extension()].
5440 */
5441 SQLITE_API void sqlite3_reset_auto_extension(void);
5442 
5443 /*
5444 ** The interface to the virtual-table mechanism is currently considered
5445 ** to be experimental.  The interface might change in incompatible ways.
5446 ** If this is a problem for you, do not use the interface at this time.
5447 **
5448 ** When the virtual-table mechanism stabilizes, we will declare the
5449 ** interface fixed, support it indefinitely, and remove this comment.
5450 */
5451 
5452 /*
5453 ** Structures used by the virtual table interface
5454 */
5455 typedef struct sqlite3_vtab sqlite3_vtab;
5456 typedef struct sqlite3_index_info sqlite3_index_info;
5457 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5458 typedef struct sqlite3_module sqlite3_module;
5459 
5460 /*
5461 ** CAPI3REF: Virtual Table Object
5462 ** KEYWORDS: sqlite3_module {virtual table module}
5463 **
5464 ** This structure, sometimes called a "virtual table module",
5465 ** defines the implementation of a [virtual tables].
5466 ** This structure consists mostly of methods for the module.
5467 **
5468 ** ^A virtual table module is created by filling in a persistent
5469 ** instance of this structure and passing a pointer to that instance
5470 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5471 ** ^The registration remains valid until it is replaced by a different
5472 ** module or until the [database connection] closes.  The content
5473 ** of this structure must not change while it is registered with
5474 ** any database connection.
5475 */
5476 struct sqlite3_module {
5477   int iVersion;
5478   int (*xCreate)(sqlite3*, void *pAux,
5479                int argc, const char *const*argv,
5480                sqlite3_vtab **ppVTab, char**);
5481   int (*xConnect)(sqlite3*, void *pAux,
5482                int argc, const char *const*argv,
5483                sqlite3_vtab **ppVTab, char**);
5484   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5485   int (*xDisconnect)(sqlite3_vtab *pVTab);
5486   int (*xDestroy)(sqlite3_vtab *pVTab);
5487   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5488   int (*xClose)(sqlite3_vtab_cursor*);
5489   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5490                 int argc, sqlite3_value **argv);
5491   int (*xNext)(sqlite3_vtab_cursor*);
5492   int (*xEof)(sqlite3_vtab_cursor*);
5493   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5494   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5495   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5496   int (*xBegin)(sqlite3_vtab *pVTab);
5497   int (*xSync)(sqlite3_vtab *pVTab);
5498   int (*xCommit)(sqlite3_vtab *pVTab);
5499   int (*xRollback)(sqlite3_vtab *pVTab);
5500   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5501                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5502                        void **ppArg);
5503   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5504   /* The methods above are in version 1 of the sqlite_module object. Those
5505   ** below are for version 2 and greater. */
5506   int (*xSavepoint)(sqlite3_vtab *pVTab, int);
5507   int (*xRelease)(sqlite3_vtab *pVTab, int);
5508   int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
5509 };
5510 
5511 /*
5512 ** CAPI3REF: Virtual Table Indexing Information
5513 ** KEYWORDS: sqlite3_index_info
5514 **
5515 ** The sqlite3_index_info structure and its substructures is used as part
5516 ** of the [virtual table] interface to
5517 ** pass information into and receive the reply from the [xBestIndex]
5518 ** method of a [virtual table module].  The fields under **Inputs** are the
5519 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5520 ** results into the **Outputs** fields.
5521 **
5522 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5523 **
5524 ** <blockquote>column OP expr</blockquote>
5525 **
5526 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5527 ** stored in aConstraint[].op using one of the
5528 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5529 ** ^(The index of the column is stored in
5530 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5531 ** expr on the right-hand side can be evaluated (and thus the constraint
5532 ** is usable) and false if it cannot.)^
5533 **
5534 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5535 ** and makes other simplifications to the WHERE clause in an attempt to
5536 ** get as many WHERE clause terms into the form shown above as possible.
5537 ** ^The aConstraint[] array only reports WHERE clause terms that are
5538 ** relevant to the particular virtual table being queried.
5539 **
5540 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5541 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5542 **
5543 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5544 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5545 ** the right-hand side of the corresponding aConstraint[] is evaluated
5546 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5547 ** is true, then the constraint is assumed to be fully handled by the
5548 ** virtual table and is not checked again by SQLite.)^
5549 **
5550 ** ^The idxNum and idxPtr values are recorded and passed into the
5551 ** [xFilter] method.
5552 ** ^[sqlite3_free()] is used to free idxPtr if and only if
5553 ** needToFreeIdxPtr is true.
5554 **
5555 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5556 ** the correct order to satisfy the ORDER BY clause so that no separate
5557 ** sorting step is required.
5558 **
5559 ** ^The estimatedCost value is an estimate of the cost of a particular
5560 ** strategy. A cost of N indicates that the cost of the strategy is similar
5561 ** to a linear scan of an SQLite table with N rows. A cost of log(N)
5562 ** indicates that the expense of the operation is similar to that of a
5563 ** binary search on a unique indexed field of an SQLite table with N rows.
5564 **
5565 ** ^The estimatedRows value is an estimate of the number of rows that
5566 ** will be returned by the strategy.
5567 **
5568 ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
5569 ** structure for SQLite version 3.8.2. If a virtual table extension is
5570 ** used with an SQLite version earlier than 3.8.2, the results of attempting
5571 ** to read or write the estimatedRows field are undefined (but are likely
5572 ** to included crashing the application). The estimatedRows field should
5573 ** therefore only be used if [sqlite3_libversion_number()] returns a
5574 ** value greater than or equal to 3008002.
5575 */
5576 struct sqlite3_index_info {
5577   /* Inputs */
5578   int nConstraint;           /* Number of entries in aConstraint */
5579   struct sqlite3_index_constraint {
5580      int iColumn;              /* Column on left-hand side of constraint */
5581      unsigned char op;         /* Constraint operator */
5582      unsigned char usable;     /* True if this constraint is usable */
5583      int iTermOffset;          /* Used internally - xBestIndex should ignore */
5584   } *aConstraint;            /* Table of WHERE clause constraints */
5585   int nOrderBy;              /* Number of terms in the ORDER BY clause */
5586   struct sqlite3_index_orderby {
5587      int iColumn;              /* Column number */
5588      unsigned char desc;       /* True for DESC.  False for ASC. */
5589   } *aOrderBy;               /* The ORDER BY clause */
5590   /* Outputs */
5591   struct sqlite3_index_constraint_usage {
5592     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5593     unsigned char omit;      /* Do not code a test for this constraint */
5594   } *aConstraintUsage;
5595   int idxNum;                /* Number used to identify the index */
5596   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5597   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5598   int orderByConsumed;       /* True if output is already ordered */
5599   double estimatedCost;           /* Estimated cost of using this index */
5600   /* Fields below are only available in SQLite 3.8.2 and later */
5601   sqlite3_int64 estimatedRows;    /* Estimated number of rows returned */
5602 };
5603 
5604 /*
5605 ** CAPI3REF: Virtual Table Constraint Operator Codes
5606 **
5607 ** These macros defined the allowed values for the
5608 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
5609 ** an operator that is part of a constraint term in the wHERE clause of
5610 ** a query that uses a [virtual table].
5611 */
5612 #define SQLITE_INDEX_CONSTRAINT_EQ    2
5613 #define SQLITE_INDEX_CONSTRAINT_GT    4
5614 #define SQLITE_INDEX_CONSTRAINT_LE    8
5615 #define SQLITE_INDEX_CONSTRAINT_LT    16
5616 #define SQLITE_INDEX_CONSTRAINT_GE    32
5617 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5618 
5619 /*
5620 ** CAPI3REF: Register A Virtual Table Implementation
5621 **
5622 ** ^These routines are used to register a new [virtual table module] name.
5623 ** ^Module names must be registered before
5624 ** creating a new [virtual table] using the module and before using a
5625 ** preexisting [virtual table] for the module.
5626 **
5627 ** ^The module name is registered on the [database connection] specified
5628 ** by the first parameter.  ^The name of the module is given by the
5629 ** second parameter.  ^The third parameter is a pointer to
5630 ** the implementation of the [virtual table module].   ^The fourth
5631 ** parameter is an arbitrary client data pointer that is passed through
5632 ** into the [xCreate] and [xConnect] methods of the virtual table module
5633 ** when a new virtual table is be being created or reinitialized.
5634 **
5635 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5636 ** is a pointer to a destructor for the pClientData.  ^SQLite will
5637 ** invoke the destructor function (if it is not NULL) when SQLite
5638 ** no longer needs the pClientData pointer.  ^The destructor will also
5639 ** be invoked if the call to sqlite3_create_module_v2() fails.
5640 ** ^The sqlite3_create_module()
5641 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
5642 ** destructor.
5643 */
5644 SQLITE_API int sqlite3_create_module(
5645   sqlite3 *db,               /* SQLite connection to register module with */
5646   const char *zName,         /* Name of the module */
5647   const sqlite3_module *p,   /* Methods for the module */
5648   void *pClientData          /* Client data for xCreate/xConnect */
5649 );
5650 SQLITE_API int sqlite3_create_module_v2(
5651   sqlite3 *db,               /* SQLite connection to register module with */
5652   const char *zName,         /* Name of the module */
5653   const sqlite3_module *p,   /* Methods for the module */
5654   void *pClientData,         /* Client data for xCreate/xConnect */
5655   void(*xDestroy)(void*)     /* Module destructor function */
5656 );
5657 
5658 /*
5659 ** CAPI3REF: Virtual Table Instance Object
5660 ** KEYWORDS: sqlite3_vtab
5661 **
5662 ** Every [virtual table module] implementation uses a subclass
5663 ** of this object to describe a particular instance
5664 ** of the [virtual table].  Each subclass will
5665 ** be tailored to the specific needs of the module implementation.
5666 ** The purpose of this superclass is to define certain fields that are
5667 ** common to all module implementations.
5668 **
5669 ** ^Virtual tables methods can set an error message by assigning a
5670 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5671 ** take care that any prior string is freed by a call to [sqlite3_free()]
5672 ** prior to assigning a new string to zErrMsg.  ^After the error message
5673 ** is delivered up to the client application, the string will be automatically
5674 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5675 */
5676 struct sqlite3_vtab {
5677   const sqlite3_module *pModule;  /* The module for this virtual table */
5678   int nRef;                       /* NO LONGER USED */
5679   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5680   /* Virtual table implementations will typically add additional fields */
5681 };
5682 
5683 /*
5684 ** CAPI3REF: Virtual Table Cursor Object
5685 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5686 **
5687 ** Every [virtual table module] implementation uses a subclass of the
5688 ** following structure to describe cursors that point into the
5689 ** [virtual table] and are used
5690 ** to loop through the virtual table.  Cursors are created using the
5691 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5692 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5693 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5694 ** of the module.  Each module implementation will define
5695 ** the content of a cursor structure to suit its own needs.
5696 **
5697 ** This superclass exists in order to define fields of the cursor that
5698 ** are common to all implementations.
5699 */
5700 struct sqlite3_vtab_cursor {
5701   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5702   /* Virtual table implementations will typically add additional fields */
5703 };
5704 
5705 /*
5706 ** CAPI3REF: Declare The Schema Of A Virtual Table
5707 **
5708 ** ^The [xCreate] and [xConnect] methods of a
5709 ** [virtual table module] call this interface
5710 ** to declare the format (the names and datatypes of the columns) of
5711 ** the virtual tables they implement.
5712 */
5713 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5714 
5715 /*
5716 ** CAPI3REF: Overload A Function For A Virtual Table
5717 **
5718 ** ^(Virtual tables can provide alternative implementations of functions
5719 ** using the [xFindFunction] method of the [virtual table module].
5720 ** But global versions of those functions
5721 ** must exist in order to be overloaded.)^
5722 **
5723 ** ^(This API makes sure a global version of a function with a particular
5724 ** name and number of parameters exists.  If no such function exists
5725 ** before this API is called, a new function is created.)^  ^The implementation
5726 ** of the new function always causes an exception to be thrown.  So
5727 ** the new function is not good for anything by itself.  Its only
5728 ** purpose is to be a placeholder function that can be overloaded
5729 ** by a [virtual table].
5730 */
5731 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5732 
5733 /*
5734 ** The interface to the virtual-table mechanism defined above (back up
5735 ** to a comment remarkably similar to this one) is currently considered
5736 ** to be experimental.  The interface might change in incompatible ways.
5737 ** If this is a problem for you, do not use the interface at this time.
5738 **
5739 ** When the virtual-table mechanism stabilizes, we will declare the
5740 ** interface fixed, support it indefinitely, and remove this comment.
5741 */
5742 
5743 /*
5744 ** CAPI3REF: A Handle To An Open BLOB
5745 ** KEYWORDS: {BLOB handle} {BLOB handles}
5746 **
5747 ** An instance of this object represents an open BLOB on which
5748 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5749 ** ^Objects of this type are created by [sqlite3_blob_open()]
5750 ** and destroyed by [sqlite3_blob_close()].
5751 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5752 ** can be used to read or write small subsections of the BLOB.
5753 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5754 */
5755 typedef struct sqlite3_blob sqlite3_blob;
5756 
5757 /*
5758 ** CAPI3REF: Open A BLOB For Incremental I/O
5759 **
5760 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5761 ** in row iRow, column zColumn, table zTable in database zDb;
5762 ** in other words, the same BLOB that would be selected by:
5763 **
5764 ** <pre>
5765 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5766 ** </pre>)^
5767 **
5768 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
5769 ** and write access. ^If it is zero, the BLOB is opened for read access.
5770 ** ^It is not possible to open a column that is part of an index or primary
5771 ** key for writing. ^If [foreign key constraints] are enabled, it is
5772 ** not possible to open a column that is part of a [child key] for writing.
5773 **
5774 ** ^Note that the database name is not the filename that contains
5775 ** the database but rather the symbolic name of the database that
5776 ** appears after the AS keyword when the database is connected using [ATTACH].
5777 ** ^For the main database file, the database name is "main".
5778 ** ^For TEMP tables, the database name is "temp".
5779 **
5780 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5781 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5782 ** to be a null pointer.)^
5783 ** ^This function sets the [database connection] error code and message
5784 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5785 ** functions. ^Note that the *ppBlob variable is always initialized in a
5786 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5787 ** regardless of the success or failure of this routine.
5788 **
5789 ** ^(If the row that a BLOB handle points to is modified by an
5790 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5791 ** then the BLOB handle is marked as "expired".
5792 ** This is true if any column of the row is changed, even a column
5793 ** other than the one the BLOB handle is open on.)^
5794 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5795 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
5796 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
5797 ** rolled back by the expiration of the BLOB.  Such changes will eventually
5798 ** commit if the transaction continues to completion.)^
5799 **
5800 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5801 ** the opened blob.  ^The size of a blob may not be changed by this
5802 ** interface.  Use the [UPDATE] SQL command to change the size of a
5803 ** blob.
5804 **
5805 ** ^The [sqlite3_blob_open()] interface will fail for a [WITHOUT ROWID]
5806 ** table.  Incremental BLOB I/O is not possible on [WITHOUT ROWID] tables.
5807 **
5808 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5809 ** and the built-in [zeroblob] SQL function can be used, if desired,
5810 ** to create an empty, zero-filled blob in which to read or write using
5811 ** this interface.
5812 **
5813 ** To avoid a resource leak, every open [BLOB handle] should eventually
5814 ** be released by a call to [sqlite3_blob_close()].
5815 */
5816 SQLITE_API int sqlite3_blob_open(
5817   sqlite3*,
5818   const char *zDb,
5819   const char *zTable,
5820   const char *zColumn,
5821   sqlite3_int64 iRow,
5822   int flags,
5823   sqlite3_blob **ppBlob
5824 );
5825 
5826 /*
5827 ** CAPI3REF: Move a BLOB Handle to a New Row
5828 **
5829 ** ^This function is used to move an existing blob handle so that it points
5830 ** to a different row of the same database table. ^The new row is identified
5831 ** by the rowid value passed as the second argument. Only the row can be
5832 ** changed. ^The database, table and column on which the blob handle is open
5833 ** remain the same. Moving an existing blob handle to a new row can be
5834 ** faster than closing the existing handle and opening a new one.
5835 **
5836 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
5837 ** it must exist and there must be either a blob or text value stored in
5838 ** the nominated column.)^ ^If the new row is not present in the table, or if
5839 ** it does not contain a blob or text value, or if another error occurs, an
5840 ** SQLite error code is returned and the blob handle is considered aborted.
5841 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
5842 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
5843 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
5844 ** always returns zero.
5845 **
5846 ** ^This function sets the database handle error code and message.
5847 */
5848 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
5849 
5850 /*
5851 ** CAPI3REF: Close A BLOB Handle
5852 **
5853 ** ^Closes an open [BLOB handle].
5854 **
5855 ** ^Closing a BLOB shall cause the current transaction to commit
5856 ** if there are no other BLOBs, no pending prepared statements, and the
5857 ** database connection is in [autocommit mode].
5858 ** ^If any writes were made to the BLOB, they might be held in cache
5859 ** until the close operation if they will fit.
5860 **
5861 ** ^(Closing the BLOB often forces the changes
5862 ** out to disk and so if any I/O errors occur, they will likely occur
5863 ** at the time when the BLOB is closed.  Any errors that occur during
5864 ** closing are reported as a non-zero return value.)^
5865 **
5866 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
5867 ** an error code, the BLOB is still closed.)^
5868 **
5869 ** ^Calling this routine with a null pointer (such as would be returned
5870 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5871 */
5872 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5873 
5874 /*
5875 ** CAPI3REF: Return The Size Of An Open BLOB
5876 **
5877 ** ^Returns the size in bytes of the BLOB accessible via the
5878 ** successfully opened [BLOB handle] in its only argument.  ^The
5879 ** incremental blob I/O routines can only read or overwriting existing
5880 ** blob content; they cannot change the size of a blob.
5881 **
5882 ** This routine only works on a [BLOB handle] which has been created
5883 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5884 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5885 ** to this routine results in undefined and probably undesirable behavior.
5886 */
5887 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5888 
5889 /*
5890 ** CAPI3REF: Read Data From A BLOB Incrementally
5891 **
5892 ** ^(This function is used to read data from an open [BLOB handle] into a
5893 ** caller-supplied buffer. N bytes of data are copied into buffer Z
5894 ** from the open BLOB, starting at offset iOffset.)^
5895 **
5896 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5897 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
5898 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
5899 ** ^The size of the blob (and hence the maximum value of N+iOffset)
5900 ** can be determined using the [sqlite3_blob_bytes()] interface.
5901 **
5902 ** ^An attempt to read from an expired [BLOB handle] fails with an
5903 ** error code of [SQLITE_ABORT].
5904 **
5905 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5906 ** Otherwise, an [error code] or an [extended error code] is returned.)^
5907 **
5908 ** This routine only works on a [BLOB handle] which has been created
5909 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5910 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5911 ** to this routine results in undefined and probably undesirable behavior.
5912 **
5913 ** See also: [sqlite3_blob_write()].
5914 */
5915 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5916 
5917 /*
5918 ** CAPI3REF: Write Data Into A BLOB Incrementally
5919 **
5920 ** ^This function is used to write data into an open [BLOB handle] from a
5921 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5922 ** into the open BLOB, starting at offset iOffset.
5923 **
5924 ** ^If the [BLOB handle] passed as the first argument was not opened for
5925 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5926 ** this function returns [SQLITE_READONLY].
5927 **
5928 ** ^This function may only modify the contents of the BLOB; it is
5929 ** not possible to increase the size of a BLOB using this API.
5930 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5931 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
5932 ** less than zero [SQLITE_ERROR] is returned and no data is written.
5933 ** The size of the BLOB (and hence the maximum value of N+iOffset)
5934 ** can be determined using the [sqlite3_blob_bytes()] interface.
5935 **
5936 ** ^An attempt to write to an expired [BLOB handle] fails with an
5937 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
5938 ** before the [BLOB handle] expired are not rolled back by the
5939 ** expiration of the handle, though of course those changes might
5940 ** have been overwritten by the statement that expired the BLOB handle
5941 ** or by other independent statements.
5942 **
5943 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5944 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
5945 **
5946 ** This routine only works on a [BLOB handle] which has been created
5947 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5948 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5949 ** to this routine results in undefined and probably undesirable behavior.
5950 **
5951 ** See also: [sqlite3_blob_read()].
5952 */
5953 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5954 
5955 /*
5956 ** CAPI3REF: Virtual File System Objects
5957 **
5958 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5959 ** that SQLite uses to interact
5960 ** with the underlying operating system.  Most SQLite builds come with a
5961 ** single default VFS that is appropriate for the host computer.
5962 ** New VFSes can be registered and existing VFSes can be unregistered.
5963 ** The following interfaces are provided.
5964 **
5965 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5966 ** ^Names are case sensitive.
5967 ** ^Names are zero-terminated UTF-8 strings.
5968 ** ^If there is no match, a NULL pointer is returned.
5969 ** ^If zVfsName is NULL then the default VFS is returned.
5970 **
5971 ** ^New VFSes are registered with sqlite3_vfs_register().
5972 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5973 ** ^The same VFS can be registered multiple times without injury.
5974 ** ^To make an existing VFS into the default VFS, register it again
5975 ** with the makeDflt flag set.  If two different VFSes with the
5976 ** same name are registered, the behavior is undefined.  If a
5977 ** VFS is registered with a name that is NULL or an empty string,
5978 ** then the behavior is undefined.
5979 **
5980 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5981 ** ^(If the default VFS is unregistered, another VFS is chosen as
5982 ** the default.  The choice for the new VFS is arbitrary.)^
5983 */
5984 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5985 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5986 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5987 
5988 /*
5989 ** CAPI3REF: Mutexes
5990 **
5991 ** The SQLite core uses these routines for thread
5992 ** synchronization. Though they are intended for internal
5993 ** use by SQLite, code that links against SQLite is
5994 ** permitted to use any of these routines.
5995 **
5996 ** The SQLite source code contains multiple implementations
5997 ** of these mutex routines.  An appropriate implementation
5998 ** is selected automatically at compile-time.  ^(The following
5999 ** implementations are available in the SQLite core:
6000 **
6001 ** <ul>
6002 ** <li>   SQLITE_MUTEX_PTHREADS
6003 ** <li>   SQLITE_MUTEX_W32
6004 ** <li>   SQLITE_MUTEX_NOOP
6005 ** </ul>)^
6006 **
6007 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
6008 ** that does no real locking and is appropriate for use in
6009 ** a single-threaded application.  ^The SQLITE_MUTEX_PTHREADS and
6010 ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
6011 ** and Windows.
6012 **
6013 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6014 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6015 ** implementation is included with the library. In this case the
6016 ** application must supply a custom mutex implementation using the
6017 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6018 ** before calling sqlite3_initialize() or any other public sqlite3_
6019 ** function that calls sqlite3_initialize().)^
6020 **
6021 ** ^The sqlite3_mutex_alloc() routine allocates a new
6022 ** mutex and returns a pointer to it. ^If it returns NULL
6023 ** that means that a mutex could not be allocated.  ^SQLite
6024 ** will unwind its stack and return an error.  ^(The argument
6025 ** to sqlite3_mutex_alloc() is one of these integer constants:
6026 **
6027 ** <ul>
6028 ** <li>  SQLITE_MUTEX_FAST
6029 ** <li>  SQLITE_MUTEX_RECURSIVE
6030 ** <li>  SQLITE_MUTEX_STATIC_MASTER
6031 ** <li>  SQLITE_MUTEX_STATIC_MEM
6032 ** <li>  SQLITE_MUTEX_STATIC_OPEN
6033 ** <li>  SQLITE_MUTEX_STATIC_PRNG
6034 ** <li>  SQLITE_MUTEX_STATIC_LRU
6035 ** <li>  SQLITE_MUTEX_STATIC_PMEM
6036 ** <li>  SQLITE_MUTEX_STATIC_APP1
6037 ** <li>  SQLITE_MUTEX_STATIC_APP2
6038 ** </ul>)^
6039 **
6040 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
6041 ** cause sqlite3_mutex_alloc() to create
6042 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6043 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
6044 ** The mutex implementation does not need to make a distinction
6045 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6046 ** not want to.  ^SQLite will only request a recursive mutex in
6047 ** cases where it really needs one.  ^If a faster non-recursive mutex
6048 ** implementation is available on the host platform, the mutex subsystem
6049 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
6050 **
6051 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
6052 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
6053 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
6054 ** used by the current version of SQLite.  Future versions of SQLite
6055 ** may add additional static mutexes.  Static mutexes are for internal
6056 ** use by SQLite only.  Applications that use SQLite mutexes should
6057 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6058 ** SQLITE_MUTEX_RECURSIVE.
6059 **
6060 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6061 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6062 ** returns a different mutex on every call.  ^But for the static
6063 ** mutex types, the same mutex is returned on every call that has
6064 ** the same type number.
6065 **
6066 ** ^The sqlite3_mutex_free() routine deallocates a previously
6067 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
6068 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
6069 ** use when they are deallocated.  Attempting to deallocate a static
6070 ** mutex results in undefined behavior.  ^SQLite never deallocates
6071 ** a static mutex.
6072 **
6073 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6074 ** to enter a mutex.  ^If another thread is already within the mutex,
6075 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6076 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
6077 ** upon successful entry.  ^(Mutexes created using
6078 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6079 ** In such cases the,
6080 ** mutex must be exited an equal number of times before another thread
6081 ** can enter.)^  ^(If the same thread tries to enter any other
6082 ** kind of mutex more than once, the behavior is undefined.
6083 ** SQLite will never exhibit
6084 ** such behavior in its own use of mutexes.)^
6085 **
6086 ** ^(Some systems (for example, Windows 95) do not support the operation
6087 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
6088 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
6089 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
6090 **
6091 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
6092 ** previously entered by the same thread.   ^(The behavior
6093 ** is undefined if the mutex is not currently entered by the
6094 ** calling thread or is not currently allocated.  SQLite will
6095 ** never do either.)^
6096 **
6097 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6098 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6099 ** behave as no-ops.
6100 **
6101 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6102 */
6103 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
6104 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
6105 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
6106 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
6107 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
6108 
6109 /*
6110 ** CAPI3REF: Mutex Methods Object
6111 **
6112 ** An instance of this structure defines the low-level routines
6113 ** used to allocate and use mutexes.
6114 **
6115 ** Usually, the default mutex implementations provided by SQLite are
6116 ** sufficient, however the user has the option of substituting a custom
6117 ** implementation for specialized deployments or systems for which SQLite
6118 ** does not provide a suitable implementation. In this case, the user
6119 ** creates and populates an instance of this structure to pass
6120 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6121 ** Additionally, an instance of this structure can be used as an
6122 ** output variable when querying the system for the current mutex
6123 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6124 **
6125 ** ^The xMutexInit method defined by this structure is invoked as
6126 ** part of system initialization by the sqlite3_initialize() function.
6127 ** ^The xMutexInit routine is called by SQLite exactly once for each
6128 ** effective call to [sqlite3_initialize()].
6129 **
6130 ** ^The xMutexEnd method defined by this structure is invoked as
6131 ** part of system shutdown by the sqlite3_shutdown() function. The
6132 ** implementation of this method is expected to release all outstanding
6133 ** resources obtained by the mutex methods implementation, especially
6134 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
6135 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
6136 **
6137 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6138 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6139 ** xMutexNotheld) implement the following interfaces (respectively):
6140 **
6141 ** <ul>
6142 **   <li>  [sqlite3_mutex_alloc()] </li>
6143 **   <li>  [sqlite3_mutex_free()] </li>
6144 **   <li>  [sqlite3_mutex_enter()] </li>
6145 **   <li>  [sqlite3_mutex_try()] </li>
6146 **   <li>  [sqlite3_mutex_leave()] </li>
6147 **   <li>  [sqlite3_mutex_held()] </li>
6148 **   <li>  [sqlite3_mutex_notheld()] </li>
6149 ** </ul>)^
6150 **
6151 ** The only difference is that the public sqlite3_XXX functions enumerated
6152 ** above silently ignore any invocations that pass a NULL pointer instead
6153 ** of a valid mutex handle. The implementations of the methods defined
6154 ** by this structure are not required to handle this case, the results
6155 ** of passing a NULL pointer instead of a valid mutex handle are undefined
6156 ** (i.e. it is acceptable to provide an implementation that segfaults if
6157 ** it is passed a NULL pointer).
6158 **
6159 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
6160 ** invoke xMutexInit() multiple times within the same process and without
6161 ** intervening calls to xMutexEnd().  Second and subsequent calls to
6162 ** xMutexInit() must be no-ops.
6163 **
6164 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6165 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
6166 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
6167 ** memory allocation for a fast or recursive mutex.
6168 **
6169 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6170 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6171 ** If xMutexInit fails in any way, it is expected to clean up after itself
6172 ** prior to returning.
6173 */
6174 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6175 struct sqlite3_mutex_methods {
6176   int (*xMutexInit)(void);
6177   int (*xMutexEnd)(void);
6178   sqlite3_mutex *(*xMutexAlloc)(int);
6179   void (*xMutexFree)(sqlite3_mutex *);
6180   void (*xMutexEnter)(sqlite3_mutex *);
6181   int (*xMutexTry)(sqlite3_mutex *);
6182   void (*xMutexLeave)(sqlite3_mutex *);
6183   int (*xMutexHeld)(sqlite3_mutex *);
6184   int (*xMutexNotheld)(sqlite3_mutex *);
6185 };
6186 
6187 /*
6188 ** CAPI3REF: Mutex Verification Routines
6189 **
6190 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6191 ** are intended for use inside assert() statements.  ^The SQLite core
6192 ** never uses these routines except inside an assert() and applications
6193 ** are advised to follow the lead of the core.  ^The SQLite core only
6194 ** provides implementations for these routines when it is compiled
6195 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
6196 ** are only required to provide these routines if SQLITE_DEBUG is
6197 ** defined and if NDEBUG is not defined.
6198 **
6199 ** ^These routines should return true if the mutex in their argument
6200 ** is held or not held, respectively, by the calling thread.
6201 **
6202 ** ^The implementation is not required to provide versions of these
6203 ** routines that actually work. If the implementation does not provide working
6204 ** versions of these routines, it should at least provide stubs that always
6205 ** return true so that one does not get spurious assertion failures.
6206 **
6207 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
6208 ** the routine should return 1.   This seems counter-intuitive since
6209 ** clearly the mutex cannot be held if it does not exist.  But
6210 ** the reason the mutex does not exist is because the build is not
6211 ** using mutexes.  And we do not want the assert() containing the
6212 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6213 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
6214 ** interface should also return 1 when given a NULL pointer.
6215 */
6216 #ifndef NDEBUG
6217 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6218 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6219 #endif
6220 
6221 /*
6222 ** CAPI3REF: Mutex Types
6223 **
6224 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6225 ** which is one of these integer constants.
6226 **
6227 ** The set of static mutexes may change from one SQLite release to the
6228 ** next.  Applications that override the built-in mutex logic must be
6229 ** prepared to accommodate additional static mutexes.
6230 */
6231 #define SQLITE_MUTEX_FAST             0
6232 #define SQLITE_MUTEX_RECURSIVE        1
6233 #define SQLITE_MUTEX_STATIC_MASTER    2
6234 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
6235 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
6236 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
6237 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
6238 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
6239 #define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
6240 #define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
6241 #define SQLITE_MUTEX_STATIC_APP1      8  /* For use by application */
6242 #define SQLITE_MUTEX_STATIC_APP2      9  /* For use by application */
6243 #define SQLITE_MUTEX_STATIC_APP3     10  /* For use by application */
6244 
6245 /*
6246 ** CAPI3REF: Retrieve the mutex for a database connection
6247 **
6248 ** ^This interface returns a pointer the [sqlite3_mutex] object that
6249 ** serializes access to the [database connection] given in the argument
6250 ** when the [threading mode] is Serialized.
6251 ** ^If the [threading mode] is Single-thread or Multi-thread then this
6252 ** routine returns a NULL pointer.
6253 */
6254 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
6255 
6256 /*
6257 ** CAPI3REF: Low-Level Control Of Database Files
6258 **
6259 ** ^The [sqlite3_file_control()] interface makes a direct call to the
6260 ** xFileControl method for the [sqlite3_io_methods] object associated
6261 ** with a particular database identified by the second argument. ^The
6262 ** name of the database is "main" for the main database or "temp" for the
6263 ** TEMP database, or the name that appears after the AS keyword for
6264 ** databases that are added using the [ATTACH] SQL command.
6265 ** ^A NULL pointer can be used in place of "main" to refer to the
6266 ** main database file.
6267 ** ^The third and fourth parameters to this routine
6268 ** are passed directly through to the second and third parameters of
6269 ** the xFileControl method.  ^The return value of the xFileControl
6270 ** method becomes the return value of this routine.
6271 **
6272 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6273 ** a pointer to the underlying [sqlite3_file] object to be written into
6274 ** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
6275 ** case is a short-circuit path which does not actually invoke the
6276 ** underlying sqlite3_io_methods.xFileControl method.
6277 **
6278 ** ^If the second parameter (zDbName) does not match the name of any
6279 ** open database file, then SQLITE_ERROR is returned.  ^This error
6280 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6281 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
6282 ** also return SQLITE_ERROR.  There is no way to distinguish between
6283 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6284 ** xFileControl method.
6285 **
6286 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6287 */
6288 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6289 
6290 /*
6291 ** CAPI3REF: Testing Interface
6292 **
6293 ** ^The sqlite3_test_control() interface is used to read out internal
6294 ** state of SQLite and to inject faults into SQLite for testing
6295 ** purposes.  ^The first parameter is an operation code that determines
6296 ** the number, meaning, and operation of all subsequent parameters.
6297 **
6298 ** This interface is not for use by applications.  It exists solely
6299 ** for verifying the correct operation of the SQLite library.  Depending
6300 ** on how the SQLite library is compiled, this interface might not exist.
6301 **
6302 ** The details of the operation codes, their meanings, the parameters
6303 ** they take, and what they do are all subject to change without notice.
6304 ** Unlike most of the SQLite API, this function is not guaranteed to
6305 ** operate consistently from one release to the next.
6306 */
6307 SQLITE_API int sqlite3_test_control(int op, ...);
6308 
6309 /*
6310 ** CAPI3REF: Testing Interface Operation Codes
6311 **
6312 ** These constants are the valid operation code parameters used
6313 ** as the first argument to [sqlite3_test_control()].
6314 **
6315 ** These parameters and their meanings are subject to change
6316 ** without notice.  These values are for testing purposes only.
6317 ** Applications should not use any of these parameters or the
6318 ** [sqlite3_test_control()] interface.
6319 */
6320 #define SQLITE_TESTCTRL_FIRST                    5
6321 #define SQLITE_TESTCTRL_PRNG_SAVE                5
6322 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
6323 #define SQLITE_TESTCTRL_PRNG_RESET               7
6324 #define SQLITE_TESTCTRL_BITVEC_TEST              8
6325 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
6326 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6327 #define SQLITE_TESTCTRL_PENDING_BYTE            11
6328 #define SQLITE_TESTCTRL_ASSERT                  12
6329 #define SQLITE_TESTCTRL_ALWAYS                  13
6330 #define SQLITE_TESTCTRL_RESERVE                 14
6331 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
6332 #define SQLITE_TESTCTRL_ISKEYWORD               16
6333 #define SQLITE_TESTCTRL_SCRATCHMALLOC           17
6334 #define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
6335 #define SQLITE_TESTCTRL_EXPLAIN_STMT            19  /* NOT USED */
6336 #define SQLITE_TESTCTRL_NEVER_CORRUPT           20
6337 #define SQLITE_TESTCTRL_VDBE_COVERAGE           21
6338 #define SQLITE_TESTCTRL_BYTEORDER               22
6339 #define SQLITE_TESTCTRL_ISINIT                  23
6340 #define SQLITE_TESTCTRL_SORTER_MMAP             24
6341 #define SQLITE_TESTCTRL_LAST                    24
6342 
6343 /*
6344 ** CAPI3REF: SQLite Runtime Status
6345 **
6346 ** ^This interface is used to retrieve runtime status information
6347 ** about the performance of SQLite, and optionally to reset various
6348 ** highwater marks.  ^The first argument is an integer code for
6349 ** the specific parameter to measure.  ^(Recognized integer codes
6350 ** are of the form [status parameters | SQLITE_STATUS_...].)^
6351 ** ^The current value of the parameter is returned into *pCurrent.
6352 ** ^The highest recorded value is returned in *pHighwater.  ^If the
6353 ** resetFlag is true, then the highest record value is reset after
6354 ** *pHighwater is written.  ^(Some parameters do not record the highest
6355 ** value.  For those parameters
6356 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
6357 ** ^(Other parameters record only the highwater mark and not the current
6358 ** value.  For these latter parameters nothing is written into *pCurrent.)^
6359 **
6360 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
6361 ** non-zero [error code] on failure.
6362 **
6363 ** This routine is threadsafe but is not atomic.  This routine can be
6364 ** called while other threads are running the same or different SQLite
6365 ** interfaces.  However the values returned in *pCurrent and
6366 ** *pHighwater reflect the status of SQLite at different points in time
6367 ** and it is possible that another thread might change the parameter
6368 ** in between the times when *pCurrent and *pHighwater are written.
6369 **
6370 ** See also: [sqlite3_db_status()]
6371 */
6372 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6373 
6374 
6375 /*
6376 ** CAPI3REF: Status Parameters
6377 ** KEYWORDS: {status parameters}
6378 **
6379 ** These integer constants designate various run-time status parameters
6380 ** that can be returned by [sqlite3_status()].
6381 **
6382 ** <dl>
6383 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6384 ** <dd>This parameter is the current amount of memory checked out
6385 ** using [sqlite3_malloc()], either directly or indirectly.  The
6386 ** figure includes calls made to [sqlite3_malloc()] by the application
6387 ** and internal memory usage by the SQLite library.  Scratch memory
6388 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6389 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6390 ** this parameter.  The amount returned is the sum of the allocation
6391 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6392 **
6393 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6394 ** <dd>This parameter records the largest memory allocation request
6395 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6396 ** internal equivalents).  Only the value returned in the
6397 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6398 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6399 **
6400 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6401 ** <dd>This parameter records the number of separate memory allocations
6402 ** currently checked out.</dd>)^
6403 **
6404 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6405 ** <dd>This parameter returns the number of pages used out of the
6406 ** [pagecache memory allocator] that was configured using
6407 ** [SQLITE_CONFIG_PAGECACHE].  The
6408 ** value returned is in pages, not in bytes.</dd>)^
6409 **
6410 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
6411 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6412 ** <dd>This parameter returns the number of bytes of page cache
6413 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6414 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
6415 ** returned value includes allocations that overflowed because they
6416 ** where too large (they were larger than the "sz" parameter to
6417 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6418 ** no space was left in the page cache.</dd>)^
6419 **
6420 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6421 ** <dd>This parameter records the largest memory allocation request
6422 ** handed to [pagecache memory allocator].  Only the value returned in the
6423 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6424 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6425 **
6426 ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6427 ** <dd>This parameter returns the number of allocations used out of the
6428 ** [scratch memory allocator] configured using
6429 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6430 ** in bytes.  Since a single thread may only have one scratch allocation
6431 ** outstanding at time, this parameter also reports the number of threads
6432 ** using scratch memory at the same time.</dd>)^
6433 **
6434 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6435 ** <dd>This parameter returns the number of bytes of scratch memory
6436 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6437 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6438 ** returned include overflows because the requested allocation was too
6439 ** larger (that is, because the requested allocation was larger than the
6440 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6441 ** slots were available.
6442 ** </dd>)^
6443 **
6444 ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6445 ** <dd>This parameter records the largest memory allocation request
6446 ** handed to [scratch memory allocator].  Only the value returned in the
6447 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6448 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6449 **
6450 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6451 ** <dd>This parameter records the deepest parser stack.  It is only
6452 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6453 ** </dl>
6454 **
6455 ** New status parameters may be added from time to time.
6456 */
6457 #define SQLITE_STATUS_MEMORY_USED          0
6458 #define SQLITE_STATUS_PAGECACHE_USED       1
6459 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6460 #define SQLITE_STATUS_SCRATCH_USED         3
6461 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6462 #define SQLITE_STATUS_MALLOC_SIZE          5
6463 #define SQLITE_STATUS_PARSER_STACK         6
6464 #define SQLITE_STATUS_PAGECACHE_SIZE       7
6465 #define SQLITE_STATUS_SCRATCH_SIZE         8
6466 #define SQLITE_STATUS_MALLOC_COUNT         9
6467 
6468 /*
6469 ** CAPI3REF: Database Connection Status
6470 **
6471 ** ^This interface is used to retrieve runtime status information
6472 ** about a single [database connection].  ^The first argument is the
6473 ** database connection object to be interrogated.  ^The second argument
6474 ** is an integer constant, taken from the set of
6475 ** [SQLITE_DBSTATUS options], that
6476 ** determines the parameter to interrogate.  The set of
6477 ** [SQLITE_DBSTATUS options] is likely
6478 ** to grow in future releases of SQLite.
6479 **
6480 ** ^The current value of the requested parameter is written into *pCur
6481 ** and the highest instantaneous value is written into *pHiwtr.  ^If
6482 ** the resetFlg is true, then the highest instantaneous value is
6483 ** reset back down to the current value.
6484 **
6485 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6486 ** non-zero [error code] on failure.
6487 **
6488 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6489 */
6490 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6491 
6492 /*
6493 ** CAPI3REF: Status Parameters for database connections
6494 ** KEYWORDS: {SQLITE_DBSTATUS options}
6495 **
6496 ** These constants are the available integer "verbs" that can be passed as
6497 ** the second argument to the [sqlite3_db_status()] interface.
6498 **
6499 ** New verbs may be added in future releases of SQLite. Existing verbs
6500 ** might be discontinued. Applications should check the return code from
6501 ** [sqlite3_db_status()] to make sure that the call worked.
6502 ** The [sqlite3_db_status()] interface will return a non-zero error code
6503 ** if a discontinued or unsupported verb is invoked.
6504 **
6505 ** <dl>
6506 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6507 ** <dd>This parameter returns the number of lookaside memory slots currently
6508 ** checked out.</dd>)^
6509 **
6510 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6511 ** <dd>This parameter returns the number malloc attempts that were
6512 ** satisfied using lookaside memory. Only the high-water value is meaningful;
6513 ** the current value is always zero.)^
6514 **
6515 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6516 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6517 ** <dd>This parameter returns the number malloc attempts that might have
6518 ** been satisfied using lookaside memory but failed due to the amount of
6519 ** memory requested being larger than the lookaside slot size.
6520 ** Only the high-water value is meaningful;
6521 ** the current value is always zero.)^
6522 **
6523 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
6524 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6525 ** <dd>This parameter returns the number malloc attempts that might have
6526 ** been satisfied using lookaside memory but failed due to all lookaside
6527 ** memory already being in use.
6528 ** Only the high-water value is meaningful;
6529 ** the current value is always zero.)^
6530 **
6531 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6532 ** <dd>This parameter returns the approximate number of bytes of heap
6533 ** memory used by all pager caches associated with the database connection.)^
6534 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6535 **
6536 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6537 ** <dd>This parameter returns the approximate number of bytes of heap
6538 ** memory used to store the schema for all databases associated
6539 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
6540 ** ^The full amount of memory used by the schemas is reported, even if the
6541 ** schema memory is shared with other database connections due to
6542 ** [shared cache mode] being enabled.
6543 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6544 **
6545 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6546 ** <dd>This parameter returns the approximate number of bytes of heap
6547 ** and lookaside memory used by all prepared statements associated with
6548 ** the database connection.)^
6549 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6550 ** </dd>
6551 **
6552 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
6553 ** <dd>This parameter returns the number of pager cache hits that have
6554 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
6555 ** is always 0.
6556 ** </dd>
6557 **
6558 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
6559 ** <dd>This parameter returns the number of pager cache misses that have
6560 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
6561 ** is always 0.
6562 ** </dd>
6563 **
6564 ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
6565 ** <dd>This parameter returns the number of dirty cache entries that have
6566 ** been written to disk. Specifically, the number of pages written to the
6567 ** wal file in wal mode databases, or the number of pages written to the
6568 ** database file in rollback mode databases. Any pages written as part of
6569 ** transaction rollback or database recovery operations are not included.
6570 ** If an IO or other error occurs while writing a page to disk, the effect
6571 ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
6572 ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
6573 ** </dd>
6574 **
6575 ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
6576 ** <dd>This parameter returns zero for the current value if and only if
6577 ** all foreign key constraints (deferred or immediate) have been
6578 ** resolved.)^  ^The highwater mark is always 0.
6579 ** </dd>
6580 ** </dl>
6581 */
6582 #define SQLITE_DBSTATUS_LOOKASIDE_USED       0
6583 #define SQLITE_DBSTATUS_CACHE_USED           1
6584 #define SQLITE_DBSTATUS_SCHEMA_USED          2
6585 #define SQLITE_DBSTATUS_STMT_USED            3
6586 #define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
6587 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
6588 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
6589 #define SQLITE_DBSTATUS_CACHE_HIT            7
6590 #define SQLITE_DBSTATUS_CACHE_MISS           8
6591 #define SQLITE_DBSTATUS_CACHE_WRITE          9
6592 #define SQLITE_DBSTATUS_DEFERRED_FKS        10
6593 #define SQLITE_DBSTATUS_MAX                 10   /* Largest defined DBSTATUS */
6594 
6595 
6596 /*
6597 ** CAPI3REF: Prepared Statement Status
6598 **
6599 ** ^(Each prepared statement maintains various
6600 ** [SQLITE_STMTSTATUS counters] that measure the number
6601 ** of times it has performed specific operations.)^  These counters can
6602 ** be used to monitor the performance characteristics of the prepared
6603 ** statements.  For example, if the number of table steps greatly exceeds
6604 ** the number of table searches or result rows, that would tend to indicate
6605 ** that the prepared statement is using a full table scan rather than
6606 ** an index.
6607 **
6608 ** ^(This interface is used to retrieve and reset counter values from
6609 ** a [prepared statement].  The first argument is the prepared statement
6610 ** object to be interrogated.  The second argument
6611 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
6612 ** to be interrogated.)^
6613 ** ^The current value of the requested counter is returned.
6614 ** ^If the resetFlg is true, then the counter is reset to zero after this
6615 ** interface call returns.
6616 **
6617 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
6618 */
6619 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6620 
6621 /*
6622 ** CAPI3REF: Status Parameters for prepared statements
6623 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
6624 **
6625 ** These preprocessor macros define integer codes that name counter
6626 ** values associated with the [sqlite3_stmt_status()] interface.
6627 ** The meanings of the various counters are as follows:
6628 **
6629 ** <dl>
6630 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6631 ** <dd>^This is the number of times that SQLite has stepped forward in
6632 ** a table as part of a full table scan.  Large numbers for this counter
6633 ** may indicate opportunities for performance improvement through
6634 ** careful use of indices.</dd>
6635 **
6636 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
6637 ** <dd>^This is the number of sort operations that have occurred.
6638 ** A non-zero value in this counter may indicate an opportunity to
6639 ** improvement performance through careful use of indices.</dd>
6640 **
6641 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6642 ** <dd>^This is the number of rows inserted into transient indices that
6643 ** were created automatically in order to help joins run faster.
6644 ** A non-zero value in this counter may indicate an opportunity to
6645 ** improvement performance by adding permanent indices that do not
6646 ** need to be reinitialized each time the statement is run.</dd>
6647 **
6648 ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
6649 ** <dd>^This is the number of virtual machine operations executed
6650 ** by the prepared statement if that number is less than or equal
6651 ** to 2147483647.  The number of virtual machine operations can be
6652 ** used as a proxy for the total work done by the prepared statement.
6653 ** If the number of virtual machine operations exceeds 2147483647
6654 ** then the value returned by this statement status code is undefined.
6655 ** </dd>
6656 ** </dl>
6657 */
6658 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
6659 #define SQLITE_STMTSTATUS_SORT              2
6660 #define SQLITE_STMTSTATUS_AUTOINDEX         3
6661 #define SQLITE_STMTSTATUS_VM_STEP           4
6662 
6663 /*
6664 ** CAPI3REF: Custom Page Cache Object
6665 **
6666 ** The sqlite3_pcache type is opaque.  It is implemented by
6667 ** the pluggable module.  The SQLite core has no knowledge of
6668 ** its size or internal structure and never deals with the
6669 ** sqlite3_pcache object except by holding and passing pointers
6670 ** to the object.
6671 **
6672 ** See [sqlite3_pcache_methods2] for additional information.
6673 */
6674 typedef struct sqlite3_pcache sqlite3_pcache;
6675 
6676 /*
6677 ** CAPI3REF: Custom Page Cache Object
6678 **
6679 ** The sqlite3_pcache_page object represents a single page in the
6680 ** page cache.  The page cache will allocate instances of this
6681 ** object.  Various methods of the page cache use pointers to instances
6682 ** of this object as parameters or as their return value.
6683 **
6684 ** See [sqlite3_pcache_methods2] for additional information.
6685 */
6686 typedef struct sqlite3_pcache_page sqlite3_pcache_page;
6687 struct sqlite3_pcache_page {
6688   void *pBuf;        /* The content of the page */
6689   void *pExtra;      /* Extra information associated with the page */
6690 };
6691 
6692 /*
6693 ** CAPI3REF: Application Defined Page Cache.
6694 ** KEYWORDS: {page cache}
6695 **
6696 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
6697 ** register an alternative page cache implementation by passing in an
6698 ** instance of the sqlite3_pcache_methods2 structure.)^
6699 ** In many applications, most of the heap memory allocated by
6700 ** SQLite is used for the page cache.
6701 ** By implementing a
6702 ** custom page cache using this API, an application can better control
6703 ** the amount of memory consumed by SQLite, the way in which
6704 ** that memory is allocated and released, and the policies used to
6705 ** determine exactly which parts of a database file are cached and for
6706 ** how long.
6707 **
6708 ** The alternative page cache mechanism is an
6709 ** extreme measure that is only needed by the most demanding applications.
6710 ** The built-in page cache is recommended for most uses.
6711 **
6712 ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
6713 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
6714 ** the application may discard the parameter after the call to
6715 ** [sqlite3_config()] returns.)^
6716 **
6717 ** [[the xInit() page cache method]]
6718 ** ^(The xInit() method is called once for each effective
6719 ** call to [sqlite3_initialize()])^
6720 ** (usually only once during the lifetime of the process). ^(The xInit()
6721 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
6722 ** The intent of the xInit() method is to set up global data structures
6723 ** required by the custom page cache implementation.
6724 ** ^(If the xInit() method is NULL, then the
6725 ** built-in default page cache is used instead of the application defined
6726 ** page cache.)^
6727 **
6728 ** [[the xShutdown() page cache method]]
6729 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
6730 ** It can be used to clean up
6731 ** any outstanding resources before process shutdown, if required.
6732 ** ^The xShutdown() method may be NULL.
6733 **
6734 ** ^SQLite automatically serializes calls to the xInit method,
6735 ** so the xInit method need not be threadsafe.  ^The
6736 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
6737 ** not need to be threadsafe either.  All other methods must be threadsafe
6738 ** in multithreaded applications.
6739 **
6740 ** ^SQLite will never invoke xInit() more than once without an intervening
6741 ** call to xShutdown().
6742 **
6743 ** [[the xCreate() page cache methods]]
6744 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6745 ** SQLite will typically create one cache instance for each open database file,
6746 ** though this is not guaranteed. ^The
6747 ** first parameter, szPage, is the size in bytes of the pages that must
6748 ** be allocated by the cache.  ^szPage will always a power of two.  ^The
6749 ** second parameter szExtra is a number of bytes of extra storage
6750 ** associated with each page cache entry.  ^The szExtra parameter will
6751 ** a number less than 250.  SQLite will use the
6752 ** extra szExtra bytes on each page to store metadata about the underlying
6753 ** database page on disk.  The value passed into szExtra depends
6754 ** on the SQLite version, the target platform, and how SQLite was compiled.
6755 ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
6756 ** created will be used to cache database pages of a file stored on disk, or
6757 ** false if it is used for an in-memory database. The cache implementation
6758 ** does not have to do anything special based with the value of bPurgeable;
6759 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
6760 ** never invoke xUnpin() except to deliberately delete a page.
6761 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6762 ** false will always have the "discard" flag set to true.
6763 ** ^Hence, a cache created with bPurgeable false will
6764 ** never contain any unpinned pages.
6765 **
6766 ** [[the xCachesize() page cache method]]
6767 ** ^(The xCachesize() method may be called at any time by SQLite to set the
6768 ** suggested maximum cache-size (number of pages stored by) the cache
6769 ** instance passed as the first argument. This is the value configured using
6770 ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
6771 ** parameter, the implementation is not required to do anything with this
6772 ** value; it is advisory only.
6773 **
6774 ** [[the xPagecount() page cache methods]]
6775 ** The xPagecount() method must return the number of pages currently
6776 ** stored in the cache, both pinned and unpinned.
6777 **
6778 ** [[the xFetch() page cache methods]]
6779 ** The xFetch() method locates a page in the cache and returns a pointer to
6780 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
6781 ** The pBuf element of the returned sqlite3_pcache_page object will be a
6782 ** pointer to a buffer of szPage bytes used to store the content of a
6783 ** single database page.  The pExtra element of sqlite3_pcache_page will be
6784 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
6785 ** for each entry in the page cache.
6786 **
6787 ** The page to be fetched is determined by the key. ^The minimum key value
6788 ** is 1.  After it has been retrieved using xFetch, the page is considered
6789 ** to be "pinned".
6790 **
6791 ** If the requested page is already in the page cache, then the page cache
6792 ** implementation must return a pointer to the page buffer with its content
6793 ** intact.  If the requested page is not already in the cache, then the
6794 ** cache implementation should use the value of the createFlag
6795 ** parameter to help it determined what action to take:
6796 **
6797 ** <table border=1 width=85% align=center>
6798 ** <tr><th> createFlag <th> Behavior when page is not already in cache
6799 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
6800 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6801 **                 Otherwise return NULL.
6802 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
6803 **                 NULL if allocating a new page is effectively impossible.
6804 ** </table>
6805 **
6806 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
6807 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
6808 ** failed.)^  In between the to xFetch() calls, SQLite may
6809 ** attempt to unpin one or more cache pages by spilling the content of
6810 ** pinned pages to disk and synching the operating system disk cache.
6811 **
6812 ** [[the xUnpin() page cache method]]
6813 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6814 ** as its second argument.  If the third parameter, discard, is non-zero,
6815 ** then the page must be evicted from the cache.
6816 ** ^If the discard parameter is
6817 ** zero, then the page may be discarded or retained at the discretion of
6818 ** page cache implementation. ^The page cache implementation
6819 ** may choose to evict unpinned pages at any time.
6820 **
6821 ** The cache must not perform any reference counting. A single
6822 ** call to xUnpin() unpins the page regardless of the number of prior calls
6823 ** to xFetch().
6824 **
6825 ** [[the xRekey() page cache methods]]
6826 ** The xRekey() method is used to change the key value associated with the
6827 ** page passed as the second argument. If the cache
6828 ** previously contains an entry associated with newKey, it must be
6829 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6830 ** to be pinned.
6831 **
6832 ** When SQLite calls the xTruncate() method, the cache must discard all
6833 ** existing cache entries with page numbers (keys) greater than or equal
6834 ** to the value of the iLimit parameter passed to xTruncate(). If any
6835 ** of these pages are pinned, they are implicitly unpinned, meaning that
6836 ** they can be safely discarded.
6837 **
6838 ** [[the xDestroy() page cache method]]
6839 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6840 ** All resources associated with the specified cache should be freed. ^After
6841 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
6842 ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
6843 ** functions.
6844 **
6845 ** [[the xShrink() page cache method]]
6846 ** ^SQLite invokes the xShrink() method when it wants the page cache to
6847 ** free up as much of heap memory as possible.  The page cache implementation
6848 ** is not obligated to free any memory, but well-behaved implementations should
6849 ** do their best.
6850 */
6851 typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
6852 struct sqlite3_pcache_methods2 {
6853   int iVersion;
6854   void *pArg;
6855   int (*xInit)(void*);
6856   void (*xShutdown)(void*);
6857   sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
6858   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6859   int (*xPagecount)(sqlite3_pcache*);
6860   sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6861   void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
6862   void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
6863       unsigned oldKey, unsigned newKey);
6864   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6865   void (*xDestroy)(sqlite3_pcache*);
6866   void (*xShrink)(sqlite3_pcache*);
6867 };
6868 
6869 /*
6870 ** This is the obsolete pcache_methods object that has now been replaced
6871 ** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
6872 ** retained in the header file for backwards compatibility only.
6873 */
6874 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
6875 struct sqlite3_pcache_methods {
6876   void *pArg;
6877   int (*xInit)(void*);
6878   void (*xShutdown)(void*);
6879   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
6880   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6881   int (*xPagecount)(sqlite3_pcache*);
6882   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6883   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
6884   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
6885   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6886   void (*xDestroy)(sqlite3_pcache*);
6887 };
6888 
6889 
6890 /*
6891 ** CAPI3REF: Online Backup Object
6892 **
6893 ** The sqlite3_backup object records state information about an ongoing
6894 ** online backup operation.  ^The sqlite3_backup object is created by
6895 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
6896 ** [sqlite3_backup_finish()].
6897 **
6898 ** See Also: [Using the SQLite Online Backup API]
6899 */
6900 typedef struct sqlite3_backup sqlite3_backup;
6901 
6902 /*
6903 ** CAPI3REF: Online Backup API.
6904 **
6905 ** The backup API copies the content of one database into another.
6906 ** It is useful either for creating backups of databases or
6907 ** for copying in-memory databases to or from persistent files.
6908 **
6909 ** See Also: [Using the SQLite Online Backup API]
6910 **
6911 ** ^SQLite holds a write transaction open on the destination database file
6912 ** for the duration of the backup operation.
6913 ** ^The source database is read-locked only while it is being read;
6914 ** it is not locked continuously for the entire backup operation.
6915 ** ^Thus, the backup may be performed on a live source database without
6916 ** preventing other database connections from
6917 ** reading or writing to the source database while the backup is underway.
6918 **
6919 ** ^(To perform a backup operation:
6920 **   <ol>
6921 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
6922 **         backup,
6923 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
6924 **         the data between the two databases, and finally
6925 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources
6926 **         associated with the backup operation.
6927 **   </ol>)^
6928 ** There should be exactly one call to sqlite3_backup_finish() for each
6929 ** successful call to sqlite3_backup_init().
6930 **
6931 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
6932 **
6933 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
6934 ** [database connection] associated with the destination database
6935 ** and the database name, respectively.
6936 ** ^The database name is "main" for the main database, "temp" for the
6937 ** temporary database, or the name specified after the AS keyword in
6938 ** an [ATTACH] statement for an attached database.
6939 ** ^The S and M arguments passed to
6940 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
6941 ** and database name of the source database, respectively.
6942 ** ^The source and destination [database connections] (parameters S and D)
6943 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
6944 ** an error.
6945 **
6946 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
6947 ** returned and an error code and error message are stored in the
6948 ** destination [database connection] D.
6949 ** ^The error code and message for the failed call to sqlite3_backup_init()
6950 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
6951 ** [sqlite3_errmsg16()] functions.
6952 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
6953 ** [sqlite3_backup] object.
6954 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
6955 ** sqlite3_backup_finish() functions to perform the specified backup
6956 ** operation.
6957 **
6958 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
6959 **
6960 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
6961 ** the source and destination databases specified by [sqlite3_backup] object B.
6962 ** ^If N is negative, all remaining source pages are copied.
6963 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
6964 ** are still more pages to be copied, then the function returns [SQLITE_OK].
6965 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
6966 ** from source to destination, then it returns [SQLITE_DONE].
6967 ** ^If an error occurs while running sqlite3_backup_step(B,N),
6968 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
6969 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
6970 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
6971 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
6972 **
6973 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
6974 ** <ol>
6975 ** <li> the destination database was opened read-only, or
6976 ** <li> the destination database is using write-ahead-log journaling
6977 ** and the destination and source page sizes differ, or
6978 ** <li> the destination database is an in-memory database and the
6979 ** destination and source page sizes differ.
6980 ** </ol>)^
6981 **
6982 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
6983 ** the [sqlite3_busy_handler | busy-handler function]
6984 ** is invoked (if one is specified). ^If the
6985 ** busy-handler returns non-zero before the lock is available, then
6986 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
6987 ** sqlite3_backup_step() can be retried later. ^If the source
6988 ** [database connection]
6989 ** is being used to write to the source database when sqlite3_backup_step()
6990 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
6991 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
6992 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
6993 ** [SQLITE_READONLY] is returned, then
6994 ** there is no point in retrying the call to sqlite3_backup_step(). These
6995 ** errors are considered fatal.)^  The application must accept
6996 ** that the backup operation has failed and pass the backup operation handle
6997 ** to the sqlite3_backup_finish() to release associated resources.
6998 **
6999 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
7000 ** on the destination file. ^The exclusive lock is not released until either
7001 ** sqlite3_backup_finish() is called or the backup operation is complete
7002 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
7003 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
7004 ** lasts for the duration of the sqlite3_backup_step() call.
7005 ** ^Because the source database is not locked between calls to
7006 ** sqlite3_backup_step(), the source database may be modified mid-way
7007 ** through the backup process.  ^If the source database is modified by an
7008 ** external process or via a database connection other than the one being
7009 ** used by the backup operation, then the backup will be automatically
7010 ** restarted by the next call to sqlite3_backup_step(). ^If the source
7011 ** database is modified by the using the same database connection as is used
7012 ** by the backup operation, then the backup database is automatically
7013 ** updated at the same time.
7014 **
7015 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
7016 **
7017 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
7018 ** application wishes to abandon the backup operation, the application
7019 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
7020 ** ^The sqlite3_backup_finish() interfaces releases all
7021 ** resources associated with the [sqlite3_backup] object.
7022 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
7023 ** active write-transaction on the destination database is rolled back.
7024 ** The [sqlite3_backup] object is invalid
7025 ** and may not be used following a call to sqlite3_backup_finish().
7026 **
7027 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
7028 ** sqlite3_backup_step() errors occurred, regardless or whether or not
7029 ** sqlite3_backup_step() completed.
7030 ** ^If an out-of-memory condition or IO error occurred during any prior
7031 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
7032 ** sqlite3_backup_finish() returns the corresponding [error code].
7033 **
7034 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
7035 ** is not a permanent error and does not affect the return value of
7036 ** sqlite3_backup_finish().
7037 **
7038 ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
7039 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
7040 **
7041 ** ^Each call to sqlite3_backup_step() sets two values inside
7042 ** the [sqlite3_backup] object: the number of pages still to be backed
7043 ** up and the total number of pages in the source database file.
7044 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
7045 ** retrieve these two values, respectively.
7046 **
7047 ** ^The values returned by these functions are only updated by
7048 ** sqlite3_backup_step(). ^If the source database is modified during a backup
7049 ** operation, then the values are not updated to account for any extra
7050 ** pages that need to be updated or the size of the source database file
7051 ** changing.
7052 **
7053 ** <b>Concurrent Usage of Database Handles</b>
7054 **
7055 ** ^The source [database connection] may be used by the application for other
7056 ** purposes while a backup operation is underway or being initialized.
7057 ** ^If SQLite is compiled and configured to support threadsafe database
7058 ** connections, then the source database connection may be used concurrently
7059 ** from within other threads.
7060 **
7061 ** However, the application must guarantee that the destination
7062 ** [database connection] is not passed to any other API (by any thread) after
7063 ** sqlite3_backup_init() is called and before the corresponding call to
7064 ** sqlite3_backup_finish().  SQLite does not currently check to see
7065 ** if the application incorrectly accesses the destination [database connection]
7066 ** and so no error code is reported, but the operations may malfunction
7067 ** nevertheless.  Use of the destination database connection while a
7068 ** backup is in progress might also also cause a mutex deadlock.
7069 **
7070 ** If running in [shared cache mode], the application must
7071 ** guarantee that the shared cache used by the destination database
7072 ** is not accessed while the backup is running. In practice this means
7073 ** that the application must guarantee that the disk file being
7074 ** backed up to is not accessed by any connection within the process,
7075 ** not just the specific connection that was passed to sqlite3_backup_init().
7076 **
7077 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
7078 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7079 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7080 ** APIs are not strictly speaking threadsafe. If they are invoked at the
7081 ** same time as another thread is invoking sqlite3_backup_step() it is
7082 ** possible that they return invalid values.
7083 */
7084 SQLITE_API sqlite3_backup *sqlite3_backup_init(
7085   sqlite3 *pDest,                        /* Destination database handle */
7086   const char *zDestName,                 /* Destination database name */
7087   sqlite3 *pSource,                      /* Source database handle */
7088   const char *zSourceName                /* Source database name */
7089 );
7090 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
7091 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
7092 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
7093 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
7094 
7095 /*
7096 ** CAPI3REF: Unlock Notification
7097 **
7098 ** ^When running in shared-cache mode, a database operation may fail with
7099 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
7100 ** individual tables within the shared-cache cannot be obtained. See
7101 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
7102 ** ^This API may be used to register a callback that SQLite will invoke
7103 ** when the connection currently holding the required lock relinquishes it.
7104 ** ^This API is only available if the library was compiled with the
7105 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
7106 **
7107 ** See Also: [Using the SQLite Unlock Notification Feature].
7108 **
7109 ** ^Shared-cache locks are released when a database connection concludes
7110 ** its current transaction, either by committing it or rolling it back.
7111 **
7112 ** ^When a connection (known as the blocked connection) fails to obtain a
7113 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
7114 ** identity of the database connection (the blocking connection) that
7115 ** has locked the required resource is stored internally. ^After an
7116 ** application receives an SQLITE_LOCKED error, it may call the
7117 ** sqlite3_unlock_notify() method with the blocked connection handle as
7118 ** the first argument to register for a callback that will be invoked
7119 ** when the blocking connections current transaction is concluded. ^The
7120 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
7121 ** call that concludes the blocking connections transaction.
7122 **
7123 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
7124 ** there is a chance that the blocking connection will have already
7125 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
7126 ** If this happens, then the specified callback is invoked immediately,
7127 ** from within the call to sqlite3_unlock_notify().)^
7128 **
7129 ** ^If the blocked connection is attempting to obtain a write-lock on a
7130 ** shared-cache table, and more than one other connection currently holds
7131 ** a read-lock on the same table, then SQLite arbitrarily selects one of
7132 ** the other connections to use as the blocking connection.
7133 **
7134 ** ^(There may be at most one unlock-notify callback registered by a
7135 ** blocked connection. If sqlite3_unlock_notify() is called when the
7136 ** blocked connection already has a registered unlock-notify callback,
7137 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
7138 ** called with a NULL pointer as its second argument, then any existing
7139 ** unlock-notify callback is canceled. ^The blocked connections
7140 ** unlock-notify callback may also be canceled by closing the blocked
7141 ** connection using [sqlite3_close()].
7142 **
7143 ** The unlock-notify callback is not reentrant. If an application invokes
7144 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
7145 ** crash or deadlock may be the result.
7146 **
7147 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
7148 ** returns SQLITE_OK.
7149 **
7150 ** <b>Callback Invocation Details</b>
7151 **
7152 ** When an unlock-notify callback is registered, the application provides a
7153 ** single void* pointer that is passed to the callback when it is invoked.
7154 ** However, the signature of the callback function allows SQLite to pass
7155 ** it an array of void* context pointers. The first argument passed to
7156 ** an unlock-notify callback is a pointer to an array of void* pointers,
7157 ** and the second is the number of entries in the array.
7158 **
7159 ** When a blocking connections transaction is concluded, there may be
7160 ** more than one blocked connection that has registered for an unlock-notify
7161 ** callback. ^If two or more such blocked connections have specified the
7162 ** same callback function, then instead of invoking the callback function
7163 ** multiple times, it is invoked once with the set of void* context pointers
7164 ** specified by the blocked connections bundled together into an array.
7165 ** This gives the application an opportunity to prioritize any actions
7166 ** related to the set of unblocked database connections.
7167 **
7168 ** <b>Deadlock Detection</b>
7169 **
7170 ** Assuming that after registering for an unlock-notify callback a
7171 ** database waits for the callback to be issued before taking any further
7172 ** action (a reasonable assumption), then using this API may cause the
7173 ** application to deadlock. For example, if connection X is waiting for
7174 ** connection Y's transaction to be concluded, and similarly connection
7175 ** Y is waiting on connection X's transaction, then neither connection
7176 ** will proceed and the system may remain deadlocked indefinitely.
7177 **
7178 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
7179 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
7180 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
7181 ** unlock-notify callback is registered. The system is said to be in
7182 ** a deadlocked state if connection A has registered for an unlock-notify
7183 ** callback on the conclusion of connection B's transaction, and connection
7184 ** B has itself registered for an unlock-notify callback when connection
7185 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
7186 ** the system is also considered to be deadlocked if connection B has
7187 ** registered for an unlock-notify callback on the conclusion of connection
7188 ** C's transaction, where connection C is waiting on connection A. ^Any
7189 ** number of levels of indirection are allowed.
7190 **
7191 ** <b>The "DROP TABLE" Exception</b>
7192 **
7193 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
7194 ** always appropriate to call sqlite3_unlock_notify(). There is however,
7195 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7196 ** SQLite checks if there are any currently executing SELECT statements
7197 ** that belong to the same connection. If there are, SQLITE_LOCKED is
7198 ** returned. In this case there is no "blocking connection", so invoking
7199 ** sqlite3_unlock_notify() results in the unlock-notify callback being
7200 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
7201 ** or "DROP INDEX" query, an infinite loop might be the result.
7202 **
7203 ** One way around this problem is to check the extended error code returned
7204 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7205 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7206 ** the special "DROP TABLE/INDEX" case, the extended error code is just
7207 ** SQLITE_LOCKED.)^
7208 */
7209 SQLITE_API int sqlite3_unlock_notify(
7210   sqlite3 *pBlocked,                          /* Waiting connection */
7211   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
7212   void *pNotifyArg                            /* Argument to pass to xNotify */
7213 );
7214 
7215 
7216 /*
7217 ** CAPI3REF: String Comparison
7218 **
7219 ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7220 ** and extensions to compare the contents of two buffers containing UTF-8
7221 ** strings in a case-independent fashion, using the same definition of "case
7222 ** independence" that SQLite uses internally when comparing identifiers.
7223 */
7224 SQLITE_API int sqlite3_stricmp(const char *, const char *);
7225 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
7226 
7227 /*
7228 ** CAPI3REF: String Globbing
7229 *
7230 ** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches
7231 ** the glob pattern P, and it returns non-zero if string X does not match
7232 ** the glob pattern P.  ^The definition of glob pattern matching used in
7233 ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
7234 ** SQL dialect used by SQLite.  ^The sqlite3_strglob(P,X) function is case
7235 ** sensitive.
7236 **
7237 ** Note that this routine returns zero on a match and non-zero if the strings
7238 ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
7239 */
7240 SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
7241 
7242 /*
7243 ** CAPI3REF: Error Logging Interface
7244 **
7245 ** ^The [sqlite3_log()] interface writes a message into the [error log]
7246 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
7247 ** ^If logging is enabled, the zFormat string and subsequent arguments are
7248 ** used with [sqlite3_snprintf()] to generate the final output string.
7249 **
7250 ** The sqlite3_log() interface is intended for use by extensions such as
7251 ** virtual tables, collating functions, and SQL functions.  While there is
7252 ** nothing to prevent an application from calling sqlite3_log(), doing so
7253 ** is considered bad form.
7254 **
7255 ** The zFormat string must not be NULL.
7256 **
7257 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
7258 ** will not use dynamically allocated memory.  The log message is stored in
7259 ** a fixed-length buffer on the stack.  If the log message is longer than
7260 ** a few hundred characters, it will be truncated to the length of the
7261 ** buffer.
7262 */
7263 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
7264 
7265 /*
7266 ** CAPI3REF: Write-Ahead Log Commit Hook
7267 **
7268 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
7269 ** will be invoked each time a database connection commits data to a
7270 ** [write-ahead log] (i.e. whenever a transaction is committed in
7271 ** [journal_mode | journal_mode=WAL mode]).
7272 **
7273 ** ^The callback is invoked by SQLite after the commit has taken place and
7274 ** the associated write-lock on the database released, so the implementation
7275 ** may read, write or [checkpoint] the database as required.
7276 **
7277 ** ^The first parameter passed to the callback function when it is invoked
7278 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
7279 ** registering the callback. ^The second is a copy of the database handle.
7280 ** ^The third parameter is the name of the database that was written to -
7281 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7282 ** is the number of pages currently in the write-ahead log file,
7283 ** including those that were just committed.
7284 **
7285 ** The callback function should normally return [SQLITE_OK].  ^If an error
7286 ** code is returned, that error will propagate back up through the
7287 ** SQLite code base to cause the statement that provoked the callback
7288 ** to report an error, though the commit will have still occurred. If the
7289 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7290 ** that does not correspond to any valid SQLite error code, the results
7291 ** are undefined.
7292 **
7293 ** A single database handle may have at most a single write-ahead log callback
7294 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7295 ** previously registered write-ahead log callback. ^Note that the
7296 ** [sqlite3_wal_autocheckpoint()] interface and the
7297 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7298 ** those overwrite any prior [sqlite3_wal_hook()] settings.
7299 */
7300 SQLITE_API void *sqlite3_wal_hook(
7301   sqlite3*,
7302   int(*)(void *,sqlite3*,const char*,int),
7303   void*
7304 );
7305 
7306 /*
7307 ** CAPI3REF: Configure an auto-checkpoint
7308 **
7309 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
7310 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
7311 ** to automatically [checkpoint]
7312 ** after committing a transaction if there are N or
7313 ** more frames in the [write-ahead log] file.  ^Passing zero or
7314 ** a negative value as the nFrame parameter disables automatic
7315 ** checkpoints entirely.
7316 **
7317 ** ^The callback registered by this function replaces any existing callback
7318 ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
7319 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
7320 ** configured by this function.
7321 **
7322 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7323 ** from SQL.
7324 **
7325 ** ^Checkpoints initiated by this mechanism are
7326 ** [sqlite3_wal_checkpoint_v2|PASSIVE].
7327 **
7328 ** ^Every new [database connection] defaults to having the auto-checkpoint
7329 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
7330 ** pages.  The use of this interface
7331 ** is only necessary if the default setting is found to be suboptimal
7332 ** for a particular application.
7333 */
7334 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
7335 
7336 /*
7337 ** CAPI3REF: Checkpoint a database
7338 **
7339 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
7340 ** on [database connection] D to be [checkpointed].  ^If X is NULL or an
7341 ** empty string, then a checkpoint is run on all databases of
7342 ** connection D.  ^If the database connection D is not in
7343 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
7344 ** ^The [sqlite3_wal_checkpoint(D,X)] interface initiates a
7345 ** [sqlite3_wal_checkpoint_v2|PASSIVE] checkpoint.
7346 ** Use the [sqlite3_wal_checkpoint_v2()] interface to get a FULL
7347 ** or RESET checkpoint.
7348 **
7349 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
7350 ** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
7351 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
7352 ** run whenever the WAL reaches a certain size threshold.
7353 **
7354 ** See also: [sqlite3_wal_checkpoint_v2()]
7355 */
7356 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
7357 
7358 /*
7359 ** CAPI3REF: Checkpoint a database
7360 **
7361 ** Run a checkpoint operation on WAL database zDb attached to database
7362 ** handle db. The specific operation is determined by the value of the
7363 ** eMode parameter:
7364 **
7365 ** <dl>
7366 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
7367 **   Checkpoint as many frames as possible without waiting for any database
7368 **   readers or writers to finish. Sync the db file if all frames in the log
7369 **   are checkpointed. This mode is the same as calling
7370 **   sqlite3_wal_checkpoint(). The [sqlite3_busy_handler|busy-handler callback]
7371 **   is never invoked.
7372 **
7373 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
7374 **   This mode blocks (it invokes the
7375 **   [sqlite3_busy_handler|busy-handler callback]) until there is no
7376 **   database writer and all readers are reading from the most recent database
7377 **   snapshot. It then checkpoints all frames in the log file and syncs the
7378 **   database file. This call blocks database writers while it is running,
7379 **   but not database readers.
7380 **
7381 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
7382 **   This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
7383 **   checkpointing the log file it blocks (calls the
7384 **   [sqlite3_busy_handler|busy-handler callback])
7385 **   until all readers are reading from the database file only. This ensures
7386 **   that the next client to write to the database file restarts the log file
7387 **   from the beginning. This call blocks database writers while it is running,
7388 **   but not database readers.
7389 ** </dl>
7390 **
7391 ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
7392 ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
7393 ** the total number of checkpointed frames (including any that were already
7394 ** checkpointed when this function is called). *pnLog and *pnCkpt may be
7395 ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
7396 ** If no values are available because of an error, they are both set to -1
7397 ** before returning to communicate this to the caller.
7398 **
7399 ** All calls obtain an exclusive "checkpoint" lock on the database file. If
7400 ** any other process is running a checkpoint operation at the same time, the
7401 ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
7402 ** busy-handler configured, it will not be invoked in this case.
7403 **
7404 ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
7405 ** "writer" lock on the database file. If the writer lock cannot be obtained
7406 ** immediately, and a busy-handler is configured, it is invoked and the writer
7407 ** lock retried until either the busy-handler returns 0 or the lock is
7408 ** successfully obtained. The busy-handler is also invoked while waiting for
7409 ** database readers as described above. If the busy-handler returns 0 before
7410 ** the writer lock is obtained or while waiting for database readers, the
7411 ** checkpoint operation proceeds from that point in the same way as
7412 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
7413 ** without blocking any further. SQLITE_BUSY is returned in this case.
7414 **
7415 ** If parameter zDb is NULL or points to a zero length string, then the
7416 ** specified operation is attempted on all WAL databases. In this case the
7417 ** values written to output parameters *pnLog and *pnCkpt are undefined. If
7418 ** an SQLITE_BUSY error is encountered when processing one or more of the
7419 ** attached WAL databases, the operation is still attempted on any remaining
7420 ** attached databases and SQLITE_BUSY is returned to the caller. If any other
7421 ** error occurs while processing an attached database, processing is abandoned
7422 ** and the error code returned to the caller immediately. If no error
7423 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
7424 ** databases, SQLITE_OK is returned.
7425 **
7426 ** If database zDb is the name of an attached database that is not in WAL
7427 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
7428 ** zDb is not NULL (or a zero length string) and is not the name of any
7429 ** attached database, SQLITE_ERROR is returned to the caller.
7430 */
7431 SQLITE_API int sqlite3_wal_checkpoint_v2(
7432   sqlite3 *db,                    /* Database handle */
7433   const char *zDb,                /* Name of attached database (or NULL) */
7434   int eMode,                      /* SQLITE_CHECKPOINT_* value */
7435   int *pnLog,                     /* OUT: Size of WAL log in frames */
7436   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
7437 );
7438 
7439 /*
7440 ** CAPI3REF: Checkpoint operation parameters
7441 **
7442 ** These constants can be used as the 3rd parameter to
7443 ** [sqlite3_wal_checkpoint_v2()].  See the [sqlite3_wal_checkpoint_v2()]
7444 ** documentation for additional information about the meaning and use of
7445 ** each of these values.
7446 */
7447 #define SQLITE_CHECKPOINT_PASSIVE 0
7448 #define SQLITE_CHECKPOINT_FULL    1
7449 #define SQLITE_CHECKPOINT_RESTART 2
7450 
7451 /*
7452 ** CAPI3REF: Virtual Table Interface Configuration
7453 **
7454 ** This function may be called by either the [xConnect] or [xCreate] method
7455 ** of a [virtual table] implementation to configure
7456 ** various facets of the virtual table interface.
7457 **
7458 ** If this interface is invoked outside the context of an xConnect or
7459 ** xCreate virtual table method then the behavior is undefined.
7460 **
7461 ** At present, there is only one option that may be configured using
7462 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
7463 ** may be added in the future.
7464 */
7465 SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
7466 
7467 /*
7468 ** CAPI3REF: Virtual Table Configuration Options
7469 **
7470 ** These macros define the various options to the
7471 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
7472 ** can use to customize and optimize their behavior.
7473 **
7474 ** <dl>
7475 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
7476 ** <dd>Calls of the form
7477 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
7478 ** where X is an integer.  If X is zero, then the [virtual table] whose
7479 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
7480 ** support constraints.  In this configuration (which is the default) if
7481 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
7482 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
7483 ** specified as part of the users SQL statement, regardless of the actual
7484 ** ON CONFLICT mode specified.
7485 **
7486 ** If X is non-zero, then the virtual table implementation guarantees
7487 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
7488 ** any modifications to internal or persistent data structures have been made.
7489 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
7490 ** is able to roll back a statement or database transaction, and abandon
7491 ** or continue processing the current SQL statement as appropriate.
7492 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
7493 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
7494 ** had been ABORT.
7495 **
7496 ** Virtual table implementations that are required to handle OR REPLACE
7497 ** must do so within the [xUpdate] method. If a call to the
7498 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
7499 ** CONFLICT policy is REPLACE, the virtual table implementation should
7500 ** silently replace the appropriate rows within the xUpdate callback and
7501 ** return SQLITE_OK. Or, if this is not possible, it may return
7502 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
7503 ** constraint handling.
7504 ** </dl>
7505 */
7506 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
7507 
7508 /*
7509 ** CAPI3REF: Determine The Virtual Table Conflict Policy
7510 **
7511 ** This function may only be called from within a call to the [xUpdate] method
7512 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
7513 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
7514 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
7515 ** of the SQL statement that triggered the call to the [xUpdate] method of the
7516 ** [virtual table].
7517 */
7518 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
7519 
7520 /*
7521 ** CAPI3REF: Conflict resolution modes
7522 ** KEYWORDS: {conflict resolution mode}
7523 **
7524 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
7525 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
7526 ** is for the SQL statement being evaluated.
7527 **
7528 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
7529 ** return value from the [sqlite3_set_authorizer()] callback and that
7530 ** [SQLITE_ABORT] is also a [result code].
7531 */
7532 #define SQLITE_ROLLBACK 1
7533 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
7534 #define SQLITE_FAIL     3
7535 /* #define SQLITE_ABORT 4  // Also an error code */
7536 #define SQLITE_REPLACE  5
7537 
7538 
7539 
7540 /*
7541 ** Undo the hack that converts floating point types to integer for
7542 ** builds on processors without floating point support.
7543 */
7544 #ifdef SQLITE_OMIT_FLOATING_POINT
7545 # undef double
7546 #endif
7547 
7548 #if 0
7549 }  /* End of the 'extern "C"' block */
7550 #endif
7551 #endif /* _SQLITE3_H_ */
7552 
7553 /*
7554 ** 2010 August 30
7555 **
7556 ** The author disclaims copyright to this source code.  In place of
7557 ** a legal notice, here is a blessing:
7558 **
7559 **    May you do good and not evil.
7560 **    May you find forgiveness for yourself and forgive others.
7561 **    May you share freely, never taking more than you give.
7562 **
7563 *************************************************************************
7564 */
7565 
7566 #ifndef _SQLITE3RTREE_H_
7567 #define _SQLITE3RTREE_H_
7568 
7569 
7570 #if 0
7571 extern "C" {
7572 #endif
7573 
7574 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
7575 typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
7576 
7577 /* The double-precision datatype used by RTree depends on the
7578 ** SQLITE_RTREE_INT_ONLY compile-time option.
7579 */
7580 #ifdef SQLITE_RTREE_INT_ONLY
7581   typedef sqlite3_int64 sqlite3_rtree_dbl;
7582 #else
7583   typedef double sqlite3_rtree_dbl;
7584 #endif
7585 
7586 /*
7587 ** Register a geometry callback named zGeom that can be used as part of an
7588 ** R-Tree geometry query as follows:
7589 **
7590 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
7591 */
7592 SQLITE_API int sqlite3_rtree_geometry_callback(
7593   sqlite3 *db,
7594   const char *zGeom,
7595   int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
7596   void *pContext
7597 );
7598 
7599 
7600 /*
7601 ** A pointer to a structure of the following type is passed as the first
7602 ** argument to callbacks registered using rtree_geometry_callback().
7603 */
7604 struct sqlite3_rtree_geometry {
7605   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
7606   int nParam;                     /* Size of array aParam[] */
7607   sqlite3_rtree_dbl *aParam;      /* Parameters passed to SQL geom function */
7608   void *pUser;                    /* Callback implementation user data */
7609   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
7610 };
7611 
7612 /*
7613 ** Register a 2nd-generation geometry callback named zScore that can be
7614 ** used as part of an R-Tree geometry query as follows:
7615 **
7616 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
7617 */
7618 SQLITE_API int sqlite3_rtree_query_callback(
7619   sqlite3 *db,
7620   const char *zQueryFunc,
7621   int (*xQueryFunc)(sqlite3_rtree_query_info*),
7622   void *pContext,
7623   void (*xDestructor)(void*)
7624 );
7625 
7626 
7627 /*
7628 ** A pointer to a structure of the following type is passed as the
7629 ** argument to scored geometry callback registered using
7630 ** sqlite3_rtree_query_callback().
7631 **
7632 ** Note that the first 5 fields of this structure are identical to
7633 ** sqlite3_rtree_geometry.  This structure is a subclass of
7634 ** sqlite3_rtree_geometry.
7635 */
7636 struct sqlite3_rtree_query_info {
7637   void *pContext;                   /* pContext from when function registered */
7638   int nParam;                       /* Number of function parameters */
7639   sqlite3_rtree_dbl *aParam;        /* value of function parameters */
7640   void *pUser;                      /* callback can use this, if desired */
7641   void (*xDelUser)(void*);          /* function to free pUser */
7642   sqlite3_rtree_dbl *aCoord;        /* Coordinates of node or entry to check */
7643   unsigned int *anQueue;            /* Number of pending entries in the queue */
7644   int nCoord;                       /* Number of coordinates */
7645   int iLevel;                       /* Level of current node or entry */
7646   int mxLevel;                      /* The largest iLevel value in the tree */
7647   sqlite3_int64 iRowid;             /* Rowid for current entry */
7648   sqlite3_rtree_dbl rParentScore;   /* Score of parent node */
7649   int eParentWithin;                /* Visibility of parent node */
7650   int eWithin;                      /* OUT: Visiblity */
7651   sqlite3_rtree_dbl rScore;         /* OUT: Write the score here */
7652 };
7653 
7654 /*
7655 ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
7656 */
7657 #define NOT_WITHIN       0   /* Object completely outside of query region */
7658 #define PARTLY_WITHIN    1   /* Object partially overlaps query region */
7659 #define FULLY_WITHIN     2   /* Object fully contained within query region */
7660 
7661 
7662 #if 0
7663 }  /* end of the 'extern "C"' block */
7664 #endif
7665 
7666 #endif  /* ifndef _SQLITE3RTREE_H_ */
7667 
7668 
7669 /************** End of sqlite3.h *********************************************/
7670 /************** Continuing where we left off in sqliteInt.h ******************/
7671 
7672 /*
7673 ** Include the configuration header output by 'configure' if we're using the
7674 ** autoconf-based build
7675 */
7676 #ifdef _HAVE_SQLITE_CONFIG_H
7677 #include "config.h"
7678 #endif
7679 
7680 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
7681 /************** Begin file sqliteLimit.h *************************************/
7682 /*
7683 ** 2007 May 7
7684 **
7685 ** The author disclaims copyright to this source code.  In place of
7686 ** a legal notice, here is a blessing:
7687 **
7688 **    May you do good and not evil.
7689 **    May you find forgiveness for yourself and forgive others.
7690 **    May you share freely, never taking more than you give.
7691 **
7692 *************************************************************************
7693 **
7694 ** This file defines various limits of what SQLite can process.
7695 */
7696 
7697 /*
7698 ** The maximum length of a TEXT or BLOB in bytes.   This also
7699 ** limits the size of a row in a table or index.
7700 **
7701 ** The hard limit is the ability of a 32-bit signed integer
7702 ** to count the size: 2^31-1 or 2147483647.
7703 */
7704 #ifndef SQLITE_MAX_LENGTH
7705 # define SQLITE_MAX_LENGTH 1000000000
7706 #endif
7707 
7708 /*
7709 ** This is the maximum number of
7710 **
7711 **    * Columns in a table
7712 **    * Columns in an index
7713 **    * Columns in a view
7714 **    * Terms in the SET clause of an UPDATE statement
7715 **    * Terms in the result set of a SELECT statement
7716 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
7717 **    * Terms in the VALUES clause of an INSERT statement
7718 **
7719 ** The hard upper limit here is 32676.  Most database people will
7720 ** tell you that in a well-normalized database, you usually should
7721 ** not have more than a dozen or so columns in any table.  And if
7722 ** that is the case, there is no point in having more than a few
7723 ** dozen values in any of the other situations described above.
7724 */
7725 #ifndef SQLITE_MAX_COLUMN
7726 # define SQLITE_MAX_COLUMN 2000
7727 #endif
7728 
7729 /*
7730 ** The maximum length of a single SQL statement in bytes.
7731 **
7732 ** It used to be the case that setting this value to zero would
7733 ** turn the limit off.  That is no longer true.  It is not possible
7734 ** to turn this limit off.
7735 */
7736 #ifndef SQLITE_MAX_SQL_LENGTH
7737 # define SQLITE_MAX_SQL_LENGTH 1000000000
7738 #endif
7739 
7740 /*
7741 ** The maximum depth of an expression tree. This is limited to
7742 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
7743 ** want to place more severe limits on the complexity of an
7744 ** expression.
7745 **
7746 ** A value of 0 used to mean that the limit was not enforced.
7747 ** But that is no longer true.  The limit is now strictly enforced
7748 ** at all times.
7749 */
7750 #ifndef SQLITE_MAX_EXPR_DEPTH
7751 # define SQLITE_MAX_EXPR_DEPTH 1000
7752 #endif
7753 
7754 /*
7755 ** The maximum number of terms in a compound SELECT statement.
7756 ** The code generator for compound SELECT statements does one
7757 ** level of recursion for each term.  A stack overflow can result
7758 ** if the number of terms is too large.  In practice, most SQL
7759 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
7760 ** any limit on the number of terms in a compount SELECT.
7761 */
7762 #ifndef SQLITE_MAX_COMPOUND_SELECT
7763 # define SQLITE_MAX_COMPOUND_SELECT 500
7764 #endif
7765 
7766 /*
7767 ** The maximum number of opcodes in a VDBE program.
7768 ** Not currently enforced.
7769 */
7770 #ifndef SQLITE_MAX_VDBE_OP
7771 # define SQLITE_MAX_VDBE_OP 25000
7772 #endif
7773 
7774 /*
7775 ** The maximum number of arguments to an SQL function.
7776 */
7777 #ifndef SQLITE_MAX_FUNCTION_ARG
7778 # define SQLITE_MAX_FUNCTION_ARG 127
7779 #endif
7780 
7781 /*
7782 ** The maximum number of in-memory pages to use for the main database
7783 ** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
7784 */
7785 #ifndef SQLITE_DEFAULT_CACHE_SIZE
7786 # define SQLITE_DEFAULT_CACHE_SIZE  2000
7787 #endif
7788 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
7789 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
7790 #endif
7791 
7792 /*
7793 ** The default number of frames to accumulate in the log file before
7794 ** checkpointing the database in WAL mode.
7795 */
7796 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
7797 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
7798 #endif
7799 
7800 /*
7801 ** The maximum number of attached databases.  This must be between 0
7802 ** and 62.  The upper bound on 62 is because a 64-bit integer bitmap
7803 ** is used internally to track attached databases.
7804 */
7805 #ifndef SQLITE_MAX_ATTACHED
7806 # define SQLITE_MAX_ATTACHED 10
7807 #endif
7808 
7809 
7810 /*
7811 ** The maximum value of a ?nnn wildcard that the parser will accept.
7812 */
7813 #ifndef SQLITE_MAX_VARIABLE_NUMBER
7814 # define SQLITE_MAX_VARIABLE_NUMBER 999
7815 #endif
7816 
7817 /* Maximum page size.  The upper bound on this value is 65536.  This a limit
7818 ** imposed by the use of 16-bit offsets within each page.
7819 **
7820 ** Earlier versions of SQLite allowed the user to change this value at
7821 ** compile time. This is no longer permitted, on the grounds that it creates
7822 ** a library that is technically incompatible with an SQLite library
7823 ** compiled with a different limit. If a process operating on a database
7824 ** with a page-size of 65536 bytes crashes, then an instance of SQLite
7825 ** compiled with the default page-size limit will not be able to rollback
7826 ** the aborted transaction. This could lead to database corruption.
7827 */
7828 #ifdef SQLITE_MAX_PAGE_SIZE
7829 # undef SQLITE_MAX_PAGE_SIZE
7830 #endif
7831 #define SQLITE_MAX_PAGE_SIZE 65536
7832 
7833 
7834 /*
7835 ** The default size of a database page.
7836 */
7837 #ifndef SQLITE_DEFAULT_PAGE_SIZE
7838 # define SQLITE_DEFAULT_PAGE_SIZE 1024
7839 #endif
7840 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
7841 # undef SQLITE_DEFAULT_PAGE_SIZE
7842 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
7843 #endif
7844 
7845 /*
7846 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
7847 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
7848 ** device characteristics (sector-size and atomic write() support),
7849 ** SQLite may choose a larger value. This constant is the maximum value
7850 ** SQLite will choose on its own.
7851 */
7852 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
7853 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
7854 #endif
7855 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
7856 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
7857 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
7858 #endif
7859 
7860 
7861 /*
7862 ** Maximum number of pages in one database file.
7863 **
7864 ** This is really just the default value for the max_page_count pragma.
7865 ** This value can be lowered (or raised) at run-time using that the
7866 ** max_page_count macro.
7867 */
7868 #ifndef SQLITE_MAX_PAGE_COUNT
7869 # define SQLITE_MAX_PAGE_COUNT 1073741823
7870 #endif
7871 
7872 /*
7873 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
7874 ** operator.
7875 */
7876 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
7877 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
7878 #endif
7879 
7880 /*
7881 ** Maximum depth of recursion for triggers.
7882 **
7883 ** A value of 1 means that a trigger program will not be able to itself
7884 ** fire any triggers. A value of 0 means that no trigger programs at all
7885 ** may be executed.
7886 */
7887 #ifndef SQLITE_MAX_TRIGGER_DEPTH
7888 # define SQLITE_MAX_TRIGGER_DEPTH 1000
7889 #endif
7890 
7891 /************** End of sqliteLimit.h *****************************************/
7892 /************** Continuing where we left off in sqliteInt.h ******************/
7893 
7894 /* Disable nuisance warnings on Borland compilers */
7895 #if defined(__BORLANDC__)
7896 #pragma warn -rch /* unreachable code */
7897 #pragma warn -ccc /* Condition is always true or false */
7898 #pragma warn -aus /* Assigned value is never used */
7899 #pragma warn -csu /* Comparing signed and unsigned */
7900 #pragma warn -spa /* Suspicious pointer arithmetic */
7901 #endif
7902 
7903 /*
7904 ** Include standard header files as necessary
7905 */
7906 #ifdef HAVE_STDINT_H
7907 #include <stdint.h>
7908 #endif
7909 #ifdef HAVE_INTTYPES_H
7910 #include <inttypes.h>
7911 #endif
7912 
7913 /*
7914 ** The following macros are used to cast pointers to integers and
7915 ** integers to pointers.  The way you do this varies from one compiler
7916 ** to the next, so we have developed the following set of #if statements
7917 ** to generate appropriate macros for a wide range of compilers.
7918 **
7919 ** The correct "ANSI" way to do this is to use the intptr_t type.
7920 ** Unfortunately, that typedef is not available on all compilers, or
7921 ** if it is available, it requires an #include of specific headers
7922 ** that vary from one machine to the next.
7923 **
7924 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
7925 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
7926 ** So we have to define the macros in different ways depending on the
7927 ** compiler.
7928 */
7929 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
7930 # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
7931 # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
7932 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
7933 # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
7934 # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
7935 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
7936 # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
7937 # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
7938 #else                          /* Generates a warning - but it always works */
7939 # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
7940 # define SQLITE_PTR_TO_INT(X)  ((int)(X))
7941 #endif
7942 
7943 /*
7944 ** A macro to hint to the compiler that a function should not be
7945 ** inlined.
7946 */
7947 #if defined(__GNUC__)
7948 #  define SQLITE_NOINLINE  __attribute__((noinline))
7949 #elif defined(_MSC_VER) && _MSC_VER>=1310
7950 #  define SQLITE_NOINLINE  __declspec(noinline)
7951 #else
7952 #  define SQLITE_NOINLINE
7953 #endif
7954 
7955 /*
7956 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
7957 ** 0 means mutexes are permanently disable and the library is never
7958 ** threadsafe.  1 means the library is serialized which is the highest
7959 ** level of threadsafety.  2 means the library is multithreaded - multiple
7960 ** threads can use SQLite as long as no two threads try to use the same
7961 ** database connection at the same time.
7962 **
7963 ** Older versions of SQLite used an optional THREADSAFE macro.
7964 ** We support that for legacy.
7965 */
7966 #if !defined(SQLITE_THREADSAFE)
7967 # if defined(THREADSAFE)
7968 #   define SQLITE_THREADSAFE THREADSAFE
7969 # else
7970 #   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
7971 # endif
7972 #endif
7973 
7974 /*
7975 ** Powersafe overwrite is on by default.  But can be turned off using
7976 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
7977 */
7978 #ifndef SQLITE_POWERSAFE_OVERWRITE
7979 # define SQLITE_POWERSAFE_OVERWRITE 1
7980 #endif
7981 
7982 /*
7983 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
7984 ** It determines whether or not the features related to
7985 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
7986 ** be overridden at runtime using the sqlite3_config() API.
7987 */
7988 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
7989 # define SQLITE_DEFAULT_MEMSTATUS 1
7990 #endif
7991 
7992 /*
7993 ** Exactly one of the following macros must be defined in order to
7994 ** specify which memory allocation subsystem to use.
7995 **
7996 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
7997 **     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
7998 **     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
7999 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
8000 **
8001 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
8002 ** assert() macro is enabled, each call into the Win32 native heap subsystem
8003 ** will cause HeapValidate to be called.  If heap validation should fail, an
8004 ** assertion will be triggered.
8005 **
8006 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
8007 ** the default.
8008 */
8009 #if defined(SQLITE_SYSTEM_MALLOC) \
8010   + defined(SQLITE_WIN32_MALLOC) \
8011   + defined(SQLITE_ZERO_MALLOC) \
8012   + defined(SQLITE_MEMDEBUG)>1
8013 # error "Two or more of the following compile-time configuration options\
8014  are defined but at most one is allowed:\
8015  SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
8016  SQLITE_ZERO_MALLOC"
8017 #endif
8018 #if defined(SQLITE_SYSTEM_MALLOC) \
8019   + defined(SQLITE_WIN32_MALLOC) \
8020   + defined(SQLITE_ZERO_MALLOC) \
8021   + defined(SQLITE_MEMDEBUG)==0
8022 # define SQLITE_SYSTEM_MALLOC 1
8023 #endif
8024 
8025 /*
8026 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
8027 ** sizes of memory allocations below this value where possible.
8028 */
8029 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
8030 # define SQLITE_MALLOC_SOFT_LIMIT 1024
8031 #endif
8032 
8033 /*
8034 ** We need to define _XOPEN_SOURCE as follows in order to enable
8035 ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
8036 ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
8037 ** it.
8038 */
8039 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
8040 #  define _XOPEN_SOURCE 600
8041 #endif
8042 
8043 /*
8044 ** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
8045 ** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
8046 ** make it true by defining or undefining NDEBUG.
8047 **
8048 ** Setting NDEBUG makes the code smaller and faster by disabling the
8049 ** assert() statements in the code.  So we want the default action
8050 ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
8051 ** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
8052 ** feature.
8053 */
8054 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
8055 # define NDEBUG 1
8056 #endif
8057 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
8058 # undef NDEBUG
8059 #endif
8060 
8061 /*
8062 ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
8063 */
8064 #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
8065 # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
8066 #endif
8067 
8068 /*
8069 ** The testcase() macro is used to aid in coverage testing.  When
8070 ** doing coverage testing, the condition inside the argument to
8071 ** testcase() must be evaluated both true and false in order to
8072 ** get full branch coverage.  The testcase() macro is inserted
8073 ** to help ensure adequate test coverage in places where simple
8074 ** condition/decision coverage is inadequate.  For example, testcase()
8075 ** can be used to make sure boundary values are tested.  For
8076 ** bitmask tests, testcase() can be used to make sure each bit
8077 ** is significant and used at least once.  On switch statements
8078 ** where multiple cases go to the same block of code, testcase()
8079 ** can insure that all cases are evaluated.
8080 **
8081 */
8082 #ifdef SQLITE_COVERAGE_TEST
8083 SQLITE_PRIVATE   void sqlite3Coverage(int);
8084 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
8085 #else
8086 # define testcase(X)
8087 #endif
8088 
8089 /*
8090 ** The TESTONLY macro is used to enclose variable declarations or
8091 ** other bits of code that are needed to support the arguments
8092 ** within testcase() and assert() macros.
8093 */
8094 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
8095 # define TESTONLY(X)  X
8096 #else
8097 # define TESTONLY(X)
8098 #endif
8099 
8100 /*
8101 ** Sometimes we need a small amount of code such as a variable initialization
8102 ** to setup for a later assert() statement.  We do not want this code to
8103 ** appear when assert() is disabled.  The following macro is therefore
8104 ** used to contain that setup code.  The "VVA" acronym stands for
8105 ** "Verification, Validation, and Accreditation".  In other words, the
8106 ** code within VVA_ONLY() will only run during verification processes.
8107 */
8108 #ifndef NDEBUG
8109 # define VVA_ONLY(X)  X
8110 #else
8111 # define VVA_ONLY(X)
8112 #endif
8113 
8114 /*
8115 ** The ALWAYS and NEVER macros surround boolean expressions which
8116 ** are intended to always be true or false, respectively.  Such
8117 ** expressions could be omitted from the code completely.  But they
8118 ** are included in a few cases in order to enhance the resilience
8119 ** of SQLite to unexpected behavior - to make the code "self-healing"
8120 ** or "ductile" rather than being "brittle" and crashing at the first
8121 ** hint of unplanned behavior.
8122 **
8123 ** In other words, ALWAYS and NEVER are added for defensive code.
8124 **
8125 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
8126 ** be true and false so that the unreachable code they specify will
8127 ** not be counted as untested code.
8128 */
8129 #if defined(SQLITE_COVERAGE_TEST)
8130 # define ALWAYS(X)      (1)
8131 # define NEVER(X)       (0)
8132 #elif !defined(NDEBUG)
8133 # define ALWAYS(X)      ((X)?1:(assert(0),0))
8134 # define NEVER(X)       ((X)?(assert(0),1):0)
8135 #else
8136 # define ALWAYS(X)      (X)
8137 # define NEVER(X)       (X)
8138 #endif
8139 
8140 /*
8141 ** Return true (non-zero) if the input is an integer that is too large
8142 ** to fit in 32-bits.  This macro is used inside of various testcase()
8143 ** macros to verify that we have tested SQLite for large-file support.
8144 */
8145 #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
8146 
8147 /*
8148 ** The macro unlikely() is a hint that surrounds a boolean
8149 ** expression that is usually false.  Macro likely() surrounds
8150 ** a boolean expression that is usually true.  These hints could,
8151 ** in theory, be used by the compiler to generate better code, but
8152 ** currently they are just comments for human readers.
8153 */
8154 #define likely(X)    (X)
8155 #define unlikely(X)  (X)
8156 
8157 /************** Include hash.h in the middle of sqliteInt.h ******************/
8158 /************** Begin file hash.h ********************************************/
8159 /*
8160 ** 2001 September 22
8161 **
8162 ** The author disclaims copyright to this source code.  In place of
8163 ** a legal notice, here is a blessing:
8164 **
8165 **    May you do good and not evil.
8166 **    May you find forgiveness for yourself and forgive others.
8167 **    May you share freely, never taking more than you give.
8168 **
8169 *************************************************************************
8170 ** This is the header file for the generic hash-table implementation
8171 ** used in SQLite.
8172 */
8173 #ifndef _SQLITE_HASH_H_
8174 #define _SQLITE_HASH_H_
8175 
8176 /* Forward declarations of structures. */
8177 typedef struct Hash Hash;
8178 typedef struct HashElem HashElem;
8179 
8180 /* A complete hash table is an instance of the following structure.
8181 ** The internals of this structure are intended to be opaque -- client
8182 ** code should not attempt to access or modify the fields of this structure
8183 ** directly.  Change this structure only by using the routines below.
8184 ** However, some of the "procedures" and "functions" for modifying and
8185 ** accessing this structure are really macros, so we can't really make
8186 ** this structure opaque.
8187 **
8188 ** All elements of the hash table are on a single doubly-linked list.
8189 ** Hash.first points to the head of this list.
8190 **
8191 ** There are Hash.htsize buckets.  Each bucket points to a spot in
8192 ** the global doubly-linked list.  The contents of the bucket are the
8193 ** element pointed to plus the next _ht.count-1 elements in the list.
8194 **
8195 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
8196 ** by a linear search of the global list.  For small tables, the
8197 ** Hash.ht table is never allocated because if there are few elements
8198 ** in the table, it is faster to do a linear search than to manage
8199 ** the hash table.
8200 */
8201 struct Hash {
8202   unsigned int htsize;      /* Number of buckets in the hash table */
8203   unsigned int count;       /* Number of entries in this table */
8204   HashElem *first;          /* The first element of the array */
8205   struct _ht {              /* the hash table */
8206     int count;                 /* Number of entries with this hash */
8207     HashElem *chain;           /* Pointer to first entry with this hash */
8208   } *ht;
8209 };
8210 
8211 /* Each element in the hash table is an instance of the following
8212 ** structure.  All elements are stored on a single doubly-linked list.
8213 **
8214 ** Again, this structure is intended to be opaque, but it can't really
8215 ** be opaque because it is used by macros.
8216 */
8217 struct HashElem {
8218   HashElem *next, *prev;       /* Next and previous elements in the table */
8219   void *data;                  /* Data associated with this element */
8220   const char *pKey;            /* Key associated with this element */
8221 };
8222 
8223 /*
8224 ** Access routines.  To delete, insert a NULL pointer.
8225 */
8226 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
8227 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
8228 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
8229 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
8230 
8231 /*
8232 ** Macros for looping over all elements of a hash table.  The idiom is
8233 ** like this:
8234 **
8235 **   Hash h;
8236 **   HashElem *p;
8237 **   ...
8238 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
8239 **     SomeStructure *pData = sqliteHashData(p);
8240 **     // do something with pData
8241 **   }
8242 */
8243 #define sqliteHashFirst(H)  ((H)->first)
8244 #define sqliteHashNext(E)   ((E)->next)
8245 #define sqliteHashData(E)   ((E)->data)
8246 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
8247 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
8248 
8249 /*
8250 ** Number of entries in a hash table
8251 */
8252 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
8253 
8254 #endif /* _SQLITE_HASH_H_ */
8255 
8256 /************** End of hash.h ************************************************/
8257 /************** Continuing where we left off in sqliteInt.h ******************/
8258 /************** Include parse.h in the middle of sqliteInt.h *****************/
8259 /************** Begin file parse.h *******************************************/
8260 #define TK_SEMI                             1
8261 #define TK_EXPLAIN                          2
8262 #define TK_QUERY                            3
8263 #define TK_PLAN                             4
8264 #define TK_BEGIN                            5
8265 #define TK_TRANSACTION                      6
8266 #define TK_DEFERRED                         7
8267 #define TK_IMMEDIATE                        8
8268 #define TK_EXCLUSIVE                        9
8269 #define TK_COMMIT                          10
8270 #define TK_END                             11
8271 #define TK_ROLLBACK                        12
8272 #define TK_SAVEPOINT                       13
8273 #define TK_RELEASE                         14
8274 #define TK_TO                              15
8275 #define TK_TABLE                           16
8276 #define TK_CREATE                          17
8277 #define TK_IF                              18
8278 #define TK_NOT                             19
8279 #define TK_EXISTS                          20
8280 #define TK_TEMP                            21
8281 #define TK_LP                              22
8282 #define TK_RP                              23
8283 #define TK_AS                              24
8284 #define TK_WITHOUT                         25
8285 #define TK_COMMA                           26
8286 #define TK_ID                              27
8287 #define TK_INDEXED                         28
8288 #define TK_ABORT                           29
8289 #define TK_ACTION                          30
8290 #define TK_AFTER                           31
8291 #define TK_ANALYZE                         32
8292 #define TK_ASC                             33
8293 #define TK_ATTACH                          34
8294 #define TK_BEFORE                          35
8295 #define TK_BY                              36
8296 #define TK_CASCADE                         37
8297 #define TK_CAST                            38
8298 #define TK_COLUMNKW                        39
8299 #define TK_CONFLICT                        40
8300 #define TK_DATABASE                        41
8301 #define TK_DESC                            42
8302 #define TK_DETACH                          43
8303 #define TK_EACH                            44
8304 #define TK_FAIL                            45
8305 #define TK_FOR                             46
8306 #define TK_IGNORE                          47
8307 #define TK_INITIALLY                       48
8308 #define TK_INSTEAD                         49
8309 #define TK_LIKE_KW                         50
8310 #define TK_MATCH                           51
8311 #define TK_NO                              52
8312 #define TK_KEY                             53
8313 #define TK_OF                              54
8314 #define TK_OFFSET                          55
8315 #define TK_PRAGMA                          56
8316 #define TK_RAISE                           57
8317 #define TK_RECURSIVE                       58
8318 #define TK_REPLACE                         59
8319 #define TK_RESTRICT                        60
8320 #define TK_ROW                             61
8321 #define TK_TRIGGER                         62
8322 #define TK_VACUUM                          63
8323 #define TK_VIEW                            64
8324 #define TK_VIRTUAL                         65
8325 #define TK_WITH                            66
8326 #define TK_REINDEX                         67
8327 #define TK_RENAME                          68
8328 #define TK_CTIME_KW                        69
8329 #define TK_ANY                             70
8330 #define TK_OR                              71
8331 #define TK_AND                             72
8332 #define TK_IS                              73
8333 #define TK_BETWEEN                         74
8334 #define TK_IN                              75
8335 #define TK_ISNULL                          76
8336 #define TK_NOTNULL                         77
8337 #define TK_NE                              78
8338 #define TK_EQ                              79
8339 #define TK_GT                              80
8340 #define TK_LE                              81
8341 #define TK_LT                              82
8342 #define TK_GE                              83
8343 #define TK_ESCAPE                          84
8344 #define TK_BITAND                          85
8345 #define TK_BITOR                           86
8346 #define TK_LSHIFT                          87
8347 #define TK_RSHIFT                          88
8348 #define TK_PLUS                            89
8349 #define TK_MINUS                           90
8350 #define TK_STAR                            91
8351 #define TK_SLASH                           92
8352 #define TK_REM                             93
8353 #define TK_CONCAT                          94
8354 #define TK_COLLATE                         95
8355 #define TK_BITNOT                          96
8356 #define TK_STRING                          97
8357 #define TK_JOIN_KW                         98
8358 #define TK_CONSTRAINT                      99
8359 #define TK_DEFAULT                        100
8360 #define TK_NULL                           101
8361 #define TK_PRIMARY                        102
8362 #define TK_UNIQUE                         103
8363 #define TK_CHECK                          104
8364 #define TK_REFERENCES                     105
8365 #define TK_AUTOINCR                       106
8366 #define TK_ON                             107
8367 #define TK_INSERT                         108
8368 #define TK_DELETE                         109
8369 #define TK_UPDATE                         110
8370 #define TK_SET                            111
8371 #define TK_DEFERRABLE                     112
8372 #define TK_FOREIGN                        113
8373 #define TK_DROP                           114
8374 #define TK_UNION                          115
8375 #define TK_ALL                            116
8376 #define TK_EXCEPT                         117
8377 #define TK_INTERSECT                      118
8378 #define TK_SELECT                         119
8379 #define TK_VALUES                         120
8380 #define TK_DISTINCT                       121
8381 #define TK_DOT                            122
8382 #define TK_FROM                           123
8383 #define TK_JOIN                           124
8384 #define TK_USING                          125
8385 #define TK_ORDER                          126
8386 #define TK_GROUP                          127
8387 #define TK_HAVING                         128
8388 #define TK_LIMIT                          129
8389 #define TK_WHERE                          130
8390 #define TK_INTO                           131
8391 #define TK_INTEGER                        132
8392 #define TK_FLOAT                          133
8393 #define TK_BLOB                           134
8394 #define TK_VARIABLE                       135
8395 #define TK_CASE                           136
8396 #define TK_WHEN                           137
8397 #define TK_THEN                           138
8398 #define TK_ELSE                           139
8399 #define TK_INDEX                          140
8400 #define TK_ALTER                          141
8401 #define TK_ADD                            142
8402 #define TK_TO_TEXT                        143
8403 #define TK_TO_BLOB                        144
8404 #define TK_TO_NUMERIC                     145
8405 #define TK_TO_INT                         146
8406 #define TK_TO_REAL                        147
8407 #define TK_ISNOT                          148
8408 #define TK_END_OF_FILE                    149
8409 #define TK_ILLEGAL                        150
8410 #define TK_SPACE                          151
8411 #define TK_UNCLOSED_STRING                152
8412 #define TK_FUNCTION                       153
8413 #define TK_COLUMN                         154
8414 #define TK_AGG_FUNCTION                   155
8415 #define TK_AGG_COLUMN                     156
8416 #define TK_UMINUS                         157
8417 #define TK_UPLUS                          158
8418 #define TK_REGISTER                       159
8419 
8420 /************** End of parse.h ***********************************************/
8421 /************** Continuing where we left off in sqliteInt.h ******************/
8422 #include <stdio.h>
8423 #include <stdlib.h>
8424 #include <string.h>
8425 #include <assert.h>
8426 #include <stddef.h>
8427 
8428 /*
8429 ** If compiling for a processor that lacks floating point support,
8430 ** substitute integer for floating-point
8431 */
8432 #ifdef SQLITE_OMIT_FLOATING_POINT
8433 # define double sqlite_int64
8434 # define float sqlite_int64
8435 # define LONGDOUBLE_TYPE sqlite_int64
8436 # ifndef SQLITE_BIG_DBL
8437 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
8438 # endif
8439 # define SQLITE_OMIT_DATETIME_FUNCS 1
8440 # define SQLITE_OMIT_TRACE 1
8441 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
8442 # undef SQLITE_HAVE_ISNAN
8443 #endif
8444 #ifndef SQLITE_BIG_DBL
8445 # define SQLITE_BIG_DBL (1e99)
8446 #endif
8447 
8448 /*
8449 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
8450 ** afterward. Having this macro allows us to cause the C compiler
8451 ** to omit code used by TEMP tables without messy #ifndef statements.
8452 */
8453 #ifdef SQLITE_OMIT_TEMPDB
8454 #define OMIT_TEMPDB 1
8455 #else
8456 #define OMIT_TEMPDB 0
8457 #endif
8458 
8459 /*
8460 ** The "file format" number is an integer that is incremented whenever
8461 ** the VDBE-level file format changes.  The following macros define the
8462 ** the default file format for new databases and the maximum file format
8463 ** that the library can read.
8464 */
8465 #define SQLITE_MAX_FILE_FORMAT 4
8466 #ifndef SQLITE_DEFAULT_FILE_FORMAT
8467 # define SQLITE_DEFAULT_FILE_FORMAT 4
8468 #endif
8469 
8470 /*
8471 ** Determine whether triggers are recursive by default.  This can be
8472 ** changed at run-time using a pragma.
8473 */
8474 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
8475 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
8476 #endif
8477 
8478 /*
8479 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
8480 ** on the command-line
8481 */
8482 #ifndef SQLITE_TEMP_STORE
8483 # define SQLITE_TEMP_STORE 1
8484 # define SQLITE_TEMP_STORE_xc 1  /* Exclude from ctime.c */
8485 #endif
8486 
8487 /*
8488 ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
8489 ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
8490 ** to zero.
8491 */
8492 #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
8493 # undef SQLITE_MAX_WORKER_THREADS
8494 # define SQLITE_MAX_WORKER_THREADS 0
8495 #endif
8496 #ifndef SQLITE_MAX_WORKER_THREADS
8497 # define SQLITE_MAX_WORKER_THREADS 8
8498 #endif
8499 #ifndef SQLITE_DEFAULT_WORKER_THREADS
8500 # define SQLITE_DEFAULT_WORKER_THREADS 0
8501 #endif
8502 #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
8503 # undef SQLITE_MAX_WORKER_THREADS
8504 # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
8505 #endif
8506 
8507 
8508 /*
8509 ** GCC does not define the offsetof() macro so we'll have to do it
8510 ** ourselves.
8511 */
8512 #ifndef offsetof
8513 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
8514 #endif
8515 
8516 /*
8517 ** Macros to compute minimum and maximum of two numbers.
8518 */
8519 #define MIN(A,B) ((A)<(B)?(A):(B))
8520 #define MAX(A,B) ((A)>(B)?(A):(B))
8521 
8522 /*
8523 ** Swap two objects of type TYPE.
8524 */
8525 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
8526 
8527 /*
8528 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
8529 ** not, there are still machines out there that use EBCDIC.)
8530 */
8531 #if 'A' == '\301'
8532 # define SQLITE_EBCDIC 1
8533 #else
8534 # define SQLITE_ASCII 1
8535 #endif
8536 
8537 /*
8538 ** Integers of known sizes.  These typedefs might change for architectures
8539 ** where the sizes very.  Preprocessor macros are available so that the
8540 ** types can be conveniently redefined at compile-type.  Like this:
8541 **
8542 **         cc '-DUINTPTR_TYPE=long long int' ...
8543 */
8544 #ifndef UINT32_TYPE
8545 # ifdef HAVE_UINT32_T
8546 #  define UINT32_TYPE uint32_t
8547 # else
8548 #  define UINT32_TYPE unsigned int
8549 # endif
8550 #endif
8551 #ifndef UINT16_TYPE
8552 # ifdef HAVE_UINT16_T
8553 #  define UINT16_TYPE uint16_t
8554 # else
8555 #  define UINT16_TYPE unsigned short int
8556 # endif
8557 #endif
8558 #ifndef INT16_TYPE
8559 # ifdef HAVE_INT16_T
8560 #  define INT16_TYPE int16_t
8561 # else
8562 #  define INT16_TYPE short int
8563 # endif
8564 #endif
8565 #ifndef UINT8_TYPE
8566 # ifdef HAVE_UINT8_T
8567 #  define UINT8_TYPE uint8_t
8568 # else
8569 #  define UINT8_TYPE unsigned char
8570 # endif
8571 #endif
8572 #ifndef INT8_TYPE
8573 # ifdef HAVE_INT8_T
8574 #  define INT8_TYPE int8_t
8575 # else
8576 #  define INT8_TYPE signed char
8577 # endif
8578 #endif
8579 #ifndef LONGDOUBLE_TYPE
8580 # define LONGDOUBLE_TYPE long double
8581 #endif
8582 typedef sqlite_int64 i64;          /* 8-byte signed integer */
8583 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
8584 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
8585 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
8586 typedef INT16_TYPE i16;            /* 2-byte signed integer */
8587 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
8588 typedef INT8_TYPE i8;              /* 1-byte signed integer */
8589 
8590 /*
8591 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
8592 ** that can be stored in a u32 without loss of data.  The value
8593 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
8594 ** have to specify the value in the less intuitive manner shown:
8595 */
8596 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
8597 
8598 /*
8599 ** The datatype used to store estimates of the number of rows in a
8600 ** table or index.  This is an unsigned integer type.  For 99.9% of
8601 ** the world, a 32-bit integer is sufficient.  But a 64-bit integer
8602 ** can be used at compile-time if desired.
8603 */
8604 #ifdef SQLITE_64BIT_STATS
8605  typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
8606 #else
8607  typedef u32 tRowcnt;    /* 32-bit is the default */
8608 #endif
8609 
8610 /*
8611 ** Estimated quantities used for query planning are stored as 16-bit
8612 ** logarithms.  For quantity X, the value stored is 10*log2(X).  This
8613 ** gives a possible range of values of approximately 1.0e986 to 1e-986.
8614 ** But the allowed values are "grainy".  Not every value is representable.
8615 ** For example, quantities 16 and 17 are both represented by a LogEst
8616 ** of 40.  However, since LogEst quantaties are suppose to be estimates,
8617 ** not exact values, this imprecision is not a problem.
8618 **
8619 ** "LogEst" is short for "Logarithmic Estimate".
8620 **
8621 ** Examples:
8622 **      1 -> 0              20 -> 43          10000 -> 132
8623 **      2 -> 10             25 -> 46          25000 -> 146
8624 **      3 -> 16            100 -> 66        1000000 -> 199
8625 **      4 -> 20           1000 -> 99        1048576 -> 200
8626 **     10 -> 33           1024 -> 100    4294967296 -> 320
8627 **
8628 ** The LogEst can be negative to indicate fractional values.
8629 ** Examples:
8630 **
8631 **    0.5 -> -10           0.1 -> -33        0.0625 -> -40
8632 */
8633 typedef INT16_TYPE LogEst;
8634 
8635 /*
8636 ** Macros to determine whether the machine is big or little endian,
8637 ** and whether or not that determination is run-time or compile-time.
8638 **
8639 ** For best performance, an attempt is made to guess at the byte-order
8640 ** using C-preprocessor macros.  If that is unsuccessful, or if
8641 ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
8642 ** at run-time.
8643 */
8644 #ifdef SQLITE_AMALGAMATION
8645 SQLITE_PRIVATE const int sqlite3one = 1;
8646 #else
8647 SQLITE_PRIVATE const int sqlite3one;
8648 #endif
8649 #if (defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
8650      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
8651      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
8652      defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER)
8653 # define SQLITE_BYTEORDER    1234
8654 # define SQLITE_BIGENDIAN    0
8655 # define SQLITE_LITTLEENDIAN 1
8656 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
8657 #endif
8658 #if (defined(sparc)    || defined(__ppc__))  \
8659     && !defined(SQLITE_RUNTIME_BYTEORDER)
8660 # define SQLITE_BYTEORDER    4321
8661 # define SQLITE_BIGENDIAN    1
8662 # define SQLITE_LITTLEENDIAN 0
8663 # define SQLITE_UTF16NATIVE  SQLITE_UTF16BE
8664 #endif
8665 #if !defined(SQLITE_BYTEORDER)
8666 # define SQLITE_BYTEORDER    0     /* 0 means "unknown at compile-time" */
8667 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
8668 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
8669 # define SQLITE_UTF16NATIVE  (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
8670 #endif
8671 
8672 /*
8673 ** Constants for the largest and smallest possible 64-bit signed integers.
8674 ** These macros are designed to work correctly on both 32-bit and 64-bit
8675 ** compilers.
8676 */
8677 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
8678 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
8679 
8680 /*
8681 ** Round up a number to the next larger multiple of 8.  This is used
8682 ** to force 8-byte alignment on 64-bit architectures.
8683 */
8684 #define ROUND8(x)     (((x)+7)&~7)
8685 
8686 /*
8687 ** Round down to the nearest multiple of 8
8688 */
8689 #define ROUNDDOWN8(x) ((x)&~7)
8690 
8691 /*
8692 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
8693 ** macro is used only within assert() to verify that the code gets
8694 ** all alignment restrictions correct.
8695 **
8696 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
8697 ** underlying malloc() implementation might return us 4-byte aligned
8698 ** pointers.  In that case, only verify 4-byte alignment.
8699 */
8700 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
8701 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
8702 #else
8703 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
8704 #endif
8705 
8706 /*
8707 ** Disable MMAP on platforms where it is known to not work
8708 */
8709 #if defined(__OpenBSD__) || defined(__QNXNTO__)
8710 # undef SQLITE_MAX_MMAP_SIZE
8711 # define SQLITE_MAX_MMAP_SIZE 0
8712 #endif
8713 
8714 /*
8715 ** Default maximum size of memory used by memory-mapped I/O in the VFS
8716 */
8717 #ifdef __APPLE__
8718 # include <TargetConditionals.h>
8719 # if TARGET_OS_IPHONE
8720 #   undef SQLITE_MAX_MMAP_SIZE
8721 #   define SQLITE_MAX_MMAP_SIZE 0
8722 # endif
8723 #endif
8724 #ifndef SQLITE_MAX_MMAP_SIZE
8725 # if defined(__linux__) \
8726   || defined(_WIN32) \
8727   || (defined(__APPLE__) && defined(__MACH__)) \
8728   || defined(__sun)
8729 #   define SQLITE_MAX_MMAP_SIZE 0x7fff0000  /* 2147418112 */
8730 # else
8731 #   define SQLITE_MAX_MMAP_SIZE 0
8732 # endif
8733 # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
8734 #endif
8735 
8736 /*
8737 ** The default MMAP_SIZE is zero on all platforms.  Or, even if a larger
8738 ** default MMAP_SIZE is specified at compile-time, make sure that it does
8739 ** not exceed the maximum mmap size.
8740 */
8741 #ifndef SQLITE_DEFAULT_MMAP_SIZE
8742 # define SQLITE_DEFAULT_MMAP_SIZE 0
8743 # define SQLITE_DEFAULT_MMAP_SIZE_xc 1  /* Exclude from ctime.c */
8744 #endif
8745 #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
8746 # undef SQLITE_DEFAULT_MMAP_SIZE
8747 # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
8748 #endif
8749 
8750 /*
8751 ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
8752 ** Priority is given to SQLITE_ENABLE_STAT4.  If either are defined, also
8753 ** define SQLITE_ENABLE_STAT3_OR_STAT4
8754 */
8755 #ifdef SQLITE_ENABLE_STAT4
8756 # undef SQLITE_ENABLE_STAT3
8757 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
8758 #elif SQLITE_ENABLE_STAT3
8759 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
8760 #elif SQLITE_ENABLE_STAT3_OR_STAT4
8761 # undef SQLITE_ENABLE_STAT3_OR_STAT4
8762 #endif
8763 
8764 /*
8765 ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
8766 ** the Select query generator tracing logic is turned on.
8767 */
8768 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
8769 # define SELECTTRACE_ENABLED 1
8770 #else
8771 # define SELECTTRACE_ENABLED 0
8772 #endif
8773 
8774 /*
8775 ** An instance of the following structure is used to store the busy-handler
8776 ** callback for a given sqlite handle.
8777 **
8778 ** The sqlite.busyHandler member of the sqlite struct contains the busy
8779 ** callback for the database handle. Each pager opened via the sqlite
8780 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
8781 ** callback is currently invoked only from within pager.c.
8782 */
8783 typedef struct BusyHandler BusyHandler;
8784 struct BusyHandler {
8785   int (*xFunc)(void *,int);  /* The busy callback */
8786   void *pArg;                /* First arg to busy callback */
8787   int nBusy;                 /* Incremented with each busy call */
8788 };
8789 
8790 /*
8791 ** Name of the master database table.  The master database table
8792 ** is a special table that holds the names and attributes of all
8793 ** user tables and indices.
8794 */
8795 #define MASTER_NAME       "sqlite_master"
8796 #define TEMP_MASTER_NAME  "sqlite_temp_master"
8797 
8798 /*
8799 ** The root-page of the master database table.
8800 */
8801 #define MASTER_ROOT       1
8802 
8803 /*
8804 ** The name of the schema table.
8805 */
8806 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
8807 
8808 /*
8809 ** A convenience macro that returns the number of elements in
8810 ** an array.
8811 */
8812 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
8813 
8814 /*
8815 ** Determine if the argument is a power of two
8816 */
8817 #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
8818 
8819 /*
8820 ** The following value as a destructor means to use sqlite3DbFree().
8821 ** The sqlite3DbFree() routine requires two parameters instead of the
8822 ** one parameter that destructors normally want.  So we have to introduce
8823 ** this magic value that the code knows to handle differently.  Any
8824 ** pointer will work here as long as it is distinct from SQLITE_STATIC
8825 ** and SQLITE_TRANSIENT.
8826 */
8827 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
8828 
8829 /*
8830 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
8831 ** not support Writable Static Data (WSD) such as global and static variables.
8832 ** All variables must either be on the stack or dynamically allocated from
8833 ** the heap.  When WSD is unsupported, the variable declarations scattered
8834 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
8835 ** macro is used for this purpose.  And instead of referencing the variable
8836 ** directly, we use its constant as a key to lookup the run-time allocated
8837 ** buffer that holds real variable.  The constant is also the initializer
8838 ** for the run-time allocated buffer.
8839 **
8840 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
8841 ** macros become no-ops and have zero performance impact.
8842 */
8843 #ifdef SQLITE_OMIT_WSD
8844   #define SQLITE_WSD const
8845   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
8846   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
8847 SQLITE_API   int sqlite3_wsd_init(int N, int J);
8848 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
8849 #else
8850   #define SQLITE_WSD
8851   #define GLOBAL(t,v) v
8852   #define sqlite3GlobalConfig sqlite3Config
8853 #endif
8854 
8855 /*
8856 ** The following macros are used to suppress compiler warnings and to
8857 ** make it clear to human readers when a function parameter is deliberately
8858 ** left unused within the body of a function. This usually happens when
8859 ** a function is called via a function pointer. For example the
8860 ** implementation of an SQL aggregate step callback may not use the
8861 ** parameter indicating the number of arguments passed to the aggregate,
8862 ** if it knows that this is enforced elsewhere.
8863 **
8864 ** When a function parameter is not used at all within the body of a function,
8865 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
8866 ** However, these macros may also be used to suppress warnings related to
8867 ** parameters that may or may not be used depending on compilation options.
8868 ** For example those parameters only used in assert() statements. In these
8869 ** cases the parameters are named as per the usual conventions.
8870 */
8871 #define UNUSED_PARAMETER(x) (void)(x)
8872 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
8873 
8874 /*
8875 ** Forward references to structures
8876 */
8877 typedef struct AggInfo AggInfo;
8878 typedef struct AuthContext AuthContext;
8879 typedef struct AutoincInfo AutoincInfo;
8880 typedef struct Bitvec Bitvec;
8881 typedef struct CollSeq CollSeq;
8882 typedef struct Column Column;
8883 typedef struct Db Db;
8884 typedef struct Schema Schema;
8885 typedef struct Expr Expr;
8886 typedef struct ExprList ExprList;
8887 typedef struct ExprSpan ExprSpan;
8888 typedef struct FKey FKey;
8889 typedef struct FuncDestructor FuncDestructor;
8890 typedef struct FuncDef FuncDef;
8891 typedef struct FuncDefHash FuncDefHash;
8892 typedef struct IdList IdList;
8893 typedef struct Index Index;
8894 typedef struct IndexSample IndexSample;
8895 typedef struct KeyClass KeyClass;
8896 typedef struct KeyInfo KeyInfo;
8897 typedef struct Lookaside Lookaside;
8898 typedef struct LookasideSlot LookasideSlot;
8899 typedef struct Module Module;
8900 typedef struct NameContext NameContext;
8901 typedef struct Parse Parse;
8902 typedef struct PrintfArguments PrintfArguments;
8903 typedef struct RowSet RowSet;
8904 typedef struct Savepoint Savepoint;
8905 typedef struct Select Select;
8906 typedef struct SQLiteThread SQLiteThread;
8907 typedef struct SelectDest SelectDest;
8908 typedef struct SrcList SrcList;
8909 typedef struct StrAccum StrAccum;
8910 typedef struct Table Table;
8911 typedef struct TableLock TableLock;
8912 typedef struct Token Token;
8913 typedef struct TreeView TreeView;
8914 typedef struct Trigger Trigger;
8915 typedef struct TriggerPrg TriggerPrg;
8916 typedef struct TriggerStep TriggerStep;
8917 typedef struct UnpackedRecord UnpackedRecord;
8918 typedef struct VTable VTable;
8919 typedef struct VtabCtx VtabCtx;
8920 typedef struct Walker Walker;
8921 typedef struct WhereInfo WhereInfo;
8922 typedef struct With With;
8923 
8924 /*
8925 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
8926 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
8927 ** pointer types (i.e. FuncDef) defined above.
8928 */
8929 /************** Include btree.h in the middle of sqliteInt.h *****************/
8930 /************** Begin file btree.h *******************************************/
8931 /*
8932 ** 2001 September 15
8933 **
8934 ** The author disclaims copyright to this source code.  In place of
8935 ** a legal notice, here is a blessing:
8936 **
8937 **    May you do good and not evil.
8938 **    May you find forgiveness for yourself and forgive others.
8939 **    May you share freely, never taking more than you give.
8940 **
8941 *************************************************************************
8942 ** This header file defines the interface that the sqlite B-Tree file
8943 ** subsystem.  See comments in the source code for a detailed description
8944 ** of what each interface routine does.
8945 */
8946 #ifndef _BTREE_H_
8947 #define _BTREE_H_
8948 
8949 /* TODO: This definition is just included so other modules compile. It
8950 ** needs to be revisited.
8951 */
8952 #define SQLITE_N_BTREE_META 10
8953 
8954 /*
8955 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
8956 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
8957 */
8958 #ifndef SQLITE_DEFAULT_AUTOVACUUM
8959   #define SQLITE_DEFAULT_AUTOVACUUM 0
8960 #endif
8961 
8962 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
8963 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
8964 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
8965 
8966 /*
8967 ** Forward declarations of structure
8968 */
8969 typedef struct Btree Btree;
8970 typedef struct BtCursor BtCursor;
8971 typedef struct BtShared BtShared;
8972 
8973 
8974 SQLITE_PRIVATE int sqlite3BtreeOpen(
8975   sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
8976   const char *zFilename,   /* Name of database file to open */
8977   sqlite3 *db,             /* Associated database connection */
8978   Btree **ppBtree,         /* Return open Btree* here */
8979   int flags,               /* Flags */
8980   int vfsFlags             /* Flags passed through to VFS open */
8981 );
8982 
8983 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
8984 ** following values.
8985 **
8986 ** NOTE:  These values must match the corresponding PAGER_ values in
8987 ** pager.h.
8988 */
8989 #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
8990 #define BTREE_MEMORY        2  /* This is an in-memory DB */
8991 #define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
8992 #define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
8993 
8994 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
8995 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
8996 #if SQLITE_MAX_MMAP_SIZE>0
8997 SQLITE_PRIVATE   int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
8998 #endif
8999 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
9000 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
9001 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
9002 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
9003 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
9004 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
9005 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
9006 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
9007 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
9008 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
9009 #endif
9010 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
9011 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
9012 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
9013 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
9014 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
9015 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
9016 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
9017 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
9018 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
9019 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
9020 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
9021 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
9022 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
9023 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
9024 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
9025 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
9026 
9027 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
9028 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
9029 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
9030 
9031 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
9032 
9033 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
9034 ** of the flags shown below.
9035 **
9036 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
9037 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
9038 ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
9039 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
9040 ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
9041 ** indices.)
9042 */
9043 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
9044 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
9045 
9046 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
9047 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
9048 SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
9049 SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
9050 
9051 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
9052 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
9053 
9054 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
9055 
9056 /*
9057 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
9058 ** should be one of the following values. The integer values are assigned
9059 ** to constants so that the offset of the corresponding field in an
9060 ** SQLite database header may be found using the following formula:
9061 **
9062 **   offset = 36 + (idx * 4)
9063 **
9064 ** For example, the free-page-count field is located at byte offset 36 of
9065 ** the database file header. The incr-vacuum-flag field is located at
9066 ** byte offset 64 (== 36+4*7).
9067 */
9068 #define BTREE_FREE_PAGE_COUNT     0
9069 #define BTREE_SCHEMA_VERSION      1
9070 #define BTREE_FILE_FORMAT         2
9071 #define BTREE_DEFAULT_CACHE_SIZE  3
9072 #define BTREE_LARGEST_ROOT_PAGE   4
9073 #define BTREE_TEXT_ENCODING       5
9074 #define BTREE_USER_VERSION        6
9075 #define BTREE_INCR_VACUUM         7
9076 #define BTREE_APPLICATION_ID      8
9077 
9078 /*
9079 ** Values that may be OR'd together to form the second argument of an
9080 ** sqlite3BtreeCursorHints() call.
9081 */
9082 #define BTREE_BULKLOAD 0x00000001
9083 
9084 SQLITE_PRIVATE int sqlite3BtreeCursor(
9085   Btree*,                              /* BTree containing table to open */
9086   int iTable,                          /* Index of root page */
9087   int wrFlag,                          /* 1 for writing.  0 for read-only */
9088   struct KeyInfo*,                     /* First argument to compare function */
9089   BtCursor *pCursor                    /* Space to write cursor structure */
9090 );
9091 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
9092 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
9093 
9094 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
9095 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
9096   BtCursor*,
9097   UnpackedRecord *pUnKey,
9098   i64 intKey,
9099   int bias,
9100   int *pRes
9101 );
9102 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
9103 SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
9104 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
9105 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
9106                                   const void *pData, int nData,
9107                                   int nZero, int bias, int seekResult);
9108 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
9109 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
9110 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
9111 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
9112 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
9113 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
9114 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
9115 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, u32 *pAmt);
9116 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, u32 *pAmt);
9117 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
9118 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
9119 
9120 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
9121 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
9122 
9123 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
9124 SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
9125 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
9126 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
9127 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
9128 SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
9129 
9130 #ifndef NDEBUG
9131 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
9132 #endif
9133 
9134 #ifndef SQLITE_OMIT_BTREECOUNT
9135 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
9136 #endif
9137 
9138 #ifdef SQLITE_TEST
9139 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
9140 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
9141 #endif
9142 
9143 #ifndef SQLITE_OMIT_WAL
9144 SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
9145 #endif
9146 
9147 /*
9148 ** If we are not using shared cache, then there is no need to
9149 ** use mutexes to access the BtShared structures.  So make the
9150 ** Enter and Leave procedures no-ops.
9151 */
9152 #ifndef SQLITE_OMIT_SHARED_CACHE
9153 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
9154 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
9155 #else
9156 # define sqlite3BtreeEnter(X)
9157 # define sqlite3BtreeEnterAll(X)
9158 #endif
9159 
9160 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
9161 SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
9162 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
9163 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
9164 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
9165 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
9166 #ifndef NDEBUG
9167   /* These routines are used inside assert() statements only. */
9168 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
9169 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
9170 SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
9171 #endif
9172 #else
9173 
9174 # define sqlite3BtreeSharable(X) 0
9175 # define sqlite3BtreeLeave(X)
9176 # define sqlite3BtreeEnterCursor(X)
9177 # define sqlite3BtreeLeaveCursor(X)
9178 # define sqlite3BtreeLeaveAll(X)
9179 
9180 # define sqlite3BtreeHoldsMutex(X) 1
9181 # define sqlite3BtreeHoldsAllMutexes(X) 1
9182 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
9183 #endif
9184 
9185 
9186 #endif /* _BTREE_H_ */
9187 
9188 /************** End of btree.h ***********************************************/
9189 /************** Continuing where we left off in sqliteInt.h ******************/
9190 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
9191 /************** Begin file vdbe.h ********************************************/
9192 /*
9193 ** 2001 September 15
9194 **
9195 ** The author disclaims copyright to this source code.  In place of
9196 ** a legal notice, here is a blessing:
9197 **
9198 **    May you do good and not evil.
9199 **    May you find forgiveness for yourself and forgive others.
9200 **    May you share freely, never taking more than you give.
9201 **
9202 *************************************************************************
9203 ** Header file for the Virtual DataBase Engine (VDBE)
9204 **
9205 ** This header defines the interface to the virtual database engine
9206 ** or VDBE.  The VDBE implements an abstract machine that runs a
9207 ** simple program to access and modify the underlying database.
9208 */
9209 #ifndef _SQLITE_VDBE_H_
9210 #define _SQLITE_VDBE_H_
9211 /* #include <stdio.h> */
9212 
9213 /*
9214 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
9215 ** in the source file sqliteVdbe.c are allowed to see the insides
9216 ** of this structure.
9217 */
9218 typedef struct Vdbe Vdbe;
9219 
9220 /*
9221 ** The names of the following types declared in vdbeInt.h are required
9222 ** for the VdbeOp definition.
9223 */
9224 typedef struct Mem Mem;
9225 typedef struct SubProgram SubProgram;
9226 
9227 /*
9228 ** A single instruction of the virtual machine has an opcode
9229 ** and as many as three operands.  The instruction is recorded
9230 ** as an instance of the following structure:
9231 */
9232 struct VdbeOp {
9233   u8 opcode;          /* What operation to perform */
9234   signed char p4type; /* One of the P4_xxx constants for p4 */
9235   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
9236   u8 p5;              /* Fifth parameter is an unsigned character */
9237   int p1;             /* First operand */
9238   int p2;             /* Second parameter (often the jump destination) */
9239   int p3;             /* The third parameter */
9240   union {             /* fourth parameter */
9241     int i;                 /* Integer value if p4type==P4_INT32 */
9242     void *p;               /* Generic pointer */
9243     char *z;               /* Pointer to data for string (char array) types */
9244     i64 *pI64;             /* Used when p4type is P4_INT64 */
9245     double *pReal;         /* Used when p4type is P4_REAL */
9246     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
9247     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
9248     Mem *pMem;             /* Used when p4type is P4_MEM */
9249     VTable *pVtab;         /* Used when p4type is P4_VTAB */
9250     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
9251     int *ai;               /* Used when p4type is P4_INTARRAY */
9252     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
9253     int (*xAdvance)(BtCursor *, int *);
9254   } p4;
9255 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
9256   char *zComment;          /* Comment to improve readability */
9257 #endif
9258 #ifdef VDBE_PROFILE
9259   u32 cnt;                 /* Number of times this instruction was executed */
9260   u64 cycles;              /* Total time spent executing this instruction */
9261 #endif
9262 #ifdef SQLITE_VDBE_COVERAGE
9263   int iSrcLine;            /* Source-code line that generated this opcode */
9264 #endif
9265 };
9266 typedef struct VdbeOp VdbeOp;
9267 
9268 
9269 /*
9270 ** A sub-routine used to implement a trigger program.
9271 */
9272 struct SubProgram {
9273   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
9274   int nOp;                      /* Elements in aOp[] */
9275   int nMem;                     /* Number of memory cells required */
9276   int nCsr;                     /* Number of cursors required */
9277   int nOnce;                    /* Number of OP_Once instructions */
9278   void *token;                  /* id that may be used to recursive triggers */
9279   SubProgram *pNext;            /* Next sub-program already visited */
9280 };
9281 
9282 /*
9283 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
9284 ** it takes up less space.
9285 */
9286 struct VdbeOpList {
9287   u8 opcode;          /* What operation to perform */
9288   signed char p1;     /* First operand */
9289   signed char p2;     /* Second parameter (often the jump destination) */
9290   signed char p3;     /* Third parameter */
9291 };
9292 typedef struct VdbeOpList VdbeOpList;
9293 
9294 /*
9295 ** Allowed values of VdbeOp.p4type
9296 */
9297 #define P4_NOTUSED    0   /* The P4 parameter is not used */
9298 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
9299 #define P4_STATIC   (-2)  /* Pointer to a static string */
9300 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
9301 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
9302 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
9303 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
9304 #define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
9305 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
9306 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
9307 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
9308 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
9309 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
9310 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
9311 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
9312 #define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
9313 
9314 /* Error message codes for OP_Halt */
9315 #define P5_ConstraintNotNull 1
9316 #define P5_ConstraintUnique  2
9317 #define P5_ConstraintCheck   3
9318 #define P5_ConstraintFK      4
9319 
9320 /*
9321 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
9322 ** number of columns of data returned by the statement.
9323 */
9324 #define COLNAME_NAME     0
9325 #define COLNAME_DECLTYPE 1
9326 #define COLNAME_DATABASE 2
9327 #define COLNAME_TABLE    3
9328 #define COLNAME_COLUMN   4
9329 #ifdef SQLITE_ENABLE_COLUMN_METADATA
9330 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
9331 #else
9332 # ifdef SQLITE_OMIT_DECLTYPE
9333 #   define COLNAME_N      1      /* Store only the name */
9334 # else
9335 #   define COLNAME_N      2      /* Store the name and decltype */
9336 # endif
9337 #endif
9338 
9339 /*
9340 ** The following macro converts a relative address in the p2 field
9341 ** of a VdbeOp structure into a negative number so that
9342 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
9343 ** the macro again restores the address.
9344 */
9345 #define ADDR(X)  (-1-(X))
9346 
9347 /*
9348 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
9349 ** header file that defines a number for each opcode used by the VDBE.
9350 */
9351 /************** Include opcodes.h in the middle of vdbe.h ********************/
9352 /************** Begin file opcodes.h *****************************************/
9353 /* Automatically generated.  Do not edit */
9354 /* See the mkopcodeh.awk script for details */
9355 #define OP_Function        1 /* synopsis: r[P3]=func(r[P2@P5])             */
9356 #define OP_Savepoint       2
9357 #define OP_AutoCommit      3
9358 #define OP_Transaction     4
9359 #define OP_SorterNext      5
9360 #define OP_PrevIfOpen      6
9361 #define OP_NextIfOpen      7
9362 #define OP_Prev            8
9363 #define OP_Next            9
9364 #define OP_AggStep        10 /* synopsis: accum=r[P3] step(r[P2@P5])       */
9365 #define OP_Checkpoint     11
9366 #define OP_JournalMode    12
9367 #define OP_Vacuum         13
9368 #define OP_VFilter        14 /* synopsis: iplan=r[P3] zplan='P4'           */
9369 #define OP_VUpdate        15 /* synopsis: data=r[P3@P2]                    */
9370 #define OP_Goto           16
9371 #define OP_Gosub          17
9372 #define OP_Return         18
9373 #define OP_Not            19 /* same as TK_NOT, synopsis: r[P2]= !r[P1]    */
9374 #define OP_InitCoroutine  20
9375 #define OP_EndCoroutine   21
9376 #define OP_Yield          22
9377 #define OP_HaltIfNull     23 /* synopsis: if r[P3]=null halt               */
9378 #define OP_Halt           24
9379 #define OP_Integer        25 /* synopsis: r[P2]=P1                         */
9380 #define OP_Int64          26 /* synopsis: r[P2]=P4                         */
9381 #define OP_String         27 /* synopsis: r[P2]='P4' (len=P1)              */
9382 #define OP_Null           28 /* synopsis: r[P2..P3]=NULL                   */
9383 #define OP_SoftNull       29 /* synopsis: r[P1]=NULL                       */
9384 #define OP_Blob           30 /* synopsis: r[P2]=P4 (len=P1)                */
9385 #define OP_Variable       31 /* synopsis: r[P2]=parameter(P1,P4)           */
9386 #define OP_Move           32 /* synopsis: r[P2@P3]=r[P1@P3]                */
9387 #define OP_Copy           33 /* synopsis: r[P2@P3+1]=r[P1@P3+1]            */
9388 #define OP_SCopy          34 /* synopsis: r[P2]=r[P1]                      */
9389 #define OP_ResultRow      35 /* synopsis: output=r[P1@P2]                  */
9390 #define OP_CollSeq        36
9391 #define OP_AddImm         37 /* synopsis: r[P1]=r[P1]+P2                   */
9392 #define OP_MustBeInt      38
9393 #define OP_RealAffinity   39
9394 #define OP_Cast           40 /* synopsis: affinity(r[P1])                  */
9395 #define OP_Permutation    41
9396 #define OP_Compare        42 /* synopsis: r[P1@P3] <-> r[P2@P3]            */
9397 #define OP_Jump           43
9398 #define OP_Once           44
9399 #define OP_If             45
9400 #define OP_IfNot          46
9401 #define OP_Column         47 /* synopsis: r[P3]=PX                         */
9402 #define OP_Affinity       48 /* synopsis: affinity(r[P1@P2])               */
9403 #define OP_MakeRecord     49 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
9404 #define OP_Count          50 /* synopsis: r[P2]=count()                    */
9405 #define OP_ReadCookie     51
9406 #define OP_SetCookie      52
9407 #define OP_ReopenIdx      53 /* synopsis: root=P2 iDb=P3                   */
9408 #define OP_OpenRead       54 /* synopsis: root=P2 iDb=P3                   */
9409 #define OP_OpenWrite      55 /* synopsis: root=P2 iDb=P3                   */
9410 #define OP_OpenAutoindex  56 /* synopsis: nColumn=P2                       */
9411 #define OP_OpenEphemeral  57 /* synopsis: nColumn=P2                       */
9412 #define OP_SorterOpen     58
9413 #define OP_SequenceTest   59 /* synopsis: if( cursor[P1].ctr++ ) pc = P2   */
9414 #define OP_OpenPseudo     60 /* synopsis: P3 columns in r[P2]              */
9415 #define OP_Close          61
9416 #define OP_SeekLT         62 /* synopsis: key=r[P3@P4]                     */
9417 #define OP_SeekLE         63 /* synopsis: key=r[P3@P4]                     */
9418 #define OP_SeekGE         64 /* synopsis: key=r[P3@P4]                     */
9419 #define OP_SeekGT         65 /* synopsis: key=r[P3@P4]                     */
9420 #define OP_Seek           66 /* synopsis: intkey=r[P2]                     */
9421 #define OP_NoConflict     67 /* synopsis: key=r[P3@P4]                     */
9422 #define OP_NotFound       68 /* synopsis: key=r[P3@P4]                     */
9423 #define OP_Found          69 /* synopsis: key=r[P3@P4]                     */
9424 #define OP_NotExists      70 /* synopsis: intkey=r[P3]                     */
9425 #define OP_Or             71 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
9426 #define OP_And            72 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
9427 #define OP_Sequence       73 /* synopsis: r[P2]=cursor[P1].ctr++           */
9428 #define OP_NewRowid       74 /* synopsis: r[P2]=rowid                      */
9429 #define OP_Insert         75 /* synopsis: intkey=r[P3] data=r[P2]          */
9430 #define OP_IsNull         76 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
9431 #define OP_NotNull        77 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
9432 #define OP_Ne             78 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
9433 #define OP_Eq             79 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
9434 #define OP_Gt             80 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
9435 #define OP_Le             81 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
9436 #define OP_Lt             82 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
9437 #define OP_Ge             83 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
9438 #define OP_InsertInt      84 /* synopsis: intkey=P3 data=r[P2]             */
9439 #define OP_BitAnd         85 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
9440 #define OP_BitOr          86 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
9441 #define OP_ShiftLeft      87 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
9442 #define OP_ShiftRight     88 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
9443 #define OP_Add            89 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
9444 #define OP_Subtract       90 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
9445 #define OP_Multiply       91 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
9446 #define OP_Divide         92 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
9447 #define OP_Remainder      93 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
9448 #define OP_Concat         94 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
9449 #define OP_Delete         95
9450 #define OP_BitNot         96 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
9451 #define OP_String8        97 /* same as TK_STRING, synopsis: r[P2]='P4'    */
9452 #define OP_ResetCount     98
9453 #define OP_SorterCompare  99 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
9454 #define OP_SorterData    100 /* synopsis: r[P2]=data                       */
9455 #define OP_RowKey        101 /* synopsis: r[P2]=key                        */
9456 #define OP_RowData       102 /* synopsis: r[P2]=data                       */
9457 #define OP_Rowid         103 /* synopsis: r[P2]=rowid                      */
9458 #define OP_NullRow       104
9459 #define OP_Last          105
9460 #define OP_SorterSort    106
9461 #define OP_Sort          107
9462 #define OP_Rewind        108
9463 #define OP_SorterInsert  109
9464 #define OP_IdxInsert     110 /* synopsis: key=r[P2]                        */
9465 #define OP_IdxDelete     111 /* synopsis: key=r[P2@P3]                     */
9466 #define OP_IdxRowid      112 /* synopsis: r[P2]=rowid                      */
9467 #define OP_IdxLE         113 /* synopsis: key=r[P3@P4]                     */
9468 #define OP_IdxGT         114 /* synopsis: key=r[P3@P4]                     */
9469 #define OP_IdxLT         115 /* synopsis: key=r[P3@P4]                     */
9470 #define OP_IdxGE         116 /* synopsis: key=r[P3@P4]                     */
9471 #define OP_Destroy       117
9472 #define OP_Clear         118
9473 #define OP_ResetSorter   119
9474 #define OP_CreateIndex   120 /* synopsis: r[P2]=root iDb=P1                */
9475 #define OP_CreateTable   121 /* synopsis: r[P2]=root iDb=P1                */
9476 #define OP_ParseSchema   122
9477 #define OP_LoadAnalysis  123
9478 #define OP_DropTable     124
9479 #define OP_DropIndex     125
9480 #define OP_DropTrigger   126
9481 #define OP_IntegrityCk   127
9482 #define OP_RowSetAdd     128 /* synopsis: rowset(P1)=r[P2]                 */
9483 #define OP_RowSetRead    129 /* synopsis: r[P3]=rowset(P1)                 */
9484 #define OP_RowSetTest    130 /* synopsis: if r[P3] in rowset(P1) goto P2   */
9485 #define OP_Program       131
9486 #define OP_Param         132
9487 #define OP_Real          133 /* same as TK_FLOAT, synopsis: r[P2]=P4       */
9488 #define OP_FkCounter     134 /* synopsis: fkctr[P1]+=P2                    */
9489 #define OP_FkIfZero      135 /* synopsis: if fkctr[P1]==0 goto P2          */
9490 #define OP_MemMax        136 /* synopsis: r[P1]=max(r[P1],r[P2])           */
9491 #define OP_IfPos         137 /* synopsis: if r[P1]>0 goto P2               */
9492 #define OP_IfNeg         138 /* synopsis: r[P1]+=P3, if r[P1]<0 goto P2    */
9493 #define OP_IfZero        139 /* synopsis: r[P1]+=P3, if r[P1]==0 goto P2   */
9494 #define OP_AggFinal      140 /* synopsis: accum=r[P1] N=P2                 */
9495 #define OP_IncrVacuum    141
9496 #define OP_Expire        142
9497 #define OP_TableLock     143 /* synopsis: iDb=P1 root=P2 write=P3          */
9498 #define OP_VBegin        144
9499 #define OP_VCreate       145
9500 #define OP_VDestroy      146
9501 #define OP_VOpen         147
9502 #define OP_VColumn       148 /* synopsis: r[P3]=vcolumn(P2)                */
9503 #define OP_VNext         149
9504 #define OP_VRename       150
9505 #define OP_Pagecount     151
9506 #define OP_MaxPgcnt      152
9507 #define OP_Init          153 /* synopsis: Start at P2                      */
9508 #define OP_Noop          154
9509 #define OP_Explain       155
9510 
9511 
9512 /* Properties such as "out2" or "jump" that are specified in
9513 ** comments following the "case" for each opcode in the vdbe.c
9514 ** are encoded into bitvectors as follows:
9515 */
9516 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
9517 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
9518 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
9519 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
9520 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
9521 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
9522 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
9523 #define OPFLG_INITIALIZER {\
9524 /*   0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01,\
9525 /*   8 */ 0x01, 0x01, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00,\
9526 /*  16 */ 0x01, 0x01, 0x04, 0x24, 0x01, 0x04, 0x05, 0x10,\
9527 /*  24 */ 0x00, 0x02, 0x02, 0x02, 0x02, 0x00, 0x02, 0x02,\
9528 /*  32 */ 0x00, 0x00, 0x20, 0x00, 0x00, 0x04, 0x05, 0x04,\
9529 /*  40 */ 0x04, 0x00, 0x00, 0x01, 0x01, 0x05, 0x05, 0x00,\
9530 /*  48 */ 0x00, 0x00, 0x02, 0x02, 0x10, 0x00, 0x00, 0x00,\
9531 /*  56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\
9532 /*  64 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x4c,\
9533 /*  72 */ 0x4c, 0x02, 0x02, 0x00, 0x05, 0x05, 0x15, 0x15,\
9534 /*  80 */ 0x15, 0x15, 0x15, 0x15, 0x00, 0x4c, 0x4c, 0x4c,\
9535 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x00,\
9536 /*  96 */ 0x24, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,\
9537 /* 104 */ 0x00, 0x01, 0x01, 0x01, 0x01, 0x08, 0x08, 0x00,\
9538 /* 112 */ 0x02, 0x01, 0x01, 0x01, 0x01, 0x02, 0x00, 0x00,\
9539 /* 120 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
9540 /* 128 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x02, 0x00, 0x01,\
9541 /* 136 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x01, 0x00, 0x00,\
9542 /* 144 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02,\
9543 /* 152 */ 0x02, 0x01, 0x00, 0x00,}
9544 
9545 /************** End of opcodes.h *********************************************/
9546 /************** Continuing where we left off in vdbe.h ***********************/
9547 
9548 /*
9549 ** Prototypes for the VDBE interface.  See comments on the implementation
9550 ** for a description of what each of these routines does.
9551 */
9552 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
9553 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
9554 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
9555 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
9556 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
9557 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
9558 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
9559 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
9560 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
9561 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
9562 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
9563 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
9564 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
9565 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
9566 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
9567 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
9568 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
9569 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
9570 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
9571 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
9572 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
9573 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
9574 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
9575 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
9576 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
9577 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
9578 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
9579 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
9580 #ifdef SQLITE_DEBUG
9581 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
9582 #endif
9583 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
9584 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
9585 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
9586 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
9587 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
9588 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
9589 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
9590 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
9591 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
9592 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
9593 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
9594 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
9595 #ifndef SQLITE_OMIT_TRACE
9596 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
9597 #endif
9598 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
9599 
9600 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
9601 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
9602 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
9603 
9604 typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
9605 SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
9606 
9607 #ifndef SQLITE_OMIT_TRIGGER
9608 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
9609 #endif
9610 
9611 /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
9612 ** each VDBE opcode.
9613 **
9614 ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
9615 ** comments in VDBE programs that show key decision points in the code
9616 ** generator.
9617 */
9618 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
9619 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
9620 # define VdbeComment(X)  sqlite3VdbeComment X
9621 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
9622 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
9623 # ifdef SQLITE_ENABLE_MODULE_COMMENTS
9624 #   define VdbeModuleComment(X)  sqlite3VdbeNoopComment X
9625 # else
9626 #   define VdbeModuleComment(X)
9627 # endif
9628 #else
9629 # define VdbeComment(X)
9630 # define VdbeNoopComment(X)
9631 # define VdbeModuleComment(X)
9632 #endif
9633 
9634 /*
9635 ** The VdbeCoverage macros are used to set a coverage testing point
9636 ** for VDBE branch instructions.  The coverage testing points are line
9637 ** numbers in the sqlite3.c source file.  VDBE branch coverage testing
9638 ** only works with an amalagmation build.  That's ok since a VDBE branch
9639 ** coverage build designed for testing the test suite only.  No application
9640 ** should ever ship with VDBE branch coverage measuring turned on.
9641 **
9642 **    VdbeCoverage(v)                  // Mark the previously coded instruction
9643 **                                     // as a branch
9644 **
9645 **    VdbeCoverageIf(v, conditional)   // Mark previous if conditional true
9646 **
9647 **    VdbeCoverageAlwaysTaken(v)       // Previous branch is always taken
9648 **
9649 **    VdbeCoverageNeverTaken(v)        // Previous branch is never taken
9650 **
9651 ** Every VDBE branch operation must be tagged with one of the macros above.
9652 ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
9653 ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
9654 ** routine in vdbe.c, alerting the developer to the missed tag.
9655 */
9656 #ifdef SQLITE_VDBE_COVERAGE
9657 SQLITE_PRIVATE   void sqlite3VdbeSetLineNumber(Vdbe*,int);
9658 # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
9659 # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
9660 # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
9661 # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
9662 # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
9663 #else
9664 # define VdbeCoverage(v)
9665 # define VdbeCoverageIf(v,x)
9666 # define VdbeCoverageAlwaysTaken(v)
9667 # define VdbeCoverageNeverTaken(v)
9668 # define VDBE_OFFSET_LINENO(x) 0
9669 #endif
9670 
9671 #endif
9672 
9673 /************** End of vdbe.h ************************************************/
9674 /************** Continuing where we left off in sqliteInt.h ******************/
9675 /************** Include pager.h in the middle of sqliteInt.h *****************/
9676 /************** Begin file pager.h *******************************************/
9677 /*
9678 ** 2001 September 15
9679 **
9680 ** The author disclaims copyright to this source code.  In place of
9681 ** a legal notice, here is a blessing:
9682 **
9683 **    May you do good and not evil.
9684 **    May you find forgiveness for yourself and forgive others.
9685 **    May you share freely, never taking more than you give.
9686 **
9687 *************************************************************************
9688 ** This header file defines the interface that the sqlite page cache
9689 ** subsystem.  The page cache subsystem reads and writes a file a page
9690 ** at a time and provides a journal for rollback.
9691 */
9692 
9693 #ifndef _PAGER_H_
9694 #define _PAGER_H_
9695 
9696 /*
9697 ** Default maximum size for persistent journal files. A negative
9698 ** value means no limit. This value may be overridden using the
9699 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
9700 */
9701 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
9702   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
9703 #endif
9704 
9705 /*
9706 ** The type used to represent a page number.  The first page in a file
9707 ** is called page 1.  0 is used to represent "not a page".
9708 */
9709 typedef u32 Pgno;
9710 
9711 /*
9712 ** Each open file is managed by a separate instance of the "Pager" structure.
9713 */
9714 typedef struct Pager Pager;
9715 
9716 /*
9717 ** Handle type for pages.
9718 */
9719 typedef struct PgHdr DbPage;
9720 
9721 /*
9722 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
9723 ** reserved for working around a windows/posix incompatibility). It is
9724 ** used in the journal to signify that the remainder of the journal file
9725 ** is devoted to storing a master journal name - there are no more pages to
9726 ** roll back. See comments for function writeMasterJournal() in pager.c
9727 ** for details.
9728 */
9729 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
9730 
9731 /*
9732 ** Allowed values for the flags parameter to sqlite3PagerOpen().
9733 **
9734 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
9735 */
9736 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
9737 #define PAGER_MEMORY        0x0002    /* In-memory database */
9738 
9739 /*
9740 ** Valid values for the second argument to sqlite3PagerLockingMode().
9741 */
9742 #define PAGER_LOCKINGMODE_QUERY      -1
9743 #define PAGER_LOCKINGMODE_NORMAL      0
9744 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
9745 
9746 /*
9747 ** Numeric constants that encode the journalmode.
9748 */
9749 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
9750 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
9751 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
9752 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
9753 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
9754 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
9755 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
9756 
9757 /*
9758 ** Flags that make up the mask passed to sqlite3PagerAcquire().
9759 */
9760 #define PAGER_GET_NOCONTENT     0x01  /* Do not load data from disk */
9761 #define PAGER_GET_READONLY      0x02  /* Read-only page is acceptable */
9762 
9763 /*
9764 ** Flags for sqlite3PagerSetFlags()
9765 */
9766 #define PAGER_SYNCHRONOUS_OFF       0x01  /* PRAGMA synchronous=OFF */
9767 #define PAGER_SYNCHRONOUS_NORMAL    0x02  /* PRAGMA synchronous=NORMAL */
9768 #define PAGER_SYNCHRONOUS_FULL      0x03  /* PRAGMA synchronous=FULL */
9769 #define PAGER_SYNCHRONOUS_MASK      0x03  /* Mask for three values above */
9770 #define PAGER_FULLFSYNC             0x04  /* PRAGMA fullfsync=ON */
9771 #define PAGER_CKPT_FULLFSYNC        0x08  /* PRAGMA checkpoint_fullfsync=ON */
9772 #define PAGER_CACHESPILL            0x10  /* PRAGMA cache_spill=ON */
9773 #define PAGER_FLAGS_MASK            0x1c  /* All above except SYNCHRONOUS */
9774 
9775 /*
9776 ** The remainder of this file contains the declarations of the functions
9777 ** that make up the Pager sub-system API. See source code comments for
9778 ** a detailed description of each routine.
9779 */
9780 
9781 /* Open and close a Pager connection. */
9782 SQLITE_PRIVATE int sqlite3PagerOpen(
9783   sqlite3_vfs*,
9784   Pager **ppPager,
9785   const char*,
9786   int,
9787   int,
9788   int,
9789   void(*)(DbPage*)
9790 );
9791 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
9792 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
9793 
9794 /* Functions used to configure a Pager object. */
9795 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
9796 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
9797 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
9798 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
9799 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
9800 SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
9801 SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
9802 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
9803 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
9804 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
9805 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
9806 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
9807 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
9808 
9809 /* Functions used to obtain and release page references. */
9810 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
9811 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
9812 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
9813 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
9814 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
9815 SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
9816 
9817 /* Operations on page references. */
9818 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
9819 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
9820 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
9821 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
9822 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
9823 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
9824 
9825 /* Functions used to manage pager transactions and savepoints. */
9826 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
9827 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
9828 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
9829 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
9830 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
9831 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
9832 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
9833 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
9834 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
9835 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
9836 
9837 #ifndef SQLITE_OMIT_WAL
9838 SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
9839 SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
9840 SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
9841 SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
9842 SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager);
9843 #endif
9844 
9845 #ifdef SQLITE_ENABLE_ZIPVFS
9846 SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
9847 #endif
9848 
9849 /* Functions used to query pager state and configuration. */
9850 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
9851 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
9852 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
9853 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
9854 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
9855 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
9856 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
9857 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
9858 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
9859 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
9860 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
9861 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
9862 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
9863 
9864 /* Functions used to truncate the database file. */
9865 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
9866 
9867 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
9868 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
9869 #endif
9870 
9871 /* Functions to support testing and debugging. */
9872 #if !defined(NDEBUG) || defined(SQLITE_TEST)
9873 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
9874 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
9875 #endif
9876 #ifdef SQLITE_TEST
9877 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
9878 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
9879   void disable_simulated_io_errors(void);
9880   void enable_simulated_io_errors(void);
9881 #else
9882 # define disable_simulated_io_errors()
9883 # define enable_simulated_io_errors()
9884 #endif
9885 
9886 #endif /* _PAGER_H_ */
9887 
9888 /************** End of pager.h ***********************************************/
9889 /************** Continuing where we left off in sqliteInt.h ******************/
9890 /************** Include pcache.h in the middle of sqliteInt.h ****************/
9891 /************** Begin file pcache.h ******************************************/
9892 /*
9893 ** 2008 August 05
9894 **
9895 ** The author disclaims copyright to this source code.  In place of
9896 ** a legal notice, here is a blessing:
9897 **
9898 **    May you do good and not evil.
9899 **    May you find forgiveness for yourself and forgive others.
9900 **    May you share freely, never taking more than you give.
9901 **
9902 *************************************************************************
9903 ** This header file defines the interface that the sqlite page cache
9904 ** subsystem.
9905 */
9906 
9907 #ifndef _PCACHE_H_
9908 
9909 typedef struct PgHdr PgHdr;
9910 typedef struct PCache PCache;
9911 
9912 /*
9913 ** Every page in the cache is controlled by an instance of the following
9914 ** structure.
9915 */
9916 struct PgHdr {
9917   sqlite3_pcache_page *pPage;    /* Pcache object page handle */
9918   void *pData;                   /* Page data */
9919   void *pExtra;                  /* Extra content */
9920   PgHdr *pDirty;                 /* Transient list of dirty pages */
9921   Pager *pPager;                 /* The pager this page is part of */
9922   Pgno pgno;                     /* Page number for this page */
9923 #ifdef SQLITE_CHECK_PAGES
9924   u32 pageHash;                  /* Hash of page content */
9925 #endif
9926   u16 flags;                     /* PGHDR flags defined below */
9927 
9928   /**********************************************************************
9929   ** Elements above are public.  All that follows is private to pcache.c
9930   ** and should not be accessed by other modules.
9931   */
9932   i16 nRef;                      /* Number of users of this page */
9933   PCache *pCache;                /* Cache that owns this page */
9934 
9935   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
9936   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
9937 };
9938 
9939 /* Bit values for PgHdr.flags */
9940 #define PGHDR_DIRTY             0x002  /* Page has changed */
9941 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
9942                                        ** writing this page to the database */
9943 #define PGHDR_NEED_READ         0x008  /* Content is unread */
9944 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
9945 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
9946 
9947 #define PGHDR_MMAP              0x040  /* This is an mmap page object */
9948 
9949 /* Initialize and shutdown the page cache subsystem */
9950 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
9951 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
9952 
9953 /* Page cache buffer management:
9954 ** These routines implement SQLITE_CONFIG_PAGECACHE.
9955 */
9956 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
9957 
9958 /* Create a new pager cache.
9959 ** Under memory stress, invoke xStress to try to make pages clean.
9960 ** Only clean and unpinned pages can be reclaimed.
9961 */
9962 SQLITE_PRIVATE int sqlite3PcacheOpen(
9963   int szPage,                    /* Size of every page */
9964   int szExtra,                   /* Extra space associated with each page */
9965   int bPurgeable,                /* True if pages are on backing store */
9966   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
9967   void *pStress,                 /* Argument to xStress */
9968   PCache *pToInit                /* Preallocated space for the PCache */
9969 );
9970 
9971 /* Modify the page-size after the cache has been created. */
9972 SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
9973 
9974 /* Return the size in bytes of a PCache object.  Used to preallocate
9975 ** storage space.
9976 */
9977 SQLITE_PRIVATE int sqlite3PcacheSize(void);
9978 
9979 /* One release per successful fetch.  Page is pinned until released.
9980 ** Reference counted.
9981 */
9982 SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
9983 SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
9984 SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
9985 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
9986 
9987 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
9988 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
9989 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
9990 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
9991 
9992 /* Change a page number.  Used by incr-vacuum. */
9993 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
9994 
9995 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
9996 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
9997 
9998 /* Get a list of all dirty pages in the cache, sorted by page number */
9999 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
10000 
10001 /* Reset and close the cache object */
10002 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
10003 
10004 /* Clear flags from pages of the page cache */
10005 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
10006 
10007 /* Discard the contents of the cache */
10008 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
10009 
10010 /* Return the total number of outstanding page references */
10011 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
10012 
10013 /* Increment the reference count of an existing page */
10014 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
10015 
10016 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
10017 
10018 /* Return the total number of pages stored in the cache */
10019 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
10020 
10021 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
10022 /* Iterate through all dirty pages currently stored in the cache. This
10023 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
10024 ** library is built.
10025 */
10026 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
10027 #endif
10028 
10029 /* Set and get the suggested cache-size for the specified pager-cache.
10030 **
10031 ** If no global maximum is configured, then the system attempts to limit
10032 ** the total number of pages cached by purgeable pager-caches to the sum
10033 ** of the suggested cache-sizes.
10034 */
10035 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
10036 #ifdef SQLITE_TEST
10037 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
10038 #endif
10039 
10040 /* Free up as much memory as possible from the page cache */
10041 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
10042 
10043 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
10044 /* Try to return memory used by the pcache module to the main memory heap */
10045 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
10046 #endif
10047 
10048 #ifdef SQLITE_TEST
10049 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
10050 #endif
10051 
10052 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
10053 
10054 #endif /* _PCACHE_H_ */
10055 
10056 /************** End of pcache.h **********************************************/
10057 /************** Continuing where we left off in sqliteInt.h ******************/
10058 
10059 /************** Include os.h in the middle of sqliteInt.h ********************/
10060 /************** Begin file os.h **********************************************/
10061 /*
10062 ** 2001 September 16
10063 **
10064 ** The author disclaims copyright to this source code.  In place of
10065 ** a legal notice, here is a blessing:
10066 **
10067 **    May you do good and not evil.
10068 **    May you find forgiveness for yourself and forgive others.
10069 **    May you share freely, never taking more than you give.
10070 **
10071 ******************************************************************************
10072 **
10073 ** This header file (together with is companion C source-code file
10074 ** "os.c") attempt to abstract the underlying operating system so that
10075 ** the SQLite library will work on both POSIX and windows systems.
10076 **
10077 ** This header file is #include-ed by sqliteInt.h and thus ends up
10078 ** being included by every source file.
10079 */
10080 #ifndef _SQLITE_OS_H_
10081 #define _SQLITE_OS_H_
10082 
10083 /*
10084 ** Attempt to automatically detect the operating system and setup the
10085 ** necessary pre-processor macros for it.
10086 */
10087 /************** Include os_setup.h in the middle of os.h *********************/
10088 /************** Begin file os_setup.h ****************************************/
10089 /*
10090 ** 2013 November 25
10091 **
10092 ** The author disclaims copyright to this source code.  In place of
10093 ** a legal notice, here is a blessing:
10094 **
10095 **    May you do good and not evil.
10096 **    May you find forgiveness for yourself and forgive others.
10097 **    May you share freely, never taking more than you give.
10098 **
10099 ******************************************************************************
10100 **
10101 ** This file contains pre-processor directives related to operating system
10102 ** detection and/or setup.
10103 */
10104 #ifndef _OS_SETUP_H_
10105 #define _OS_SETUP_H_
10106 
10107 /*
10108 ** Figure out if we are dealing with Unix, Windows, or some other operating
10109 ** system.
10110 **
10111 ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
10112 ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0.  One of
10113 ** the three will be 1.  The other two will be 0.
10114 */
10115 #if defined(SQLITE_OS_OTHER)
10116 #  if SQLITE_OS_OTHER==1
10117 #    undef SQLITE_OS_UNIX
10118 #    define SQLITE_OS_UNIX 0
10119 #    undef SQLITE_OS_WIN
10120 #    define SQLITE_OS_WIN 0
10121 #  else
10122 #    undef SQLITE_OS_OTHER
10123 #  endif
10124 #endif
10125 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
10126 #  define SQLITE_OS_OTHER 0
10127 #  ifndef SQLITE_OS_WIN
10128 #    if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
10129         defined(__MINGW32__) || defined(__BORLANDC__)
10130 #      define SQLITE_OS_WIN 1
10131 #      define SQLITE_OS_UNIX 0
10132 #    else
10133 #      define SQLITE_OS_WIN 0
10134 #      define SQLITE_OS_UNIX 1
10135 #    endif
10136 #  else
10137 #    define SQLITE_OS_UNIX 0
10138 #  endif
10139 #else
10140 #  ifndef SQLITE_OS_WIN
10141 #    define SQLITE_OS_WIN 0
10142 #  endif
10143 #endif
10144 
10145 #endif /* _OS_SETUP_H_ */
10146 
10147 /************** End of os_setup.h ********************************************/
10148 /************** Continuing where we left off in os.h *************************/
10149 
10150 /* If the SET_FULLSYNC macro is not defined above, then make it
10151 ** a no-op
10152 */
10153 #ifndef SET_FULLSYNC
10154 # define SET_FULLSYNC(x,y)
10155 #endif
10156 
10157 /*
10158 ** The default size of a disk sector
10159 */
10160 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
10161 # define SQLITE_DEFAULT_SECTOR_SIZE 4096
10162 #endif
10163 
10164 /*
10165 ** Temporary files are named starting with this prefix followed by 16 random
10166 ** alphanumeric characters, and no file extension. They are stored in the
10167 ** OS's standard temporary file directory, and are deleted prior to exit.
10168 ** If sqlite is being embedded in another program, you may wish to change the
10169 ** prefix to reflect your program's name, so that if your program exits
10170 ** prematurely, old temporary files can be easily identified. This can be done
10171 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
10172 **
10173 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
10174 ** Mcafee started using SQLite in their anti-virus product and it
10175 ** started putting files with the "sqlite" name in the c:/temp folder.
10176 ** This annoyed many windows users.  Those users would then do a
10177 ** Google search for "sqlite", find the telephone numbers of the
10178 ** developers and call to wake them up at night and complain.
10179 ** For this reason, the default name prefix is changed to be "sqlite"
10180 ** spelled backwards.  So the temp files are still identified, but
10181 ** anybody smart enough to figure out the code is also likely smart
10182 ** enough to know that calling the developer will not help get rid
10183 ** of the file.
10184 */
10185 #ifndef SQLITE_TEMP_FILE_PREFIX
10186 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
10187 #endif
10188 
10189 /*
10190 ** The following values may be passed as the second argument to
10191 ** sqlite3OsLock(). The various locks exhibit the following semantics:
10192 **
10193 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
10194 ** RESERVED:  A single process may hold a RESERVED lock on a file at
10195 **            any time. Other processes may hold and obtain new SHARED locks.
10196 ** PENDING:   A single process may hold a PENDING lock on a file at
10197 **            any one time. Existing SHARED locks may persist, but no new
10198 **            SHARED locks may be obtained by other processes.
10199 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
10200 **
10201 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
10202 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
10203 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
10204 ** sqlite3OsLock().
10205 */
10206 #define NO_LOCK         0
10207 #define SHARED_LOCK     1
10208 #define RESERVED_LOCK   2
10209 #define PENDING_LOCK    3
10210 #define EXCLUSIVE_LOCK  4
10211 
10212 /*
10213 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
10214 **
10215 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
10216 ** those functions are not available.  So we use only LockFile() and
10217 ** UnlockFile().
10218 **
10219 ** LockFile() prevents not just writing but also reading by other processes.
10220 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
10221 ** byte out of a specific range of bytes. The lock byte is obtained at
10222 ** random so two separate readers can probably access the file at the
10223 ** same time, unless they are unlucky and choose the same lock byte.
10224 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
10225 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
10226 ** a single byte of the file that is designated as the reserved lock byte.
10227 ** A PENDING_LOCK is obtained by locking a designated byte different from
10228 ** the RESERVED_LOCK byte.
10229 **
10230 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
10231 ** which means we can use reader/writer locks.  When reader/writer locks
10232 ** are used, the lock is placed on the same range of bytes that is used
10233 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
10234 ** will support two or more Win95 readers or two or more WinNT readers.
10235 ** But a single Win95 reader will lock out all WinNT readers and a single
10236 ** WinNT reader will lock out all other Win95 readers.
10237 **
10238 ** The following #defines specify the range of bytes used for locking.
10239 ** SHARED_SIZE is the number of bytes available in the pool from which
10240 ** a random byte is selected for a shared lock.  The pool of bytes for
10241 ** shared locks begins at SHARED_FIRST.
10242 **
10243 ** The same locking strategy and
10244 ** byte ranges are used for Unix.  This leaves open the possibility of having
10245 ** clients on win95, winNT, and unix all talking to the same shared file
10246 ** and all locking correctly.  To do so would require that samba (or whatever
10247 ** tool is being used for file sharing) implements locks correctly between
10248 ** windows and unix.  I'm guessing that isn't likely to happen, but by
10249 ** using the same locking range we are at least open to the possibility.
10250 **
10251 ** Locking in windows is manditory.  For this reason, we cannot store
10252 ** actual data in the bytes used for locking.  The pager never allocates
10253 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
10254 ** that all locks will fit on a single page even at the minimum page size.
10255 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
10256 ** is set high so that we don't have to allocate an unused page except
10257 ** for very large databases.  But one should test the page skipping logic
10258 ** by setting PENDING_BYTE low and running the entire regression suite.
10259 **
10260 ** Changing the value of PENDING_BYTE results in a subtly incompatible
10261 ** file format.  Depending on how it is changed, you might not notice
10262 ** the incompatibility right away, even running a full regression test.
10263 ** The default location of PENDING_BYTE is the first byte past the
10264 ** 1GB boundary.
10265 **
10266 */
10267 #ifdef SQLITE_OMIT_WSD
10268 # define PENDING_BYTE     (0x40000000)
10269 #else
10270 # define PENDING_BYTE      sqlite3PendingByte
10271 #endif
10272 #define RESERVED_BYTE     (PENDING_BYTE+1)
10273 #define SHARED_FIRST      (PENDING_BYTE+2)
10274 #define SHARED_SIZE       510
10275 
10276 /*
10277 ** Wrapper around OS specific sqlite3_os_init() function.
10278 */
10279 SQLITE_PRIVATE int sqlite3OsInit(void);
10280 
10281 /*
10282 ** Functions for accessing sqlite3_file methods
10283 */
10284 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
10285 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
10286 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
10287 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
10288 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
10289 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
10290 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
10291 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
10292 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
10293 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
10294 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
10295 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
10296 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
10297 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
10298 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
10299 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
10300 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
10301 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
10302 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
10303 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
10304 
10305 
10306 /*
10307 ** Functions for accessing sqlite3_vfs methods
10308 */
10309 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
10310 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
10311 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
10312 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
10313 #ifndef SQLITE_OMIT_LOAD_EXTENSION
10314 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
10315 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
10316 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
10317 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
10318 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
10319 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
10320 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
10321 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
10322 
10323 /*
10324 ** Convenience functions for opening and closing files using
10325 ** sqlite3_malloc() to obtain space for the file-handle structure.
10326 */
10327 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
10328 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
10329 
10330 #endif /* _SQLITE_OS_H_ */
10331 
10332 /************** End of os.h **************************************************/
10333 /************** Continuing where we left off in sqliteInt.h ******************/
10334 /************** Include mutex.h in the middle of sqliteInt.h *****************/
10335 /************** Begin file mutex.h *******************************************/
10336 /*
10337 ** 2007 August 28
10338 **
10339 ** The author disclaims copyright to this source code.  In place of
10340 ** a legal notice, here is a blessing:
10341 **
10342 **    May you do good and not evil.
10343 **    May you find forgiveness for yourself and forgive others.
10344 **    May you share freely, never taking more than you give.
10345 **
10346 *************************************************************************
10347 **
10348 ** This file contains the common header for all mutex implementations.
10349 ** The sqliteInt.h header #includes this file so that it is available
10350 ** to all source files.  We break it out in an effort to keep the code
10351 ** better organized.
10352 **
10353 ** NOTE:  source files should *not* #include this header file directly.
10354 ** Source files should #include the sqliteInt.h file and let that file
10355 ** include this one indirectly.
10356 */
10357 
10358 
10359 /*
10360 ** Figure out what version of the code to use.  The choices are
10361 **
10362 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
10363 **                             mutexes implementation cannot be overridden
10364 **                             at start-time.
10365 **
10366 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
10367 **                             mutual exclusion is provided.  But this
10368 **                             implementation can be overridden at
10369 **                             start-time.
10370 **
10371 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
10372 **
10373 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
10374 */
10375 #if !SQLITE_THREADSAFE
10376 # define SQLITE_MUTEX_OMIT
10377 #endif
10378 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
10379 #  if SQLITE_OS_UNIX
10380 #    define SQLITE_MUTEX_PTHREADS
10381 #  elif SQLITE_OS_WIN
10382 #    define SQLITE_MUTEX_W32
10383 #  else
10384 #    define SQLITE_MUTEX_NOOP
10385 #  endif
10386 #endif
10387 
10388 #ifdef SQLITE_MUTEX_OMIT
10389 /*
10390 ** If this is a no-op implementation, implement everything as macros.
10391 */
10392 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
10393 #define sqlite3_mutex_free(X)
10394 #define sqlite3_mutex_enter(X)
10395 #define sqlite3_mutex_try(X)      SQLITE_OK
10396 #define sqlite3_mutex_leave(X)
10397 #define sqlite3_mutex_held(X)     ((void)(X),1)
10398 #define sqlite3_mutex_notheld(X)  ((void)(X),1)
10399 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
10400 #define sqlite3MutexInit()        SQLITE_OK
10401 #define sqlite3MutexEnd()
10402 #define MUTEX_LOGIC(X)
10403 #else
10404 #define MUTEX_LOGIC(X)            X
10405 #endif /* defined(SQLITE_MUTEX_OMIT) */
10406 
10407 /************** End of mutex.h ***********************************************/
10408 /************** Continuing where we left off in sqliteInt.h ******************/
10409 
10410 
10411 /*
10412 ** Each database file to be accessed by the system is an instance
10413 ** of the following structure.  There are normally two of these structures
10414 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
10415 ** aDb[1] is the database file used to hold temporary tables.  Additional
10416 ** databases may be attached.
10417 */
10418 struct Db {
10419   char *zName;         /* Name of this database */
10420   Btree *pBt;          /* The B*Tree structure for this database file */
10421   u8 safety_level;     /* How aggressive at syncing data to disk */
10422   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
10423 };
10424 
10425 /*
10426 ** An instance of the following structure stores a database schema.
10427 **
10428 ** Most Schema objects are associated with a Btree.  The exception is
10429 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
10430 ** In shared cache mode, a single Schema object can be shared by multiple
10431 ** Btrees that refer to the same underlying BtShared object.
10432 **
10433 ** Schema objects are automatically deallocated when the last Btree that
10434 ** references them is destroyed.   The TEMP Schema is manually freed by
10435 ** sqlite3_close().
10436 *
10437 ** A thread must be holding a mutex on the corresponding Btree in order
10438 ** to access Schema content.  This implies that the thread must also be
10439 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
10440 ** For a TEMP Schema, only the connection mutex is required.
10441 */
10442 struct Schema {
10443   int schema_cookie;   /* Database schema version number for this file */
10444   int iGeneration;     /* Generation counter.  Incremented with each change */
10445   Hash tblHash;        /* All tables indexed by name */
10446   Hash idxHash;        /* All (named) indices indexed by name */
10447   Hash trigHash;       /* All triggers indexed by name */
10448   Hash fkeyHash;       /* All foreign keys by referenced table name */
10449   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
10450   u8 file_format;      /* Schema format version for this file */
10451   u8 enc;              /* Text encoding used by this database */
10452   u16 schemaFlags;     /* Flags associated with this schema */
10453   int cache_size;      /* Number of pages to use in the cache */
10454 };
10455 
10456 /*
10457 ** These macros can be used to test, set, or clear bits in the
10458 ** Db.pSchema->flags field.
10459 */
10460 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
10461 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
10462 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->schemaFlags|=(P)
10463 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->schemaFlags&=~(P)
10464 
10465 /*
10466 ** Allowed values for the DB.pSchema->flags field.
10467 **
10468 ** The DB_SchemaLoaded flag is set after the database schema has been
10469 ** read into internal hash tables.
10470 **
10471 ** DB_UnresetViews means that one or more views have column names that
10472 ** have been filled out.  If the schema changes, these column names might
10473 ** changes and so the view will need to be reset.
10474 */
10475 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
10476 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
10477 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
10478 
10479 /*
10480 ** The number of different kinds of things that can be limited
10481 ** using the sqlite3_limit() interface.
10482 */
10483 #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
10484 
10485 /*
10486 ** Lookaside malloc is a set of fixed-size buffers that can be used
10487 ** to satisfy small transient memory allocation requests for objects
10488 ** associated with a particular database connection.  The use of
10489 ** lookaside malloc provides a significant performance enhancement
10490 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
10491 ** SQL statements.
10492 **
10493 ** The Lookaside structure holds configuration information about the
10494 ** lookaside malloc subsystem.  Each available memory allocation in
10495 ** the lookaside subsystem is stored on a linked list of LookasideSlot
10496 ** objects.
10497 **
10498 ** Lookaside allocations are only allowed for objects that are associated
10499 ** with a particular database connection.  Hence, schema information cannot
10500 ** be stored in lookaside because in shared cache mode the schema information
10501 ** is shared by multiple database connections.  Therefore, while parsing
10502 ** schema information, the Lookaside.bEnabled flag is cleared so that
10503 ** lookaside allocations are not used to construct the schema objects.
10504 */
10505 struct Lookaside {
10506   u16 sz;                 /* Size of each buffer in bytes */
10507   u8 bEnabled;            /* False to disable new lookaside allocations */
10508   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
10509   int nOut;               /* Number of buffers currently checked out */
10510   int mxOut;              /* Highwater mark for nOut */
10511   int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
10512   LookasideSlot *pFree;   /* List of available buffers */
10513   void *pStart;           /* First byte of available memory space */
10514   void *pEnd;             /* First byte past end of available space */
10515 };
10516 struct LookasideSlot {
10517   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
10518 };
10519 
10520 /*
10521 ** A hash table for function definitions.
10522 **
10523 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
10524 ** Collisions are on the FuncDef.pHash chain.
10525 */
10526 struct FuncDefHash {
10527   FuncDef *a[23];       /* Hash table for functions */
10528 };
10529 
10530 #ifdef SQLITE_USER_AUTHENTICATION
10531 /*
10532 ** Information held in the "sqlite3" database connection object and used
10533 ** to manage user authentication.
10534 */
10535 typedef struct sqlite3_userauth sqlite3_userauth;
10536 struct sqlite3_userauth {
10537   u8 authLevel;                 /* Current authentication level */
10538   int nAuthPW;                  /* Size of the zAuthPW in bytes */
10539   char *zAuthPW;                /* Password used to authenticate */
10540   char *zAuthUser;              /* User name used to authenticate */
10541 };
10542 
10543 /* Allowed values for sqlite3_userauth.authLevel */
10544 #define UAUTH_Unknown     0     /* Authentication not yet checked */
10545 #define UAUTH_Fail        1     /* User authentication failed */
10546 #define UAUTH_User        2     /* Authenticated as a normal user */
10547 #define UAUTH_Admin       3     /* Authenticated as an administrator */
10548 
10549 /* Functions used only by user authorization logic */
10550 SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
10551 SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
10552 SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
10553 SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
10554 
10555 #endif /* SQLITE_USER_AUTHENTICATION */
10556 
10557 /*
10558 ** typedef for the authorization callback function.
10559 */
10560 #ifdef SQLITE_USER_AUTHENTICATION
10561   typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
10562                                const char*, const char*);
10563 #else
10564   typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
10565                                const char*);
10566 #endif
10567 
10568 
10569 /*
10570 ** Each database connection is an instance of the following structure.
10571 */
10572 struct sqlite3 {
10573   sqlite3_vfs *pVfs;            /* OS Interface */
10574   struct Vdbe *pVdbe;           /* List of active virtual machines */
10575   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
10576   sqlite3_mutex *mutex;         /* Connection mutex */
10577   Db *aDb;                      /* All backends */
10578   int nDb;                      /* Number of backends currently in use */
10579   int flags;                    /* Miscellaneous flags. See below */
10580   i64 lastRowid;                /* ROWID of most recent insert (see above) */
10581   i64 szMmap;                   /* Default mmap_size setting */
10582   unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
10583   int errCode;                  /* Most recent error code (SQLITE_*) */
10584   int errMask;                  /* & result codes with this before returning */
10585   u16 dbOptFlags;               /* Flags to enable/disable optimizations */
10586   u8 autoCommit;                /* The auto-commit flag. */
10587   u8 temp_store;                /* 1: file 2: memory 0: default */
10588   u8 mallocFailed;              /* True if we have seen a malloc failure */
10589   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
10590   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
10591   u8 suppressErr;               /* Do not issue error messages if true */
10592   u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
10593   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
10594   int nextPagesize;             /* Pagesize after VACUUM if >0 */
10595   u32 magic;                    /* Magic number for detect library misuse */
10596   int nChange;                  /* Value returned by sqlite3_changes() */
10597   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
10598   int aLimit[SQLITE_N_LIMIT];   /* Limits */
10599   int nMaxSorterMmap;           /* Maximum size of regions mapped by sorter */
10600   struct sqlite3InitInfo {      /* Information used during initialization */
10601     int newTnum;                /* Rootpage of table being initialized */
10602     u8 iDb;                     /* Which db file is being initialized */
10603     u8 busy;                    /* TRUE if currently initializing */
10604     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
10605   } init;
10606   int nVdbeActive;              /* Number of VDBEs currently running */
10607   int nVdbeRead;                /* Number of active VDBEs that read or write */
10608   int nVdbeWrite;               /* Number of active VDBEs that read and write */
10609   int nVdbeExec;                /* Number of nested calls to VdbeExec() */
10610   int nExtension;               /* Number of loaded extensions */
10611   void **aExtension;            /* Array of shared library handles */
10612   void (*xTrace)(void*,const char*);        /* Trace function */
10613   void *pTraceArg;                          /* Argument to the trace function */
10614   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
10615   void *pProfileArg;                        /* Argument to profile function */
10616   void *pCommitArg;                 /* Argument to xCommitCallback() */
10617   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
10618   void *pRollbackArg;               /* Argument to xRollbackCallback() */
10619   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
10620   void *pUpdateArg;
10621   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
10622 #ifndef SQLITE_OMIT_WAL
10623   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
10624   void *pWalArg;
10625 #endif
10626   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
10627   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
10628   void *pCollNeededArg;
10629   sqlite3_value *pErr;          /* Most recent error message */
10630   union {
10631     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
10632     double notUsed1;            /* Spacer */
10633   } u1;
10634   Lookaside lookaside;          /* Lookaside malloc configuration */
10635 #ifndef SQLITE_OMIT_AUTHORIZATION
10636   sqlite3_xauth xAuth;          /* Access authorization function */
10637   void *pAuthArg;               /* 1st argument to the access auth function */
10638 #endif
10639 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
10640   int (*xProgress)(void *);     /* The progress callback */
10641   void *pProgressArg;           /* Argument to the progress callback */
10642   unsigned nProgressOps;        /* Number of opcodes for progress callback */
10643 #endif
10644 #ifndef SQLITE_OMIT_VIRTUALTABLE
10645   int nVTrans;                  /* Allocated size of aVTrans */
10646   Hash aModule;                 /* populated by sqlite3_create_module() */
10647   VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
10648   VTable **aVTrans;             /* Virtual tables with open transactions */
10649   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
10650 #endif
10651   FuncDefHash aFunc;            /* Hash table of connection functions */
10652   Hash aCollSeq;                /* All collating sequences */
10653   BusyHandler busyHandler;      /* Busy callback */
10654   Db aDbStatic[2];              /* Static space for the 2 default backends */
10655   Savepoint *pSavepoint;        /* List of active savepoints */
10656   int busyTimeout;              /* Busy handler timeout, in msec */
10657   int nSavepoint;               /* Number of non-transaction savepoints */
10658   int nStatement;               /* Number of nested statement-transactions  */
10659   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
10660   i64 nDeferredImmCons;         /* Net deferred immediate constraints */
10661   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
10662 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
10663   /* The following variables are all protected by the STATIC_MASTER
10664   ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
10665   **
10666   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
10667   ** unlock so that it can proceed.
10668   **
10669   ** When X.pBlockingConnection==Y, that means that something that X tried
10670   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
10671   ** held by Y.
10672   */
10673   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
10674   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
10675   void *pUnlockArg;                     /* Argument to xUnlockNotify */
10676   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
10677   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
10678 #endif
10679 #ifdef SQLITE_USER_AUTHENTICATION
10680   sqlite3_userauth auth;        /* User authentication information */
10681 #endif
10682 };
10683 
10684 /*
10685 ** A macro to discover the encoding of a database.
10686 */
10687 #define ENC(db) ((db)->aDb[0].pSchema->enc)
10688 
10689 /*
10690 ** Possible values for the sqlite3.flags.
10691 */
10692 #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
10693 #define SQLITE_InternChanges  0x00000002  /* Uncommitted Hash table changes */
10694 #define SQLITE_FullFSync      0x00000004  /* Use full fsync on the backend */
10695 #define SQLITE_CkptFullFSync  0x00000008  /* Use full fsync for checkpoint */
10696 #define SQLITE_CacheSpill     0x00000010  /* OK to spill pager cache */
10697 #define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
10698 #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
10699 #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
10700                                           /*   DELETE, or UPDATE and return */
10701                                           /*   the count using a callback. */
10702 #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
10703                                           /*   result set is empty */
10704 #define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
10705 #define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
10706 #define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
10707 #define SQLITE_VdbeAddopTrace 0x00001000  /* Trace sqlite3VdbeAddOp() calls */
10708 #define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
10709 #define SQLITE_ReadUncommitted 0x0004000  /* For shared-cache mode */
10710 #define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
10711 #define SQLITE_RecoveryMode   0x00010000  /* Ignore schema errors */
10712 #define SQLITE_ReverseOrder   0x00020000  /* Reverse unordered SELECTs */
10713 #define SQLITE_RecTriggers    0x00040000  /* Enable recursive triggers */
10714 #define SQLITE_ForeignKeys    0x00080000  /* Enforce foreign key constraints  */
10715 #define SQLITE_AutoIndex      0x00100000  /* Enable automatic indexes */
10716 #define SQLITE_PreferBuiltin  0x00200000  /* Preference to built-in funcs */
10717 #define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
10718 #define SQLITE_EnableTrigger  0x00800000  /* True to enable triggers */
10719 #define SQLITE_DeferFKs       0x01000000  /* Defer all FK constraints */
10720 #define SQLITE_QueryOnly      0x02000000  /* Disable database changes */
10721 #define SQLITE_VdbeEQP        0x04000000  /* Debug EXPLAIN QUERY PLAN */
10722 
10723 
10724 /*
10725 ** Bits of the sqlite3.dbOptFlags field that are used by the
10726 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
10727 ** selectively disable various optimizations.
10728 */
10729 #define SQLITE_QueryFlattener 0x0001   /* Query flattening */
10730 #define SQLITE_ColumnCache    0x0002   /* Column cache */
10731 #define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */
10732 #define SQLITE_FactorOutConst 0x0008   /* Constant factoring */
10733 /*                not used    0x0010   // Was: SQLITE_IdxRealAsInt */
10734 #define SQLITE_DistinctOpt    0x0020   /* DISTINCT using indexes */
10735 #define SQLITE_CoverIdxScan   0x0040   /* Covering index scans */
10736 #define SQLITE_OrderByIdxJoin 0x0080   /* ORDER BY of joins via index */
10737 #define SQLITE_SubqCoroutine  0x0100   /* Evaluate subqueries as coroutines */
10738 #define SQLITE_Transitive     0x0200   /* Transitive constraints */
10739 #define SQLITE_OmitNoopJoin   0x0400   /* Omit unused tables in joins */
10740 #define SQLITE_Stat3          0x0800   /* Use the SQLITE_STAT3 table */
10741 #define SQLITE_AllOpts        0xffff   /* All optimizations */
10742 
10743 /*
10744 ** Macros for testing whether or not optimizations are enabled or disabled.
10745 */
10746 #ifndef SQLITE_OMIT_BUILTIN_TEST
10747 #define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
10748 #define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
10749 #else
10750 #define OptimizationDisabled(db, mask)  0
10751 #define OptimizationEnabled(db, mask)   1
10752 #endif
10753 
10754 /*
10755 ** Return true if it OK to factor constant expressions into the initialization
10756 ** code. The argument is a Parse object for the code generator.
10757 */
10758 #define ConstFactorOk(P) ((P)->okConstFactor)
10759 
10760 /*
10761 ** Possible values for the sqlite.magic field.
10762 ** The numbers are obtained at random and have no special meaning, other
10763 ** than being distinct from one another.
10764 */
10765 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
10766 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
10767 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
10768 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
10769 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
10770 #define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
10771 
10772 /*
10773 ** Each SQL function is defined by an instance of the following
10774 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
10775 ** hash table.  When multiple functions have the same name, the hash table
10776 ** points to a linked list of these structures.
10777 */
10778 struct FuncDef {
10779   i16 nArg;            /* Number of arguments.  -1 means unlimited */
10780   u16 funcFlags;       /* Some combination of SQLITE_FUNC_* */
10781   void *pUserData;     /* User data parameter */
10782   FuncDef *pNext;      /* Next function with same name */
10783   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
10784   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
10785   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
10786   char *zName;         /* SQL name of the function. */
10787   FuncDef *pHash;      /* Next with a different name but the same hash */
10788   FuncDestructor *pDestructor;   /* Reference counted destructor function */
10789 };
10790 
10791 /*
10792 ** This structure encapsulates a user-function destructor callback (as
10793 ** configured using create_function_v2()) and a reference counter. When
10794 ** create_function_v2() is called to create a function with a destructor,
10795 ** a single object of this type is allocated. FuncDestructor.nRef is set to
10796 ** the number of FuncDef objects created (either 1 or 3, depending on whether
10797 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
10798 ** member of each of the new FuncDef objects is set to point to the allocated
10799 ** FuncDestructor.
10800 **
10801 ** Thereafter, when one of the FuncDef objects is deleted, the reference
10802 ** count on this object is decremented. When it reaches 0, the destructor
10803 ** is invoked and the FuncDestructor structure freed.
10804 */
10805 struct FuncDestructor {
10806   int nRef;
10807   void (*xDestroy)(void *);
10808   void *pUserData;
10809 };
10810 
10811 /*
10812 ** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
10813 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  There
10814 ** are assert() statements in the code to verify this.
10815 */
10816 #define SQLITE_FUNC_ENCMASK  0x003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
10817 #define SQLITE_FUNC_LIKE     0x004 /* Candidate for the LIKE optimization */
10818 #define SQLITE_FUNC_CASE     0x008 /* Case-sensitive LIKE-type function */
10819 #define SQLITE_FUNC_EPHEM    0x010 /* Ephemeral.  Delete with VDBE */
10820 #define SQLITE_FUNC_NEEDCOLL 0x020 /* sqlite3GetFuncCollSeq() might be called */
10821 #define SQLITE_FUNC_LENGTH   0x040 /* Built-in length() function */
10822 #define SQLITE_FUNC_TYPEOF   0x080 /* Built-in typeof() function */
10823 #define SQLITE_FUNC_COUNT    0x100 /* Built-in count(*) aggregate */
10824 #define SQLITE_FUNC_COALESCE 0x200 /* Built-in coalesce() or ifnull() */
10825 #define SQLITE_FUNC_UNLIKELY 0x400 /* Built-in unlikely() function */
10826 #define SQLITE_FUNC_CONSTANT 0x800 /* Constant inputs give a constant output */
10827 #define SQLITE_FUNC_MINMAX  0x1000 /* True for min() and max() aggregates */
10828 
10829 /*
10830 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
10831 ** used to create the initializers for the FuncDef structures.
10832 **
10833 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
10834 **     Used to create a scalar function definition of a function zName
10835 **     implemented by C function xFunc that accepts nArg arguments. The
10836 **     value passed as iArg is cast to a (void*) and made available
10837 **     as the user-data (sqlite3_user_data()) for the function. If
10838 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
10839 **
10840 **   VFUNCTION(zName, nArg, iArg, bNC, xFunc)
10841 **     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
10842 **
10843 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
10844 **     Used to create an aggregate function definition implemented by
10845 **     the C functions xStep and xFinal. The first four parameters
10846 **     are interpreted in the same way as the first 4 parameters to
10847 **     FUNCTION().
10848 **
10849 **   LIKEFUNC(zName, nArg, pArg, flags)
10850 **     Used to create a scalar function definition of a function zName
10851 **     that accepts nArg arguments and is implemented by a call to C
10852 **     function likeFunc. Argument pArg is cast to a (void *) and made
10853 **     available as the function user-data (sqlite3_user_data()). The
10854 **     FuncDef.flags variable is set to the value passed as the flags
10855 **     parameter.
10856 */
10857 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
10858   {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
10859    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10860 #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
10861   {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
10862    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10863 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
10864   {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
10865    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10866 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
10867   {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
10868    pArg, 0, xFunc, 0, 0, #zName, 0, 0}
10869 #define LIKEFUNC(zName, nArg, arg, flags) \
10870   {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
10871    (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
10872 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
10873   {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
10874    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
10875 #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
10876   {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
10877    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
10878 
10879 /*
10880 ** All current savepoints are stored in a linked list starting at
10881 ** sqlite3.pSavepoint. The first element in the list is the most recently
10882 ** opened savepoint. Savepoints are added to the list by the vdbe
10883 ** OP_Savepoint instruction.
10884 */
10885 struct Savepoint {
10886   char *zName;                        /* Savepoint name (nul-terminated) */
10887   i64 nDeferredCons;                  /* Number of deferred fk violations */
10888   i64 nDeferredImmCons;               /* Number of deferred imm fk. */
10889   Savepoint *pNext;                   /* Parent savepoint (if any) */
10890 };
10891 
10892 /*
10893 ** The following are used as the second parameter to sqlite3Savepoint(),
10894 ** and as the P1 argument to the OP_Savepoint instruction.
10895 */
10896 #define SAVEPOINT_BEGIN      0
10897 #define SAVEPOINT_RELEASE    1
10898 #define SAVEPOINT_ROLLBACK   2
10899 
10900 
10901 /*
10902 ** Each SQLite module (virtual table definition) is defined by an
10903 ** instance of the following structure, stored in the sqlite3.aModule
10904 ** hash table.
10905 */
10906 struct Module {
10907   const sqlite3_module *pModule;       /* Callback pointers */
10908   const char *zName;                   /* Name passed to create_module() */
10909   void *pAux;                          /* pAux passed to create_module() */
10910   void (*xDestroy)(void *);            /* Module destructor function */
10911 };
10912 
10913 /*
10914 ** information about each column of an SQL table is held in an instance
10915 ** of this structure.
10916 */
10917 struct Column {
10918   char *zName;     /* Name of this column */
10919   Expr *pDflt;     /* Default value of this column */
10920   char *zDflt;     /* Original text of the default value */
10921   char *zType;     /* Data type for this column */
10922   char *zColl;     /* Collating sequence.  If NULL, use the default */
10923   u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
10924   char affinity;   /* One of the SQLITE_AFF_... values */
10925   u8 szEst;        /* Estimated size of this column.  INT==1 */
10926   u8 colFlags;     /* Boolean properties.  See COLFLAG_ defines below */
10927 };
10928 
10929 /* Allowed values for Column.colFlags:
10930 */
10931 #define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
10932 #define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
10933 
10934 /*
10935 ** A "Collating Sequence" is defined by an instance of the following
10936 ** structure. Conceptually, a collating sequence consists of a name and
10937 ** a comparison routine that defines the order of that sequence.
10938 **
10939 ** If CollSeq.xCmp is NULL, it means that the
10940 ** collating sequence is undefined.  Indices built on an undefined
10941 ** collating sequence may not be read or written.
10942 */
10943 struct CollSeq {
10944   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
10945   u8 enc;               /* Text encoding handled by xCmp() */
10946   void *pUser;          /* First argument to xCmp() */
10947   int (*xCmp)(void*,int, const void*, int, const void*);
10948   void (*xDel)(void*);  /* Destructor for pUser */
10949 };
10950 
10951 /*
10952 ** A sort order can be either ASC or DESC.
10953 */
10954 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
10955 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
10956 
10957 /*
10958 ** Column affinity types.
10959 **
10960 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
10961 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
10962 ** the speed a little by numbering the values consecutively.
10963 **
10964 ** But rather than start with 0 or 1, we begin with 'A'.  That way,
10965 ** when multiple affinity types are concatenated into a string and
10966 ** used as the P4 operand, they will be more readable.
10967 **
10968 ** Note also that the numeric types are grouped together so that testing
10969 ** for a numeric type is a single comparison.  And the NONE type is first.
10970 */
10971 #define SQLITE_AFF_NONE     'A'
10972 #define SQLITE_AFF_TEXT     'B'
10973 #define SQLITE_AFF_NUMERIC  'C'
10974 #define SQLITE_AFF_INTEGER  'D'
10975 #define SQLITE_AFF_REAL     'E'
10976 
10977 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
10978 
10979 /*
10980 ** The SQLITE_AFF_MASK values masks off the significant bits of an
10981 ** affinity value.
10982 */
10983 #define SQLITE_AFF_MASK     0x47
10984 
10985 /*
10986 ** Additional bit values that can be ORed with an affinity without
10987 ** changing the affinity.
10988 **
10989 ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
10990 ** It causes an assert() to fire if either operand to a comparison
10991 ** operator is NULL.  It is added to certain comparison operators to
10992 ** prove that the operands are always NOT NULL.
10993 */
10994 #define SQLITE_JUMPIFNULL   0x10  /* jumps if either operand is NULL */
10995 #define SQLITE_STOREP2      0x20  /* Store result in reg[P2] rather than jump */
10996 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
10997 #define SQLITE_NOTNULL      0x90  /* Assert that operands are never NULL */
10998 
10999 /*
11000 ** An object of this type is created for each virtual table present in
11001 ** the database schema.
11002 **
11003 ** If the database schema is shared, then there is one instance of this
11004 ** structure for each database connection (sqlite3*) that uses the shared
11005 ** schema. This is because each database connection requires its own unique
11006 ** instance of the sqlite3_vtab* handle used to access the virtual table
11007 ** implementation. sqlite3_vtab* handles can not be shared between
11008 ** database connections, even when the rest of the in-memory database
11009 ** schema is shared, as the implementation often stores the database
11010 ** connection handle passed to it via the xConnect() or xCreate() method
11011 ** during initialization internally. This database connection handle may
11012 ** then be used by the virtual table implementation to access real tables
11013 ** within the database. So that they appear as part of the callers
11014 ** transaction, these accesses need to be made via the same database
11015 ** connection as that used to execute SQL operations on the virtual table.
11016 **
11017 ** All VTable objects that correspond to a single table in a shared
11018 ** database schema are initially stored in a linked-list pointed to by
11019 ** the Table.pVTable member variable of the corresponding Table object.
11020 ** When an sqlite3_prepare() operation is required to access the virtual
11021 ** table, it searches the list for the VTable that corresponds to the
11022 ** database connection doing the preparing so as to use the correct
11023 ** sqlite3_vtab* handle in the compiled query.
11024 **
11025 ** When an in-memory Table object is deleted (for example when the
11026 ** schema is being reloaded for some reason), the VTable objects are not
11027 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
11028 ** immediately. Instead, they are moved from the Table.pVTable list to
11029 ** another linked list headed by the sqlite3.pDisconnect member of the
11030 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
11031 ** next time a statement is prepared using said sqlite3*. This is done
11032 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
11033 ** Refer to comments above function sqlite3VtabUnlockList() for an
11034 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
11035 ** list without holding the corresponding sqlite3.mutex mutex.
11036 **
11037 ** The memory for objects of this type is always allocated by
11038 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
11039 ** the first argument.
11040 */
11041 struct VTable {
11042   sqlite3 *db;              /* Database connection associated with this table */
11043   Module *pMod;             /* Pointer to module implementation */
11044   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
11045   int nRef;                 /* Number of pointers to this structure */
11046   u8 bConstraint;           /* True if constraints are supported */
11047   int iSavepoint;           /* Depth of the SAVEPOINT stack */
11048   VTable *pNext;            /* Next in linked list (see above) */
11049 };
11050 
11051 /*
11052 ** Each SQL table is represented in memory by an instance of the
11053 ** following structure.
11054 **
11055 ** Table.zName is the name of the table.  The case of the original
11056 ** CREATE TABLE statement is stored, but case is not significant for
11057 ** comparisons.
11058 **
11059 ** Table.nCol is the number of columns in this table.  Table.aCol is a
11060 ** pointer to an array of Column structures, one for each column.
11061 **
11062 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
11063 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
11064 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
11065 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
11066 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
11067 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
11068 ** the table has any PRIMARY KEY, INTEGER or otherwise.
11069 **
11070 ** Table.tnum is the page number for the root BTree page of the table in the
11071 ** database file.  If Table.iDb is the index of the database table backend
11072 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
11073 ** holds temporary tables and indices.  If TF_Ephemeral is set
11074 ** then the table is stored in a file that is automatically deleted
11075 ** when the VDBE cursor to the table is closed.  In this case Table.tnum
11076 ** refers VDBE cursor number that holds the table open, not to the root
11077 ** page number.  Transient tables are used to hold the results of a
11078 ** sub-query that appears instead of a real table name in the FROM clause
11079 ** of a SELECT statement.
11080 */
11081 struct Table {
11082   char *zName;         /* Name of the table or view */
11083   Column *aCol;        /* Information about each column */
11084   Index *pIndex;       /* List of SQL indexes on this table. */
11085   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
11086   FKey *pFKey;         /* Linked list of all foreign keys in this table */
11087   char *zColAff;       /* String defining the affinity of each column */
11088 #ifndef SQLITE_OMIT_CHECK
11089   ExprList *pCheck;    /* All CHECK constraints */
11090 #endif
11091   LogEst nRowLogEst;   /* Estimated rows in table - from sqlite_stat1 table */
11092   int tnum;            /* Root BTree node for this table (see note above) */
11093   i16 iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
11094   i16 nCol;            /* Number of columns in this table */
11095   u16 nRef;            /* Number of pointers to this Table */
11096   LogEst szTabRow;     /* Estimated size of each table row in bytes */
11097 #ifdef SQLITE_ENABLE_COSTMULT
11098   LogEst costMult;     /* Cost multiplier for using this table */
11099 #endif
11100   u8 tabFlags;         /* Mask of TF_* values */
11101   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
11102 #ifndef SQLITE_OMIT_ALTERTABLE
11103   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
11104 #endif
11105 #ifndef SQLITE_OMIT_VIRTUALTABLE
11106   int nModuleArg;      /* Number of arguments to the module */
11107   char **azModuleArg;  /* Text of all module args. [0] is module name */
11108   VTable *pVTable;     /* List of VTable objects. */
11109 #endif
11110   Trigger *pTrigger;   /* List of triggers stored in pSchema */
11111   Schema *pSchema;     /* Schema that contains this table */
11112   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
11113 };
11114 
11115 /*
11116 ** Allowed values for Table.tabFlags.
11117 */
11118 #define TF_Readonly        0x01    /* Read-only system table */
11119 #define TF_Ephemeral       0x02    /* An ephemeral table */
11120 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
11121 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
11122 #define TF_Virtual         0x10    /* Is a virtual table */
11123 #define TF_WithoutRowid    0x20    /* No rowid used. PRIMARY KEY is the key */
11124 
11125 
11126 /*
11127 ** Test to see whether or not a table is a virtual table.  This is
11128 ** done as a macro so that it will be optimized out when virtual
11129 ** table support is omitted from the build.
11130 */
11131 #ifndef SQLITE_OMIT_VIRTUALTABLE
11132 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
11133 #  define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
11134 #else
11135 #  define IsVirtual(X)      0
11136 #  define IsHiddenColumn(X) 0
11137 #endif
11138 
11139 /* Does the table have a rowid */
11140 #define HasRowid(X)     (((X)->tabFlags & TF_WithoutRowid)==0)
11141 
11142 /*
11143 ** Each foreign key constraint is an instance of the following structure.
11144 **
11145 ** A foreign key is associated with two tables.  The "from" table is
11146 ** the table that contains the REFERENCES clause that creates the foreign
11147 ** key.  The "to" table is the table that is named in the REFERENCES clause.
11148 ** Consider this example:
11149 **
11150 **     CREATE TABLE ex1(
11151 **       a INTEGER PRIMARY KEY,
11152 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
11153 **     );
11154 **
11155 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
11156 ** Equivalent names:
11157 **
11158 **     from-table == child-table
11159 **       to-table == parent-table
11160 **
11161 ** Each REFERENCES clause generates an instance of the following structure
11162 ** which is attached to the from-table.  The to-table need not exist when
11163 ** the from-table is created.  The existence of the to-table is not checked.
11164 **
11165 ** The list of all parents for child Table X is held at X.pFKey.
11166 **
11167 ** A list of all children for a table named Z (which might not even exist)
11168 ** is held in Schema.fkeyHash with a hash key of Z.
11169 */
11170 struct FKey {
11171   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
11172   FKey *pNextFrom;  /* Next FKey with the same in pFrom. Next parent of pFrom */
11173   char *zTo;        /* Name of table that the key points to (aka: Parent) */
11174   FKey *pNextTo;    /* Next with the same zTo. Next child of zTo. */
11175   FKey *pPrevTo;    /* Previous with the same zTo */
11176   int nCol;         /* Number of columns in this key */
11177   /* EV: R-30323-21917 */
11178   u8 isDeferred;       /* True if constraint checking is deferred till COMMIT */
11179   u8 aAction[2];        /* ON DELETE and ON UPDATE actions, respectively */
11180   Trigger *apTrigger[2];/* Triggers for aAction[] actions */
11181   struct sColMap {      /* Mapping of columns in pFrom to columns in zTo */
11182     int iFrom;            /* Index of column in pFrom */
11183     char *zCol;           /* Name of column in zTo.  If NULL use PRIMARY KEY */
11184   } aCol[1];            /* One entry for each of nCol columns */
11185 };
11186 
11187 /*
11188 ** SQLite supports many different ways to resolve a constraint
11189 ** error.  ROLLBACK processing means that a constraint violation
11190 ** causes the operation in process to fail and for the current transaction
11191 ** to be rolled back.  ABORT processing means the operation in process
11192 ** fails and any prior changes from that one operation are backed out,
11193 ** but the transaction is not rolled back.  FAIL processing means that
11194 ** the operation in progress stops and returns an error code.  But prior
11195 ** changes due to the same operation are not backed out and no rollback
11196 ** occurs.  IGNORE means that the particular row that caused the constraint
11197 ** error is not inserted or updated.  Processing continues and no error
11198 ** is returned.  REPLACE means that preexisting database rows that caused
11199 ** a UNIQUE constraint violation are removed so that the new insert or
11200 ** update can proceed.  Processing continues and no error is reported.
11201 **
11202 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
11203 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
11204 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
11205 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
11206 ** referenced table row is propagated into the row that holds the
11207 ** foreign key.
11208 **
11209 ** The following symbolic values are used to record which type
11210 ** of action to take.
11211 */
11212 #define OE_None     0   /* There is no constraint to check */
11213 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
11214 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
11215 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
11216 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
11217 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
11218 
11219 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
11220 #define OE_SetNull  7   /* Set the foreign key value to NULL */
11221 #define OE_SetDflt  8   /* Set the foreign key value to its default */
11222 #define OE_Cascade  9   /* Cascade the changes */
11223 
11224 #define OE_Default  10  /* Do whatever the default action is */
11225 
11226 
11227 /*
11228 ** An instance of the following structure is passed as the first
11229 ** argument to sqlite3VdbeKeyCompare and is used to control the
11230 ** comparison of the two index keys.
11231 **
11232 ** Note that aSortOrder[] and aColl[] have nField+1 slots.  There
11233 ** are nField slots for the columns of an index then one extra slot
11234 ** for the rowid at the end.
11235 */
11236 struct KeyInfo {
11237   u32 nRef;           /* Number of references to this KeyInfo object */
11238   u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
11239   u16 nField;         /* Number of key columns in the index */
11240   u16 nXField;        /* Number of columns beyond the key columns */
11241   sqlite3 *db;        /* The database connection */
11242   u8 *aSortOrder;     /* Sort order for each column. */
11243   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
11244 };
11245 
11246 /*
11247 ** An instance of the following structure holds information about a
11248 ** single index record that has already been parsed out into individual
11249 ** values.
11250 **
11251 ** A record is an object that contains one or more fields of data.
11252 ** Records are used to store the content of a table row and to store
11253 ** the key of an index.  A blob encoding of a record is created by
11254 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
11255 ** OP_Column opcode.
11256 **
11257 ** This structure holds a record that has already been disassembled
11258 ** into its constituent fields.
11259 **
11260 ** The r1 and r2 member variables are only used by the optimized comparison
11261 ** functions vdbeRecordCompareInt() and vdbeRecordCompareString().
11262 */
11263 struct UnpackedRecord {
11264   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
11265   u16 nField;         /* Number of entries in apMem[] */
11266   i8 default_rc;      /* Comparison result if keys are equal */
11267   u8 errCode;         /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
11268   Mem *aMem;          /* Values */
11269   int r1;             /* Value to return if (lhs > rhs) */
11270   int r2;             /* Value to return if (rhs < lhs) */
11271 };
11272 
11273 
11274 /*
11275 ** Each SQL index is represented in memory by an
11276 ** instance of the following structure.
11277 **
11278 ** The columns of the table that are to be indexed are described
11279 ** by the aiColumn[] field of this structure.  For example, suppose
11280 ** we have the following table and index:
11281 **
11282 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
11283 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
11284 **
11285 ** In the Table structure describing Ex1, nCol==3 because there are
11286 ** three columns in the table.  In the Index structure describing
11287 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
11288 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
11289 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
11290 ** The second column to be indexed (c1) has an index of 0 in
11291 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
11292 **
11293 ** The Index.onError field determines whether or not the indexed columns
11294 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
11295 ** it means this is not a unique index.  Otherwise it is a unique index
11296 ** and the value of Index.onError indicate the which conflict resolution
11297 ** algorithm to employ whenever an attempt is made to insert a non-unique
11298 ** element.
11299 */
11300 struct Index {
11301   char *zName;             /* Name of this index */
11302   i16 *aiColumn;           /* Which columns are used by this index.  1st is 0 */
11303   LogEst *aiRowLogEst;     /* From ANALYZE: Est. rows selected by each column */
11304   Table *pTable;           /* The SQL table being indexed */
11305   char *zColAff;           /* String defining the affinity of each column */
11306   Index *pNext;            /* The next index associated with the same table */
11307   Schema *pSchema;         /* Schema containing this index */
11308   u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
11309   char **azColl;           /* Array of collation sequence names for index */
11310   Expr *pPartIdxWhere;     /* WHERE clause for partial indices */
11311   KeyInfo *pKeyInfo;       /* A KeyInfo object suitable for this index */
11312   int tnum;                /* DB Page containing root of this index */
11313   LogEst szIdxRow;         /* Estimated average row size in bytes */
11314   u16 nKeyCol;             /* Number of columns forming the key */
11315   u16 nColumn;             /* Number of columns stored in the index */
11316   u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
11317   unsigned idxType:2;      /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
11318   unsigned bUnordered:1;   /* Use this index for == or IN queries only */
11319   unsigned uniqNotNull:1;  /* True if UNIQUE and NOT NULL for all columns */
11320   unsigned isResized:1;    /* True if resizeIndexObject() has been called */
11321   unsigned isCovering:1;   /* True if this is a covering index */
11322 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
11323   int nSample;             /* Number of elements in aSample[] */
11324   int nSampleCol;          /* Size of IndexSample.anEq[] and so on */
11325   tRowcnt *aAvgEq;         /* Average nEq values for keys not in aSample */
11326   IndexSample *aSample;    /* Samples of the left-most key */
11327   tRowcnt *aiRowEst;       /* Non-logarithmic stat1 data for this table */
11328 #endif
11329 };
11330 
11331 /*
11332 ** Allowed values for Index.idxType
11333 */
11334 #define SQLITE_IDXTYPE_APPDEF      0   /* Created using CREATE INDEX */
11335 #define SQLITE_IDXTYPE_UNIQUE      1   /* Implements a UNIQUE constraint */
11336 #define SQLITE_IDXTYPE_PRIMARYKEY  2   /* Is the PRIMARY KEY for the table */
11337 
11338 /* Return true if index X is a PRIMARY KEY index */
11339 #define IsPrimaryKeyIndex(X)  ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
11340 
11341 /* Return true if index X is a UNIQUE index */
11342 #define IsUniqueIndex(X)      ((X)->onError!=OE_None)
11343 
11344 /*
11345 ** Each sample stored in the sqlite_stat3 table is represented in memory
11346 ** using a structure of this type.  See documentation at the top of the
11347 ** analyze.c source file for additional information.
11348 */
11349 struct IndexSample {
11350   void *p;          /* Pointer to sampled record */
11351   int n;            /* Size of record in bytes */
11352   tRowcnt *anEq;    /* Est. number of rows where the key equals this sample */
11353   tRowcnt *anLt;    /* Est. number of rows where key is less than this sample */
11354   tRowcnt *anDLt;   /* Est. number of distinct keys less than this sample */
11355 };
11356 
11357 /*
11358 ** Each token coming out of the lexer is an instance of
11359 ** this structure.  Tokens are also used as part of an expression.
11360 **
11361 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
11362 ** may contain random values.  Do not make any assumptions about Token.dyn
11363 ** and Token.n when Token.z==0.
11364 */
11365 struct Token {
11366   const char *z;     /* Text of the token.  Not NULL-terminated! */
11367   unsigned int n;    /* Number of characters in this token */
11368 };
11369 
11370 /*
11371 ** An instance of this structure contains information needed to generate
11372 ** code for a SELECT that contains aggregate functions.
11373 **
11374 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
11375 ** pointer to this structure.  The Expr.iColumn field is the index in
11376 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
11377 ** code for that node.
11378 **
11379 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
11380 ** original Select structure that describes the SELECT statement.  These
11381 ** fields do not need to be freed when deallocating the AggInfo structure.
11382 */
11383 struct AggInfo {
11384   u8 directMode;          /* Direct rendering mode means take data directly
11385                           ** from source tables rather than from accumulators */
11386   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
11387                           ** than the source table */
11388   int sortingIdx;         /* Cursor number of the sorting index */
11389   int sortingIdxPTab;     /* Cursor number of pseudo-table */
11390   int nSortingColumn;     /* Number of columns in the sorting index */
11391   int mnReg, mxReg;       /* Range of registers allocated for aCol and aFunc */
11392   ExprList *pGroupBy;     /* The group by clause */
11393   struct AggInfo_col {    /* For each column used in source tables */
11394     Table *pTab;             /* Source table */
11395     int iTable;              /* Cursor number of the source table */
11396     int iColumn;             /* Column number within the source table */
11397     int iSorterColumn;       /* Column number in the sorting index */
11398     int iMem;                /* Memory location that acts as accumulator */
11399     Expr *pExpr;             /* The original expression */
11400   } *aCol;
11401   int nColumn;            /* Number of used entries in aCol[] */
11402   int nAccumulator;       /* Number of columns that show through to the output.
11403                           ** Additional columns are used only as parameters to
11404                           ** aggregate functions */
11405   struct AggInfo_func {   /* For each aggregate function */
11406     Expr *pExpr;             /* Expression encoding the function */
11407     FuncDef *pFunc;          /* The aggregate function implementation */
11408     int iMem;                /* Memory location that acts as accumulator */
11409     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
11410   } *aFunc;
11411   int nFunc;              /* Number of entries in aFunc[] */
11412 };
11413 
11414 /*
11415 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
11416 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
11417 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
11418 ** it uses less memory in the Expr object, which is a big memory user
11419 ** in systems with lots of prepared statements.  And few applications
11420 ** need more than about 10 or 20 variables.  But some extreme users want
11421 ** to have prepared statements with over 32767 variables, and for them
11422 ** the option is available (at compile-time).
11423 */
11424 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
11425 typedef i16 ynVar;
11426 #else
11427 typedef int ynVar;
11428 #endif
11429 
11430 /*
11431 ** Each node of an expression in the parse tree is an instance
11432 ** of this structure.
11433 **
11434 ** Expr.op is the opcode. The integer parser token codes are reused
11435 ** as opcodes here. For example, the parser defines TK_GE to be an integer
11436 ** code representing the ">=" operator. This same integer code is reused
11437 ** to represent the greater-than-or-equal-to operator in the expression
11438 ** tree.
11439 **
11440 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
11441 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
11442 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
11443 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
11444 ** then Expr.token contains the name of the function.
11445 **
11446 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
11447 ** binary operator. Either or both may be NULL.
11448 **
11449 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
11450 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
11451 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
11452 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
11453 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
11454 ** valid.
11455 **
11456 ** An expression of the form ID or ID.ID refers to a column in a table.
11457 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
11458 ** the integer cursor number of a VDBE cursor pointing to that table and
11459 ** Expr.iColumn is the column number for the specific column.  If the
11460 ** expression is used as a result in an aggregate SELECT, then the
11461 ** value is also stored in the Expr.iAgg column in the aggregate so that
11462 ** it can be accessed after all aggregates are computed.
11463 **
11464 ** If the expression is an unbound variable marker (a question mark
11465 ** character '?' in the original SQL) then the Expr.iTable holds the index
11466 ** number for that variable.
11467 **
11468 ** If the expression is a subquery then Expr.iColumn holds an integer
11469 ** register number containing the result of the subquery.  If the
11470 ** subquery gives a constant result, then iTable is -1.  If the subquery
11471 ** gives a different answer at different times during statement processing
11472 ** then iTable is the address of a subroutine that computes the subquery.
11473 **
11474 ** If the Expr is of type OP_Column, and the table it is selecting from
11475 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
11476 ** corresponding table definition.
11477 **
11478 ** ALLOCATION NOTES:
11479 **
11480 ** Expr objects can use a lot of memory space in database schema.  To
11481 ** help reduce memory requirements, sometimes an Expr object will be
11482 ** truncated.  And to reduce the number of memory allocations, sometimes
11483 ** two or more Expr objects will be stored in a single memory allocation,
11484 ** together with Expr.zToken strings.
11485 **
11486 ** If the EP_Reduced and EP_TokenOnly flags are set when
11487 ** an Expr object is truncated.  When EP_Reduced is set, then all
11488 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
11489 ** are contained within the same memory allocation.  Note, however, that
11490 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
11491 ** allocated, regardless of whether or not EP_Reduced is set.
11492 */
11493 struct Expr {
11494   u8 op;                 /* Operation performed by this node */
11495   char affinity;         /* The affinity of the column or 0 if not a column */
11496   u32 flags;             /* Various flags.  EP_* See below */
11497   union {
11498     char *zToken;          /* Token value. Zero terminated and dequoted */
11499     int iValue;            /* Non-negative integer value if EP_IntValue */
11500   } u;
11501 
11502   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
11503   ** space is allocated for the fields below this point. An attempt to
11504   ** access them will result in a segfault or malfunction.
11505   *********************************************************************/
11506 
11507   Expr *pLeft;           /* Left subnode */
11508   Expr *pRight;          /* Right subnode */
11509   union {
11510     ExprList *pList;     /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
11511     Select *pSelect;     /* EP_xIsSelect and op = IN, EXISTS, SELECT */
11512   } x;
11513 
11514   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
11515   ** space is allocated for the fields below this point. An attempt to
11516   ** access them will result in a segfault or malfunction.
11517   *********************************************************************/
11518 
11519 #if SQLITE_MAX_EXPR_DEPTH>0
11520   int nHeight;           /* Height of the tree headed by this node */
11521 #endif
11522   int iTable;            /* TK_COLUMN: cursor number of table holding column
11523                          ** TK_REGISTER: register number
11524                          ** TK_TRIGGER: 1 -> new, 0 -> old
11525                          ** EP_Unlikely:  1000 times likelihood */
11526   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
11527                          ** TK_VARIABLE: variable number (always >= 1). */
11528   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
11529   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
11530   u8 op2;                /* TK_REGISTER: original value of Expr.op
11531                          ** TK_COLUMN: the value of p5 for OP_Column
11532                          ** TK_AGG_FUNCTION: nesting depth */
11533   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
11534   Table *pTab;           /* Table for TK_COLUMN expressions. */
11535 };
11536 
11537 /*
11538 ** The following are the meanings of bits in the Expr.flags field.
11539 */
11540 #define EP_FromJoin  0x000001 /* Originated in ON or USING clause of a join */
11541 #define EP_Agg       0x000002 /* Contains one or more aggregate functions */
11542 #define EP_Resolved  0x000004 /* IDs have been resolved to COLUMNs */
11543 #define EP_Error     0x000008 /* Expression contains one or more errors */
11544 #define EP_Distinct  0x000010 /* Aggregate function with DISTINCT keyword */
11545 #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
11546 #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
11547 #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
11548 #define EP_Collate   0x000100 /* Tree contains a TK_COLLATE operator */
11549 #define EP_Generic   0x000200 /* Ignore COLLATE or affinity on this tree */
11550 #define EP_IntValue  0x000400 /* Integer value contained in u.iValue */
11551 #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
11552 #define EP_Skip      0x001000 /* COLLATE, AS, or UNLIKELY */
11553 #define EP_Reduced   0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
11554 #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
11555 #define EP_Static    0x008000 /* Held in memory not obtained from malloc() */
11556 #define EP_MemToken  0x010000 /* Need to sqlite3DbFree() Expr.zToken */
11557 #define EP_NoReduce  0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
11558 #define EP_Unlikely  0x040000 /* unlikely() or likelihood() function */
11559 #define EP_Constant  0x080000 /* Node is a constant */
11560 
11561 /*
11562 ** These macros can be used to test, set, or clear bits in the
11563 ** Expr.flags field.
11564 */
11565 #define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)
11566 #define ExprHasAllProperty(E,P)  (((E)->flags&(P))==(P))
11567 #define ExprSetProperty(E,P)     (E)->flags|=(P)
11568 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
11569 
11570 /* The ExprSetVVAProperty() macro is used for Verification, Validation,
11571 ** and Accreditation only.  It works like ExprSetProperty() during VVA
11572 ** processes but is a no-op for delivery.
11573 */
11574 #ifdef SQLITE_DEBUG
11575 # define ExprSetVVAProperty(E,P)  (E)->flags|=(P)
11576 #else
11577 # define ExprSetVVAProperty(E,P)
11578 #endif
11579 
11580 /*
11581 ** Macros to determine the number of bytes required by a normal Expr
11582 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
11583 ** and an Expr struct with the EP_TokenOnly flag set.
11584 */
11585 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
11586 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
11587 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
11588 
11589 /*
11590 ** Flags passed to the sqlite3ExprDup() function. See the header comment
11591 ** above sqlite3ExprDup() for details.
11592 */
11593 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
11594 
11595 /*
11596 ** A list of expressions.  Each expression may optionally have a
11597 ** name.  An expr/name combination can be used in several ways, such
11598 ** as the list of "expr AS ID" fields following a "SELECT" or in the
11599 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
11600 ** also be used as the argument to a function, in which case the a.zName
11601 ** field is not used.
11602 **
11603 ** By default the Expr.zSpan field holds a human-readable description of
11604 ** the expression that is used in the generation of error messages and
11605 ** column labels.  In this case, Expr.zSpan is typically the text of a
11606 ** column expression as it exists in a SELECT statement.  However, if
11607 ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
11608 ** of the result column in the form: DATABASE.TABLE.COLUMN.  This later
11609 ** form is used for name resolution with nested FROM clauses.
11610 */
11611 struct ExprList {
11612   int nExpr;             /* Number of expressions on the list */
11613   struct ExprList_item { /* For each expression in the list */
11614     Expr *pExpr;            /* The list of expressions */
11615     char *zName;            /* Token associated with this expression */
11616     char *zSpan;            /* Original text of the expression */
11617     u8 sortOrder;           /* 1 for DESC or 0 for ASC */
11618     unsigned done :1;       /* A flag to indicate when processing is finished */
11619     unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
11620     unsigned reusable :1;   /* Constant expression is reusable */
11621     union {
11622       struct {
11623         u16 iOrderByCol;      /* For ORDER BY, column number in result set */
11624         u16 iAlias;           /* Index into Parse.aAlias[] for zName */
11625       } x;
11626       int iConstExprReg;      /* Register in which Expr value is cached */
11627     } u;
11628   } *a;                  /* Alloc a power of two greater or equal to nExpr */
11629 };
11630 
11631 /*
11632 ** An instance of this structure is used by the parser to record both
11633 ** the parse tree for an expression and the span of input text for an
11634 ** expression.
11635 */
11636 struct ExprSpan {
11637   Expr *pExpr;          /* The expression parse tree */
11638   const char *zStart;   /* First character of input text */
11639   const char *zEnd;     /* One character past the end of input text */
11640 };
11641 
11642 /*
11643 ** An instance of this structure can hold a simple list of identifiers,
11644 ** such as the list "a,b,c" in the following statements:
11645 **
11646 **      INSERT INTO t(a,b,c) VALUES ...;
11647 **      CREATE INDEX idx ON t(a,b,c);
11648 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
11649 **
11650 ** The IdList.a.idx field is used when the IdList represents the list of
11651 ** column names after a table name in an INSERT statement.  In the statement
11652 **
11653 **     INSERT INTO t(a,b,c) ...
11654 **
11655 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
11656 */
11657 struct IdList {
11658   struct IdList_item {
11659     char *zName;      /* Name of the identifier */
11660     int idx;          /* Index in some Table.aCol[] of a column named zName */
11661   } *a;
11662   int nId;         /* Number of identifiers on the list */
11663 };
11664 
11665 /*
11666 ** The bitmask datatype defined below is used for various optimizations.
11667 **
11668 ** Changing this from a 64-bit to a 32-bit type limits the number of
11669 ** tables in a join to 32 instead of 64.  But it also reduces the size
11670 ** of the library by 738 bytes on ix86.
11671 */
11672 typedef u64 Bitmask;
11673 
11674 /*
11675 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
11676 */
11677 #define BMS  ((int)(sizeof(Bitmask)*8))
11678 
11679 /*
11680 ** A bit in a Bitmask
11681 */
11682 #define MASKBIT(n)   (((Bitmask)1)<<(n))
11683 #define MASKBIT32(n) (((unsigned int)1)<<(n))
11684 
11685 /*
11686 ** The following structure describes the FROM clause of a SELECT statement.
11687 ** Each table or subquery in the FROM clause is a separate element of
11688 ** the SrcList.a[] array.
11689 **
11690 ** With the addition of multiple database support, the following structure
11691 ** can also be used to describe a particular table such as the table that
11692 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
11693 ** such a table must be a simple name: ID.  But in SQLite, the table can
11694 ** now be identified by a database name, a dot, then the table name: ID.ID.
11695 **
11696 ** The jointype starts out showing the join type between the current table
11697 ** and the next table on the list.  The parser builds the list this way.
11698 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
11699 ** jointype expresses the join between the table and the previous table.
11700 **
11701 ** In the colUsed field, the high-order bit (bit 63) is set if the table
11702 ** contains more than 63 columns and the 64-th or later column is used.
11703 */
11704 struct SrcList {
11705   int nSrc;        /* Number of tables or subqueries in the FROM clause */
11706   u32 nAlloc;      /* Number of entries allocated in a[] below */
11707   struct SrcList_item {
11708     Schema *pSchema;  /* Schema to which this item is fixed */
11709     char *zDatabase;  /* Name of database holding this table */
11710     char *zName;      /* Name of the table */
11711     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
11712     Table *pTab;      /* An SQL table corresponding to zName */
11713     Select *pSelect;  /* A SELECT statement used in place of a table name */
11714     int addrFillSub;  /* Address of subroutine to manifest a subquery */
11715     int regReturn;    /* Register holding return address of addrFillSub */
11716     int regResult;    /* Registers holding results of a co-routine */
11717     u8 jointype;      /* Type of join between this able and the previous */
11718     unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
11719     unsigned isCorrelated :1;  /* True if sub-query is correlated */
11720     unsigned viaCoroutine :1;  /* Implemented as a co-routine */
11721     unsigned isRecursive :1;   /* True for recursive reference in WITH */
11722 #ifndef SQLITE_OMIT_EXPLAIN
11723     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
11724 #endif
11725     int iCursor;      /* The VDBE cursor number used to access this table */
11726     Expr *pOn;        /* The ON clause of a join */
11727     IdList *pUsing;   /* The USING clause of a join */
11728     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
11729     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
11730     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
11731   } a[1];             /* One entry for each identifier on the list */
11732 };
11733 
11734 /*
11735 ** Permitted values of the SrcList.a.jointype field
11736 */
11737 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
11738 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
11739 #define JT_NATURAL   0x0004    /* True for a "natural" join */
11740 #define JT_LEFT      0x0008    /* Left outer join */
11741 #define JT_RIGHT     0x0010    /* Right outer join */
11742 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
11743 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
11744 
11745 
11746 /*
11747 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
11748 ** and the WhereInfo.wctrlFlags member.
11749 */
11750 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
11751 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
11752 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
11753 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
11754 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
11755 #define WHERE_OMIT_OPEN_CLOSE  0x0010 /* Table cursors are already open */
11756 #define WHERE_FORCE_TABLE      0x0020 /* Do not use an index-only search */
11757 #define WHERE_ONETABLE_ONLY    0x0040 /* Only code the 1st table in pTabList */
11758                           /*   0x0080 // not currently used */
11759 #define WHERE_GROUPBY          0x0100 /* pOrderBy is really a GROUP BY */
11760 #define WHERE_DISTINCTBY       0x0200 /* pOrderby is really a DISTINCT clause */
11761 #define WHERE_WANT_DISTINCT    0x0400 /* All output needs to be distinct */
11762 #define WHERE_SORTBYGROUP      0x0800 /* Support sqlite3WhereIsSorted() */
11763 #define WHERE_REOPEN_IDX       0x1000 /* Try to use OP_ReopenIdx */
11764 
11765 /* Allowed return values from sqlite3WhereIsDistinct()
11766 */
11767 #define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
11768 #define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
11769 #define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
11770 #define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
11771 
11772 /*
11773 ** A NameContext defines a context in which to resolve table and column
11774 ** names.  The context consists of a list of tables (the pSrcList) field and
11775 ** a list of named expression (pEList).  The named expression list may
11776 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
11777 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
11778 ** pEList corresponds to the result set of a SELECT and is NULL for
11779 ** other statements.
11780 **
11781 ** NameContexts can be nested.  When resolving names, the inner-most
11782 ** context is searched first.  If no match is found, the next outer
11783 ** context is checked.  If there is still no match, the next context
11784 ** is checked.  This process continues until either a match is found
11785 ** or all contexts are check.  When a match is found, the nRef member of
11786 ** the context containing the match is incremented.
11787 **
11788 ** Each subquery gets a new NameContext.  The pNext field points to the
11789 ** NameContext in the parent query.  Thus the process of scanning the
11790 ** NameContext list corresponds to searching through successively outer
11791 ** subqueries looking for a match.
11792 */
11793 struct NameContext {
11794   Parse *pParse;       /* The parser */
11795   SrcList *pSrcList;   /* One or more tables used to resolve names */
11796   ExprList *pEList;    /* Optional list of result-set columns */
11797   AggInfo *pAggInfo;   /* Information about aggregates at this level */
11798   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
11799   int nRef;            /* Number of names resolved by this context */
11800   int nErr;            /* Number of errors encountered while resolving names */
11801   u16 ncFlags;         /* Zero or more NC_* flags defined below */
11802 };
11803 
11804 /*
11805 ** Allowed values for the NameContext, ncFlags field.
11806 **
11807 ** Note:  NC_MinMaxAgg must have the same value as SF_MinMaxAgg and
11808 ** SQLITE_FUNC_MINMAX.
11809 **
11810 */
11811 #define NC_AllowAgg  0x0001  /* Aggregate functions are allowed here */
11812 #define NC_HasAgg    0x0002  /* One or more aggregate functions seen */
11813 #define NC_IsCheck   0x0004  /* True if resolving names in a CHECK constraint */
11814 #define NC_InAggFunc 0x0008  /* True if analyzing arguments to an agg func */
11815 #define NC_PartIdx   0x0010  /* True if resolving a partial index WHERE */
11816 #define NC_MinMaxAgg 0x1000  /* min/max aggregates seen.  See note above */
11817 
11818 /*
11819 ** An instance of the following structure contains all information
11820 ** needed to generate code for a single SELECT statement.
11821 **
11822 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
11823 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
11824 ** limit and nOffset to the value of the offset (or 0 if there is not
11825 ** offset).  But later on, nLimit and nOffset become the memory locations
11826 ** in the VDBE that record the limit and offset counters.
11827 **
11828 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
11829 ** These addresses must be stored so that we can go back and fill in
11830 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
11831 ** the number of columns in P2 can be computed at the same time
11832 ** as the OP_OpenEphm instruction is coded because not
11833 ** enough information about the compound query is known at that point.
11834 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
11835 ** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
11836 ** sequences for the ORDER BY clause.
11837 */
11838 struct Select {
11839   ExprList *pEList;      /* The fields of the result */
11840   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
11841   u16 selFlags;          /* Various SF_* values */
11842   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
11843 #if SELECTTRACE_ENABLED
11844   char zSelName[12];     /* Symbolic name of this SELECT use for debugging */
11845 #endif
11846   int addrOpenEphm[2];   /* OP_OpenEphem opcodes related to this select */
11847   u64 nSelectRow;        /* Estimated number of result rows */
11848   SrcList *pSrc;         /* The FROM clause */
11849   Expr *pWhere;          /* The WHERE clause */
11850   ExprList *pGroupBy;    /* The GROUP BY clause */
11851   Expr *pHaving;         /* The HAVING clause */
11852   ExprList *pOrderBy;    /* The ORDER BY clause */
11853   Select *pPrior;        /* Prior select in a compound select statement */
11854   Select *pNext;         /* Next select to the left in a compound */
11855   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
11856   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
11857   With *pWith;           /* WITH clause attached to this select. Or NULL. */
11858 };
11859 
11860 /*
11861 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
11862 ** "Select Flag".
11863 */
11864 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
11865 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
11866 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
11867 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
11868 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
11869 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
11870 #define SF_Compound        0x0040  /* Part of a compound query */
11871 #define SF_Values          0x0080  /* Synthesized from VALUES clause */
11872                     /*     0x0100  NOT USED */
11873 #define SF_NestedFrom      0x0200  /* Part of a parenthesized FROM clause */
11874 #define SF_MaybeConvert    0x0400  /* Need convertCompoundSelectToSubquery() */
11875 #define SF_Recursive       0x0800  /* The recursive part of a recursive CTE */
11876 #define SF_MinMaxAgg       0x1000  /* Aggregate containing min() or max() */
11877 
11878 
11879 /*
11880 ** The results of a SELECT can be distributed in several ways, as defined
11881 ** by one of the following macros.  The "SRT" prefix means "SELECT Result
11882 ** Type".
11883 **
11884 **     SRT_Union       Store results as a key in a temporary index
11885 **                     identified by pDest->iSDParm.
11886 **
11887 **     SRT_Except      Remove results from the temporary index pDest->iSDParm.
11888 **
11889 **     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
11890 **                     set is not empty.
11891 **
11892 **     SRT_Discard     Throw the results away.  This is used by SELECT
11893 **                     statements within triggers whose only purpose is
11894 **                     the side-effects of functions.
11895 **
11896 ** All of the above are free to ignore their ORDER BY clause. Those that
11897 ** follow must honor the ORDER BY clause.
11898 **
11899 **     SRT_Output      Generate a row of output (using the OP_ResultRow
11900 **                     opcode) for each row in the result set.
11901 **
11902 **     SRT_Mem         Only valid if the result is a single column.
11903 **                     Store the first column of the first result row
11904 **                     in register pDest->iSDParm then abandon the rest
11905 **                     of the query.  This destination implies "LIMIT 1".
11906 **
11907 **     SRT_Set         The result must be a single column.  Store each
11908 **                     row of result as the key in table pDest->iSDParm.
11909 **                     Apply the affinity pDest->affSdst before storing
11910 **                     results.  Used to implement "IN (SELECT ...)".
11911 **
11912 **     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
11913 **                     the result there. The cursor is left open after
11914 **                     returning.  This is like SRT_Table except that
11915 **                     this destination uses OP_OpenEphemeral to create
11916 **                     the table first.
11917 **
11918 **     SRT_Coroutine   Generate a co-routine that returns a new row of
11919 **                     results each time it is invoked.  The entry point
11920 **                     of the co-routine is stored in register pDest->iSDParm
11921 **                     and the result row is stored in pDest->nDest registers
11922 **                     starting with pDest->iSdst.
11923 **
11924 **     SRT_Table       Store results in temporary table pDest->iSDParm.
11925 **     SRT_Fifo        This is like SRT_EphemTab except that the table
11926 **                     is assumed to already be open.  SRT_Fifo has
11927 **                     the additional property of being able to ignore
11928 **                     the ORDER BY clause.
11929 **
11930 **     SRT_DistFifo    Store results in a temporary table pDest->iSDParm.
11931 **                     But also use temporary table pDest->iSDParm+1 as
11932 **                     a record of all prior results and ignore any duplicate
11933 **                     rows.  Name means:  "Distinct Fifo".
11934 **
11935 **     SRT_Queue       Store results in priority queue pDest->iSDParm (really
11936 **                     an index).  Append a sequence number so that all entries
11937 **                     are distinct.
11938 **
11939 **     SRT_DistQueue   Store results in priority queue pDest->iSDParm only if
11940 **                     the same record has never been stored before.  The
11941 **                     index at pDest->iSDParm+1 hold all prior stores.
11942 */
11943 #define SRT_Union        1  /* Store result as keys in an index */
11944 #define SRT_Except       2  /* Remove result from a UNION index */
11945 #define SRT_Exists       3  /* Store 1 if the result is not empty */
11946 #define SRT_Discard      4  /* Do not save the results anywhere */
11947 #define SRT_Fifo         5  /* Store result as data with an automatic rowid */
11948 #define SRT_DistFifo     6  /* Like SRT_Fifo, but unique results only */
11949 #define SRT_Queue        7  /* Store result in an queue */
11950 #define SRT_DistQueue    8  /* Like SRT_Queue, but unique results only */
11951 
11952 /* The ORDER BY clause is ignored for all of the above */
11953 #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
11954 
11955 #define SRT_Output       9  /* Output each row of result */
11956 #define SRT_Mem         10  /* Store result in a memory cell */
11957 #define SRT_Set         11  /* Store results as keys in an index */
11958 #define SRT_EphemTab    12  /* Create transient tab and store like SRT_Table */
11959 #define SRT_Coroutine   13  /* Generate a single row of result */
11960 #define SRT_Table       14  /* Store result as data with an automatic rowid */
11961 
11962 /*
11963 ** An instance of this object describes where to put of the results of
11964 ** a SELECT statement.
11965 */
11966 struct SelectDest {
11967   u8 eDest;            /* How to dispose of the results.  On of SRT_* above. */
11968   char affSdst;        /* Affinity used when eDest==SRT_Set */
11969   int iSDParm;         /* A parameter used by the eDest disposal method */
11970   int iSdst;           /* Base register where results are written */
11971   int nSdst;           /* Number of registers allocated */
11972   ExprList *pOrderBy;  /* Key columns for SRT_Queue and SRT_DistQueue */
11973 };
11974 
11975 /*
11976 ** During code generation of statements that do inserts into AUTOINCREMENT
11977 ** tables, the following information is attached to the Table.u.autoInc.p
11978 ** pointer of each autoincrement table to record some side information that
11979 ** the code generator needs.  We have to keep per-table autoincrement
11980 ** information in case inserts are down within triggers.  Triggers do not
11981 ** normally coordinate their activities, but we do need to coordinate the
11982 ** loading and saving of autoincrement information.
11983 */
11984 struct AutoincInfo {
11985   AutoincInfo *pNext;   /* Next info block in a list of them all */
11986   Table *pTab;          /* Table this info block refers to */
11987   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
11988   int regCtr;           /* Memory register holding the rowid counter */
11989 };
11990 
11991 /*
11992 ** Size of the column cache
11993 */
11994 #ifndef SQLITE_N_COLCACHE
11995 # define SQLITE_N_COLCACHE 10
11996 #endif
11997 
11998 /*
11999 ** At least one instance of the following structure is created for each
12000 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
12001 ** statement. All such objects are stored in the linked list headed at
12002 ** Parse.pTriggerPrg and deleted once statement compilation has been
12003 ** completed.
12004 **
12005 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
12006 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
12007 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
12008 ** The Parse.pTriggerPrg list never contains two entries with the same
12009 ** values for both pTrigger and orconf.
12010 **
12011 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
12012 ** accessed (or set to 0 for triggers fired as a result of INSERT
12013 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
12014 ** a mask of new.* columns used by the program.
12015 */
12016 struct TriggerPrg {
12017   Trigger *pTrigger;      /* Trigger this program was coded from */
12018   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
12019   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
12020   int orconf;             /* Default ON CONFLICT policy */
12021   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
12022 };
12023 
12024 /*
12025 ** The yDbMask datatype for the bitmask of all attached databases.
12026 */
12027 #if SQLITE_MAX_ATTACHED>30
12028   typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
12029 # define DbMaskTest(M,I)    (((M)[(I)/8]&(1<<((I)&7)))!=0)
12030 # define DbMaskZero(M)      memset((M),0,sizeof(M))
12031 # define DbMaskSet(M,I)     (M)[(I)/8]|=(1<<((I)&7))
12032 # define DbMaskAllZero(M)   sqlite3DbMaskAllZero(M)
12033 # define DbMaskNonZero(M)   (sqlite3DbMaskAllZero(M)==0)
12034 #else
12035   typedef unsigned int yDbMask;
12036 # define DbMaskTest(M,I)    (((M)&(((yDbMask)1)<<(I)))!=0)
12037 # define DbMaskZero(M)      (M)=0
12038 # define DbMaskSet(M,I)     (M)|=(((yDbMask)1)<<(I))
12039 # define DbMaskAllZero(M)   (M)==0
12040 # define DbMaskNonZero(M)   (M)!=0
12041 #endif
12042 
12043 /*
12044 ** An SQL parser context.  A copy of this structure is passed through
12045 ** the parser and down into all the parser action routine in order to
12046 ** carry around information that is global to the entire parse.
12047 **
12048 ** The structure is divided into two parts.  When the parser and code
12049 ** generate call themselves recursively, the first part of the structure
12050 ** is constant but the second part is reset at the beginning and end of
12051 ** each recursion.
12052 **
12053 ** The nTableLock and aTableLock variables are only used if the shared-cache
12054 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
12055 ** used to store the set of table-locks required by the statement being
12056 ** compiled. Function sqlite3TableLock() is used to add entries to the
12057 ** list.
12058 */
12059 struct Parse {
12060   sqlite3 *db;         /* The main database structure */
12061   char *zErrMsg;       /* An error message */
12062   Vdbe *pVdbe;         /* An engine for executing database bytecode */
12063   int rc;              /* Return code from execution */
12064   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
12065   u8 checkSchema;      /* Causes schema cookie check after an error */
12066   u8 nested;           /* Number of nested calls to the parser/code generator */
12067   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
12068   u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
12069   u8 mayAbort;         /* True if statement may throw an ABORT exception */
12070   u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
12071   u8 okConstFactor;    /* OK to factor out constants */
12072   int aTempReg[8];     /* Holding area for temporary registers */
12073   int nRangeReg;       /* Size of the temporary register block */
12074   int iRangeReg;       /* First register in temporary register block */
12075   int nErr;            /* Number of errors seen */
12076   int nTab;            /* Number of previously allocated VDBE cursors */
12077   int nMem;            /* Number of memory cells used so far */
12078   int nSet;            /* Number of sets used so far */
12079   int nOnce;           /* Number of OP_Once instructions so far */
12080   int nOpAlloc;        /* Number of slots allocated for Vdbe.aOp[] */
12081   int iFixedOp;        /* Never back out opcodes iFixedOp-1 or earlier */
12082   int ckBase;          /* Base register of data during check constraints */
12083   int iPartIdxTab;     /* Table corresponding to a partial index */
12084   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
12085   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
12086   int nLabel;          /* Number of labels used */
12087   int *aLabel;         /* Space to hold the labels */
12088   struct yColCache {
12089     int iTable;           /* Table cursor number */
12090     i16 iColumn;          /* Table column number */
12091     u8 tempReg;           /* iReg is a temp register that needs to be freed */
12092     int iLevel;           /* Nesting level */
12093     int iReg;             /* Reg with value of this column. 0 means none. */
12094     int lru;              /* Least recently used entry has the smallest value */
12095   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
12096   ExprList *pConstExpr;/* Constant expressions */
12097   Token constraintName;/* Name of the constraint currently being parsed */
12098   yDbMask writeMask;   /* Start a write transaction on these databases */
12099   yDbMask cookieMask;  /* Bitmask of schema verified databases */
12100   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
12101   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
12102   int regRoot;         /* Register holding root page number for new objects */
12103   int nMaxArg;         /* Max args passed to user function by sub-program */
12104 #if SELECTTRACE_ENABLED
12105   int nSelect;         /* Number of SELECT statements seen */
12106   int nSelectIndent;   /* How far to indent SELECTTRACE() output */
12107 #endif
12108 #ifndef SQLITE_OMIT_SHARED_CACHE
12109   int nTableLock;        /* Number of locks in aTableLock */
12110   TableLock *aTableLock; /* Required table locks for shared-cache mode */
12111 #endif
12112   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
12113 
12114   /* Information used while coding trigger programs. */
12115   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
12116   Table *pTriggerTab;  /* Table triggers are being coded for */
12117   int addrCrTab;       /* Address of OP_CreateTable opcode on CREATE TABLE */
12118   int addrSkipPK;      /* Address of instruction to skip PRIMARY KEY index */
12119   u32 nQueryLoop;      /* Est number of iterations of a query (10*log2(N)) */
12120   u32 oldmask;         /* Mask of old.* columns referenced */
12121   u32 newmask;         /* Mask of new.* columns referenced */
12122   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
12123   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
12124   u8 disableTriggers;  /* True to disable triggers */
12125 
12126   /************************************************************************
12127   ** Above is constant between recursions.  Below is reset before and after
12128   ** each recursion.  The boundary between these two regions is determined
12129   ** using offsetof(Parse,nVar) so the nVar field must be the first field
12130   ** in the recursive region.
12131   ************************************************************************/
12132 
12133   int nVar;                 /* Number of '?' variables seen in the SQL so far */
12134   int nzVar;                /* Number of available slots in azVar[] */
12135   u8 iPkSortOrder;          /* ASC or DESC for INTEGER PRIMARY KEY */
12136   u8 bFreeWith;             /* True if pWith should be freed with parser */
12137   u8 explain;               /* True if the EXPLAIN flag is found on the query */
12138 #ifndef SQLITE_OMIT_VIRTUALTABLE
12139   u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
12140   int nVtabLock;            /* Number of virtual tables to lock */
12141 #endif
12142   int nAlias;               /* Number of aliased result set columns */
12143   int nHeight;              /* Expression tree height of current sub-select */
12144 #ifndef SQLITE_OMIT_EXPLAIN
12145   int iSelectId;            /* ID of current select for EXPLAIN output */
12146   int iNextSelectId;        /* Next available select ID for EXPLAIN output */
12147 #endif
12148   char **azVar;             /* Pointers to names of parameters */
12149   Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
12150   const char *zTail;        /* All SQL text past the last semicolon parsed */
12151   Table *pNewTable;         /* A table being constructed by CREATE TABLE */
12152   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
12153   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
12154   Token sNameToken;         /* Token with unqualified schema object name */
12155   Token sLastToken;         /* The last token parsed */
12156 #ifndef SQLITE_OMIT_VIRTUALTABLE
12157   Token sArg;               /* Complete text of a module argument */
12158   Table **apVtabLock;       /* Pointer to virtual tables needing locking */
12159 #endif
12160   Table *pZombieTab;        /* List of Table objects to delete after code gen */
12161   TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
12162   With *pWith;              /* Current WITH clause, or NULL */
12163 };
12164 
12165 /*
12166 ** Return true if currently inside an sqlite3_declare_vtab() call.
12167 */
12168 #ifdef SQLITE_OMIT_VIRTUALTABLE
12169   #define IN_DECLARE_VTAB 0
12170 #else
12171   #define IN_DECLARE_VTAB (pParse->declareVtab)
12172 #endif
12173 
12174 /*
12175 ** An instance of the following structure can be declared on a stack and used
12176 ** to save the Parse.zAuthContext value so that it can be restored later.
12177 */
12178 struct AuthContext {
12179   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
12180   Parse *pParse;              /* The Parse structure */
12181 };
12182 
12183 /*
12184 ** Bitfield flags for P5 value in various opcodes.
12185 */
12186 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
12187 #define OPFLAG_EPHEM         0x01    /* OP_Column: Ephemeral output is ok */
12188 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
12189 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
12190 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
12191 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
12192 #define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
12193 #define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
12194 #define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
12195 #define OPFLAG_P2ISREG       0x02    /* P2 to OP_Open** is a register number */
12196 #define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
12197 
12198 /*
12199  * Each trigger present in the database schema is stored as an instance of
12200  * struct Trigger.
12201  *
12202  * Pointers to instances of struct Trigger are stored in two ways.
12203  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
12204  *    database). This allows Trigger structures to be retrieved by name.
12205  * 2. All triggers associated with a single table form a linked list, using the
12206  *    pNext member of struct Trigger. A pointer to the first element of the
12207  *    linked list is stored as the "pTrigger" member of the associated
12208  *    struct Table.
12209  *
12210  * The "step_list" member points to the first element of a linked list
12211  * containing the SQL statements specified as the trigger program.
12212  */
12213 struct Trigger {
12214   char *zName;            /* The name of the trigger                        */
12215   char *table;            /* The table or view to which the trigger applies */
12216   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
12217   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
12218   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
12219   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
12220                              the <column-list> is stored here */
12221   Schema *pSchema;        /* Schema containing the trigger */
12222   Schema *pTabSchema;     /* Schema containing the table */
12223   TriggerStep *step_list; /* Link list of trigger program steps             */
12224   Trigger *pNext;         /* Next trigger associated with the table */
12225 };
12226 
12227 /*
12228 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
12229 ** determine which.
12230 **
12231 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
12232 ** In that cases, the constants below can be ORed together.
12233 */
12234 #define TRIGGER_BEFORE  1
12235 #define TRIGGER_AFTER   2
12236 
12237 /*
12238  * An instance of struct TriggerStep is used to store a single SQL statement
12239  * that is a part of a trigger-program.
12240  *
12241  * Instances of struct TriggerStep are stored in a singly linked list (linked
12242  * using the "pNext" member) referenced by the "step_list" member of the
12243  * associated struct Trigger instance. The first element of the linked list is
12244  * the first step of the trigger-program.
12245  *
12246  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
12247  * "SELECT" statement. The meanings of the other members is determined by the
12248  * value of "op" as follows:
12249  *
12250  * (op == TK_INSERT)
12251  * orconf    -> stores the ON CONFLICT algorithm
12252  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
12253  *              this stores a pointer to the SELECT statement. Otherwise NULL.
12254  * target    -> A token holding the quoted name of the table to insert into.
12255  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
12256  *              this stores values to be inserted. Otherwise NULL.
12257  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
12258  *              statement, then this stores the column-names to be
12259  *              inserted into.
12260  *
12261  * (op == TK_DELETE)
12262  * target    -> A token holding the quoted name of the table to delete from.
12263  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
12264  *              Otherwise NULL.
12265  *
12266  * (op == TK_UPDATE)
12267  * target    -> A token holding the quoted name of the table to update rows of.
12268  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
12269  *              Otherwise NULL.
12270  * pExprList -> A list of the columns to update and the expressions to update
12271  *              them to. See sqlite3Update() documentation of "pChanges"
12272  *              argument.
12273  *
12274  */
12275 struct TriggerStep {
12276   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
12277   u8 orconf;           /* OE_Rollback etc. */
12278   Trigger *pTrig;      /* The trigger that this step is a part of */
12279   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
12280   Token target;        /* Target table for DELETE, UPDATE, INSERT */
12281   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
12282   ExprList *pExprList; /* SET clause for UPDATE. */
12283   IdList *pIdList;     /* Column names for INSERT */
12284   TriggerStep *pNext;  /* Next in the link-list */
12285   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
12286 };
12287 
12288 /*
12289 ** The following structure contains information used by the sqliteFix...
12290 ** routines as they walk the parse tree to make database references
12291 ** explicit.
12292 */
12293 typedef struct DbFixer DbFixer;
12294 struct DbFixer {
12295   Parse *pParse;      /* The parsing context.  Error messages written here */
12296   Schema *pSchema;    /* Fix items to this schema */
12297   int bVarOnly;       /* Check for variable references only */
12298   const char *zDb;    /* Make sure all objects are contained in this database */
12299   const char *zType;  /* Type of the container - used for error messages */
12300   const Token *pName; /* Name of the container - used for error messages */
12301 };
12302 
12303 /*
12304 ** An objected used to accumulate the text of a string where we
12305 ** do not necessarily know how big the string will be in the end.
12306 */
12307 struct StrAccum {
12308   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
12309   char *zBase;         /* A base allocation.  Not from malloc. */
12310   char *zText;         /* The string collected so far */
12311   int  nChar;          /* Length of the string so far */
12312   int  nAlloc;         /* Amount of space allocated in zText */
12313   int  mxAlloc;        /* Maximum allowed string length */
12314   u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
12315   u8   accError;       /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
12316 };
12317 #define STRACCUM_NOMEM   1
12318 #define STRACCUM_TOOBIG  2
12319 
12320 /*
12321 ** A pointer to this structure is used to communicate information
12322 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
12323 */
12324 typedef struct {
12325   sqlite3 *db;        /* The database being initialized */
12326   char **pzErrMsg;    /* Error message stored here */
12327   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
12328   int rc;             /* Result code stored here */
12329 } InitData;
12330 
12331 /*
12332 ** Structure containing global configuration data for the SQLite library.
12333 **
12334 ** This structure also contains some state information.
12335 */
12336 struct Sqlite3Config {
12337   int bMemstat;                     /* True to enable memory status */
12338   int bCoreMutex;                   /* True to enable core mutexing */
12339   int bFullMutex;                   /* True to enable full mutexing */
12340   int bOpenUri;                     /* True to interpret filenames as URIs */
12341   int bUseCis;                      /* Use covering indices for full-scans */
12342   int mxStrlen;                     /* Maximum string length */
12343   int neverCorrupt;                 /* Database is always well-formed */
12344   int szLookaside;                  /* Default lookaside buffer size */
12345   int nLookaside;                   /* Default lookaside buffer count */
12346   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
12347   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
12348   sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
12349   void *pHeap;                      /* Heap storage space */
12350   int nHeap;                        /* Size of pHeap[] */
12351   int mnReq, mxReq;                 /* Min and max heap requests sizes */
12352   sqlite3_int64 szMmap;             /* mmap() space per open file */
12353   sqlite3_int64 mxMmap;             /* Maximum value for szMmap */
12354   void *pScratch;                   /* Scratch memory */
12355   int szScratch;                    /* Size of each scratch buffer */
12356   int nScratch;                     /* Number of scratch buffers */
12357   void *pPage;                      /* Page cache memory */
12358   int szPage;                       /* Size of each page in pPage[] */
12359   int nPage;                        /* Number of pages in pPage[] */
12360   int mxParserStack;                /* maximum depth of the parser stack */
12361   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
12362   /* The above might be initialized to non-zero.  The following need to always
12363   ** initially be zero, however. */
12364   int isInit;                       /* True after initialization has finished */
12365   int inProgress;                   /* True while initialization in progress */
12366   int isMutexInit;                  /* True after mutexes are initialized */
12367   int isMallocInit;                 /* True after malloc is initialized */
12368   int isPCacheInit;                 /* True after malloc is initialized */
12369   int nRefInitMutex;                /* Number of users of pInitMutex */
12370   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
12371   void (*xLog)(void*,int,const char*); /* Function for logging */
12372   void *pLogArg;                       /* First argument to xLog() */
12373 #ifdef SQLITE_ENABLE_SQLLOG
12374   void(*xSqllog)(void*,sqlite3*,const char*, int);
12375   void *pSqllogArg;
12376 #endif
12377 #ifdef SQLITE_VDBE_COVERAGE
12378   /* The following callback (if not NULL) is invoked on every VDBE branch
12379   ** operation.  Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
12380   */
12381   void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx);  /* Callback */
12382   void *pVdbeBranchArg;                                     /* 1st argument */
12383 #endif
12384 #ifndef SQLITE_OMIT_BUILTIN_TEST
12385   int (*xTestCallback)(int);        /* Invoked by sqlite3FaultSim() */
12386 #endif
12387   int bLocaltimeFault;              /* True to fail localtime() calls */
12388 };
12389 
12390 /*
12391 ** This macro is used inside of assert() statements to indicate that
12392 ** the assert is only valid on a well-formed database.  Instead of:
12393 **
12394 **     assert( X );
12395 **
12396 ** One writes:
12397 **
12398 **     assert( X || CORRUPT_DB );
12399 **
12400 ** CORRUPT_DB is true during normal operation.  CORRUPT_DB does not indicate
12401 ** that the database is definitely corrupt, only that it might be corrupt.
12402 ** For most test cases, CORRUPT_DB is set to false using a special
12403 ** sqlite3_test_control().  This enables assert() statements to prove
12404 ** things that are always true for well-formed databases.
12405 */
12406 #define CORRUPT_DB  (sqlite3Config.neverCorrupt==0)
12407 
12408 /*
12409 ** Context pointer passed down through the tree-walk.
12410 */
12411 struct Walker {
12412   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
12413   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
12414   void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
12415   Parse *pParse;                            /* Parser context.  */
12416   int walkerDepth;                          /* Number of subqueries */
12417   union {                                   /* Extra data for callback */
12418     NameContext *pNC;                          /* Naming context */
12419     int i;                                     /* Integer value */
12420     SrcList *pSrcList;                         /* FROM clause */
12421     struct SrcCount *pSrcCount;                /* Counting column references */
12422   } u;
12423 };
12424 
12425 /* Forward declarations */
12426 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
12427 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
12428 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
12429 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
12430 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
12431 
12432 /*
12433 ** Return code from the parse-tree walking primitives and their
12434 ** callbacks.
12435 */
12436 #define WRC_Continue    0   /* Continue down into children */
12437 #define WRC_Prune       1   /* Omit children but continue walking siblings */
12438 #define WRC_Abort       2   /* Abandon the tree walk */
12439 
12440 /*
12441 ** An instance of this structure represents a set of one or more CTEs
12442 ** (common table expressions) created by a single WITH clause.
12443 */
12444 struct With {
12445   int nCte;                       /* Number of CTEs in the WITH clause */
12446   With *pOuter;                   /* Containing WITH clause, or NULL */
12447   struct Cte {                    /* For each CTE in the WITH clause.... */
12448     char *zName;                    /* Name of this CTE */
12449     ExprList *pCols;                /* List of explicit column names, or NULL */
12450     Select *pSelect;                /* The definition of this CTE */
12451     const char *zErr;               /* Error message for circular references */
12452   } a[1];
12453 };
12454 
12455 #ifdef SQLITE_DEBUG
12456 /*
12457 ** An instance of the TreeView object is used for printing the content of
12458 ** data structures on sqlite3DebugPrintf() using a tree-like view.
12459 */
12460 struct TreeView {
12461   int iLevel;             /* Which level of the tree we are on */
12462   u8  bLine[100];         /* Draw vertical in column i if bLine[i] is true */
12463 };
12464 #endif /* SQLITE_DEBUG */
12465 
12466 /*
12467 ** Assuming zIn points to the first byte of a UTF-8 character,
12468 ** advance zIn to point to the first byte of the next UTF-8 character.
12469 */
12470 #define SQLITE_SKIP_UTF8(zIn) {                        \
12471   if( (*(zIn++))>=0xc0 ){                              \
12472     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
12473   }                                                    \
12474 }
12475 
12476 /*
12477 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
12478 ** the same name but without the _BKPT suffix.  These macros invoke
12479 ** routines that report the line-number on which the error originated
12480 ** using sqlite3_log().  The routines also provide a convenient place
12481 ** to set a debugger breakpoint.
12482 */
12483 SQLITE_PRIVATE int sqlite3CorruptError(int);
12484 SQLITE_PRIVATE int sqlite3MisuseError(int);
12485 SQLITE_PRIVATE int sqlite3CantopenError(int);
12486 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
12487 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
12488 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
12489 
12490 
12491 /*
12492 ** FTS4 is really an extension for FTS3.  It is enabled using the
12493 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also call
12494 ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
12495 */
12496 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
12497 # define SQLITE_ENABLE_FTS3
12498 #endif
12499 
12500 /*
12501 ** The ctype.h header is needed for non-ASCII systems.  It is also
12502 ** needed by FTS3 when FTS3 is included in the amalgamation.
12503 */
12504 #if !defined(SQLITE_ASCII) || \
12505     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
12506 # include <ctype.h>
12507 #endif
12508 
12509 /*
12510 ** The following macros mimic the standard library functions toupper(),
12511 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
12512 ** sqlite versions only work for ASCII characters, regardless of locale.
12513 */
12514 #ifdef SQLITE_ASCII
12515 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
12516 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
12517 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
12518 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
12519 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
12520 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
12521 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
12522 #else
12523 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
12524 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
12525 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
12526 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
12527 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
12528 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
12529 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
12530 #endif
12531 SQLITE_PRIVATE int sqlite3IsIdChar(u8);
12532 
12533 /*
12534 ** Internal function prototypes
12535 */
12536 #define sqlite3StrICmp sqlite3_stricmp
12537 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
12538 #define sqlite3StrNICmp sqlite3_strnicmp
12539 
12540 SQLITE_PRIVATE int sqlite3MallocInit(void);
12541 SQLITE_PRIVATE void sqlite3MallocEnd(void);
12542 SQLITE_PRIVATE void *sqlite3Malloc(u64);
12543 SQLITE_PRIVATE void *sqlite3MallocZero(u64);
12544 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
12545 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
12546 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
12547 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
12548 SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
12549 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
12550 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
12551 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
12552 SQLITE_PRIVATE int sqlite3MallocSize(void*);
12553 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
12554 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
12555 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
12556 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
12557 SQLITE_PRIVATE void sqlite3PageFree(void*);
12558 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
12559 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
12560 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
12561 
12562 /*
12563 ** On systems with ample stack space and that support alloca(), make
12564 ** use of alloca() to obtain space for large automatic objects.  By default,
12565 ** obtain space from malloc().
12566 **
12567 ** The alloca() routine never returns NULL.  This will cause code paths
12568 ** that deal with sqlite3StackAlloc() failures to be unreachable.
12569 */
12570 #ifdef SQLITE_USE_ALLOCA
12571 # define sqlite3StackAllocRaw(D,N)   alloca(N)
12572 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
12573 # define sqlite3StackFree(D,P)
12574 #else
12575 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
12576 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
12577 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
12578 #endif
12579 
12580 #ifdef SQLITE_ENABLE_MEMSYS3
12581 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
12582 #endif
12583 #ifdef SQLITE_ENABLE_MEMSYS5
12584 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
12585 #endif
12586 
12587 
12588 #ifndef SQLITE_MUTEX_OMIT
12589 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
12590 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
12591 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
12592 SQLITE_PRIVATE   int sqlite3MutexInit(void);
12593 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
12594 #endif
12595 
12596 SQLITE_PRIVATE int sqlite3StatusValue(int);
12597 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
12598 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
12599 
12600 #ifndef SQLITE_OMIT_FLOATING_POINT
12601 SQLITE_PRIVATE   int sqlite3IsNaN(double);
12602 #else
12603 # define sqlite3IsNaN(X)  0
12604 #endif
12605 
12606 /*
12607 ** An instance of the following structure holds information about SQL
12608 ** functions arguments that are the parameters to the printf() function.
12609 */
12610 struct PrintfArguments {
12611   int nArg;                /* Total number of arguments */
12612   int nUsed;               /* Number of arguments used so far */
12613   sqlite3_value **apArg;   /* The argument values */
12614 };
12615 
12616 #define SQLITE_PRINTF_INTERNAL 0x01
12617 #define SQLITE_PRINTF_SQLFUNC  0x02
12618 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, u32, const char*, va_list);
12619 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, u32, const char*, ...);
12620 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
12621 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
12622 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
12623 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
12624 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
12625 #endif
12626 #if defined(SQLITE_TEST)
12627 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
12628 #endif
12629 
12630 #if defined(SQLITE_DEBUG)
12631 SQLITE_PRIVATE   TreeView *sqlite3TreeViewPush(TreeView*,u8);
12632 SQLITE_PRIVATE   void sqlite3TreeViewPop(TreeView*);
12633 SQLITE_PRIVATE   void sqlite3TreeViewLine(TreeView*, const char*, ...);
12634 SQLITE_PRIVATE   void sqlite3TreeViewItem(TreeView*, const char*, u8);
12635 SQLITE_PRIVATE   void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
12636 SQLITE_PRIVATE   void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
12637 SQLITE_PRIVATE   void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
12638 #endif
12639 
12640 
12641 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
12642 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
12643 SQLITE_PRIVATE int sqlite3Dequote(char*);
12644 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
12645 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
12646 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
12647 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
12648 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
12649 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
12650 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
12651 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
12652 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
12653 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
12654 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
12655 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
12656 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
12657 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
12658 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
12659 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
12660 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
12661 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
12662 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
12663 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
12664 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
12665 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
12666 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
12667 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
12668 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
12669 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
12670 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
12671 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
12672 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
12673 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
12674 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
12675 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
12676 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
12677 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
12678 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
12679 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
12680 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
12681 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
12682 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
12683 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
12684 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
12685 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
12686                     sqlite3_vfs**,char**,char **);
12687 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
12688 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
12689 
12690 #ifdef SQLITE_OMIT_BUILTIN_TEST
12691 # define sqlite3FaultSim(X) SQLITE_OK
12692 #else
12693 SQLITE_PRIVATE   int sqlite3FaultSim(int);
12694 #endif
12695 
12696 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
12697 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
12698 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
12699 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
12700 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
12701 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
12702 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
12703 
12704 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
12705 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
12706 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
12707 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
12708 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
12709 
12710 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
12711 
12712 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
12713 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
12714 #else
12715 # define sqlite3ViewGetColumnNames(A,B) 0
12716 #endif
12717 
12718 #if SQLITE_MAX_ATTACHED>30
12719 SQLITE_PRIVATE   int sqlite3DbMaskAllZero(yDbMask);
12720 #endif
12721 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
12722 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
12723 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
12724 #ifndef SQLITE_OMIT_AUTOINCREMENT
12725 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
12726 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
12727 #else
12728 # define sqlite3AutoincrementBegin(X)
12729 # define sqlite3AutoincrementEnd(X)
12730 #endif
12731 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
12732 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
12733 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
12734 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
12735 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
12736 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
12737 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
12738                                       Token*, Select*, Expr*, IdList*);
12739 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
12740 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
12741 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
12742 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
12743 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
12744 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
12745 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
12746 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
12747                           Expr*, int, int);
12748 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
12749 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
12750 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
12751                          Expr*,ExprList*,u16,Expr*,Expr*);
12752 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
12753 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
12754 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
12755 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
12756 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
12757 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
12758 #endif
12759 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
12760 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
12761 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
12762 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
12763 SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
12764 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
12765 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
12766 SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
12767 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
12768 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
12769 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
12770 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
12771 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
12772 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
12773 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
12774 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
12775 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
12776 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
12777 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
12778 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
12779 SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
12780 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
12781 SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
12782 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
12783 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
12784 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
12785 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, u8);
12786 #define SQLITE_ECEL_DUP      0x01  /* Deep, not shallow copies */
12787 #define SQLITE_ECEL_FACTOR   0x02  /* Factor out constant terms */
12788 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
12789 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
12790 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
12791 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
12792 SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
12793 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
12794 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
12795 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
12796 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
12797 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
12798 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
12799 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
12800 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
12801 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
12802 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
12803 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
12804 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
12805 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
12806 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
12807 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
12808 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
12809 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
12810 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
12811 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
12812 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
12813 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
12814 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
12815 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
12816 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
12817 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
12818 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
12819 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
12820 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
12821 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
12822 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
12823 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
12824 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8);
12825 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*);
12826 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
12827 SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
12828 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
12829                                      u8,u8,int,int*);
12830 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
12831 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int, u8*, int*, int*);
12832 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
12833 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
12834 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
12835 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
12836 SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
12837 SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
12838 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
12839 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
12840 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
12841 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
12842 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
12843 #if SELECTTRACE_ENABLED
12844 SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
12845 #else
12846 # define sqlite3SelectSetName(A,B)
12847 #endif
12848 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
12849 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
12850 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
12851 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
12852 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
12853 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
12854 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
12855 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
12856 
12857 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
12858 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
12859 #endif
12860 
12861 #ifndef SQLITE_OMIT_TRIGGER
12862 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
12863                            Expr*,int, int);
12864 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
12865 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
12866 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
12867 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
12868 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
12869 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
12870                             int, int, int);
12871 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
12872   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
12873 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
12874 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
12875 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
12876                                         Select*,u8);
12877 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
12878 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
12879 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
12880 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
12881 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
12882 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
12883 #else
12884 # define sqlite3TriggersExist(B,C,D,E,F) 0
12885 # define sqlite3DeleteTrigger(A,B)
12886 # define sqlite3DropTriggerPtr(A,B)
12887 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
12888 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
12889 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
12890 # define sqlite3TriggerList(X, Y) 0
12891 # define sqlite3ParseToplevel(p) p
12892 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
12893 #endif
12894 
12895 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
12896 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
12897 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
12898 #ifndef SQLITE_OMIT_AUTHORIZATION
12899 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
12900 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
12901 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
12902 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
12903 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
12904 #else
12905 # define sqlite3AuthRead(a,b,c,d)
12906 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
12907 # define sqlite3AuthContextPush(a,b,c)
12908 # define sqlite3AuthContextPop(a)  ((void)(a))
12909 #endif
12910 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
12911 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
12912 SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
12913 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
12914 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
12915 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
12916 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
12917 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
12918 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
12919 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
12920 SQLITE_PRIVATE int sqlite3Atoi(const char*);
12921 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
12922 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
12923 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
12924 SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
12925 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
12926 #ifndef SQLITE_OMIT_VIRTUALTABLE
12927 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
12928 #endif
12929 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
12930 
12931 /*
12932 ** Routines to read and write variable-length integers.  These used to
12933 ** be defined locally, but now we use the varint routines in the util.c
12934 ** file.
12935 */
12936 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
12937 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
12938 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
12939 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
12940 
12941 /*
12942 ** The common case is for a varint to be a single byte.  They following
12943 ** macros handle the common case without a procedure call, but then call
12944 ** the procedure for larger varints.
12945 */
12946 #define getVarint32(A,B)  \
12947   (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
12948 #define putVarint32(A,B)  \
12949   (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
12950   sqlite3PutVarint((A),(B)))
12951 #define getVarint    sqlite3GetVarint
12952 #define putVarint    sqlite3PutVarint
12953 
12954 
12955 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
12956 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
12957 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
12958 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
12959 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
12960 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
12961 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
12962 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
12963 SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
12964 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
12965 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
12966 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
12967 
12968 #if defined(SQLITE_TEST)
12969 SQLITE_PRIVATE const char *sqlite3ErrName(int);
12970 #endif
12971 
12972 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
12973 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
12974 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
12975 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
12976 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
12977 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*);
12978 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
12979 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
12980 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
12981 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
12982 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
12983 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
12984 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
12985 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
12986 SQLITE_PRIVATE int sqlite3AbsInt32(int);
12987 #ifdef SQLITE_ENABLE_8_3_NAMES
12988 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
12989 #else
12990 # define sqlite3FileSuffix3(X,Y)
12991 #endif
12992 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
12993 
12994 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
12995 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
12996 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
12997                         void(*)(void*));
12998 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
12999 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
13000 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
13001 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
13002 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
13003 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
13004 #ifndef SQLITE_AMALGAMATION
13005 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
13006 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
13007 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
13008 SQLITE_PRIVATE const Token sqlite3IntTokens[];
13009 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
13010 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
13011 #ifndef SQLITE_OMIT_WSD
13012 SQLITE_PRIVATE int sqlite3PendingByte;
13013 #endif
13014 #endif
13015 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
13016 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
13017 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
13018 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
13019 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
13020 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
13021 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
13022 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
13023 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
13024 SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
13025 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
13026 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
13027 SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
13028 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
13029 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
13030 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
13031 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
13032 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
13033 SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
13034 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
13035 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
13036 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
13037 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
13038 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
13039 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
13040 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
13041 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
13042 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
13043 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
13044 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
13045 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
13046 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
13047 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
13048 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
13049 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
13050 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
13051 #ifdef SQLITE_DEBUG
13052 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
13053 #endif
13054 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
13055   void (*)(sqlite3_context*,int,sqlite3_value **),
13056   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
13057   FuncDestructor *pDestructor
13058 );
13059 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
13060 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
13061 
13062 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
13063 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
13064 SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
13065 SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
13066 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
13067 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
13068 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
13069 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
13070 
13071 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
13072 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
13073 
13074 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
13075 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
13076 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
13077 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
13078 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
13079 SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
13080 #endif
13081 
13082 /*
13083 ** The interface to the LEMON-generated parser
13084 */
13085 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
13086 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
13087 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
13088 #ifdef YYTRACKMAXSTACKDEPTH
13089 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
13090 #endif
13091 
13092 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
13093 #ifndef SQLITE_OMIT_LOAD_EXTENSION
13094 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
13095 #else
13096 # define sqlite3CloseExtensions(X)
13097 #endif
13098 
13099 #ifndef SQLITE_OMIT_SHARED_CACHE
13100 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
13101 #else
13102   #define sqlite3TableLock(v,w,x,y,z)
13103 #endif
13104 
13105 #ifdef SQLITE_TEST
13106 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
13107 #endif
13108 
13109 #ifdef SQLITE_OMIT_VIRTUALTABLE
13110 #  define sqlite3VtabClear(Y)
13111 #  define sqlite3VtabSync(X,Y) SQLITE_OK
13112 #  define sqlite3VtabRollback(X)
13113 #  define sqlite3VtabCommit(X)
13114 #  define sqlite3VtabInSync(db) 0
13115 #  define sqlite3VtabLock(X)
13116 #  define sqlite3VtabUnlock(X)
13117 #  define sqlite3VtabUnlockList(X)
13118 #  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
13119 #  define sqlite3GetVTable(X,Y)  ((VTable*)0)
13120 #else
13121 SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
13122 SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
13123 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, Vdbe*);
13124 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
13125 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
13126 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
13127 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
13128 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
13129 SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
13130 SQLITE_PRIVATE    void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
13131 SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
13132 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
13133 #endif
13134 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
13135 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
13136 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
13137 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
13138 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
13139 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
13140 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
13141 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
13142 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
13143 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
13144 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
13145 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
13146 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
13147 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
13148 SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
13149 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
13150 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
13151 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
13152 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
13153 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
13154 #ifndef SQLITE_OMIT_WAL
13155 SQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
13156 SQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
13157 #endif
13158 #ifndef SQLITE_OMIT_CTE
13159 SQLITE_PRIVATE   With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
13160 SQLITE_PRIVATE   void sqlite3WithDelete(sqlite3*,With*);
13161 SQLITE_PRIVATE   void sqlite3WithPush(Parse*, With*, u8);
13162 #else
13163 #define sqlite3WithPush(x,y,z)
13164 #define sqlite3WithDelete(x,y)
13165 #endif
13166 
13167 /* Declarations for functions in fkey.c. All of these are replaced by
13168 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
13169 ** key functionality is available. If OMIT_TRIGGER is defined but
13170 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
13171 ** this case foreign keys are parsed, but no other functionality is
13172 ** provided (enforcement of FK constraints requires the triggers sub-system).
13173 */
13174 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
13175 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
13176 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
13177 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
13178 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
13179 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
13180 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
13181 #else
13182   #define sqlite3FkActions(a,b,c,d,e,f)
13183   #define sqlite3FkCheck(a,b,c,d,e,f)
13184   #define sqlite3FkDropTable(a,b,c)
13185   #define sqlite3FkOldmask(a,b)         0
13186   #define sqlite3FkRequired(a,b,c,d)    0
13187 #endif
13188 #ifndef SQLITE_OMIT_FOREIGN_KEY
13189 SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
13190 SQLITE_PRIVATE   int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
13191 #else
13192   #define sqlite3FkDelete(a,b)
13193   #define sqlite3FkLocateIndex(a,b,c,d,e)
13194 #endif
13195 
13196 
13197 /*
13198 ** Available fault injectors.  Should be numbered beginning with 0.
13199 */
13200 #define SQLITE_FAULTINJECTOR_MALLOC     0
13201 #define SQLITE_FAULTINJECTOR_COUNT      1
13202 
13203 /*
13204 ** The interface to the code in fault.c used for identifying "benign"
13205 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
13206 ** is not defined.
13207 */
13208 #ifndef SQLITE_OMIT_BUILTIN_TEST
13209 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
13210 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
13211 #else
13212   #define sqlite3BeginBenignMalloc()
13213   #define sqlite3EndBenignMalloc()
13214 #endif
13215 
13216 /*
13217 ** Allowed return values from sqlite3FindInIndex()
13218 */
13219 #define IN_INDEX_ROWID        1   /* Search the rowid of the table */
13220 #define IN_INDEX_EPH          2   /* Search an ephemeral b-tree */
13221 #define IN_INDEX_INDEX_ASC    3   /* Existing index ASCENDING */
13222 #define IN_INDEX_INDEX_DESC   4   /* Existing index DESCENDING */
13223 #define IN_INDEX_NOOP         5   /* No table available. Use comparisons */
13224 /*
13225 ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
13226 */
13227 #define IN_INDEX_NOOP_OK     0x0001  /* OK to return IN_INDEX_NOOP */
13228 #define IN_INDEX_MEMBERSHIP  0x0002  /* IN operator used for membership test */
13229 #define IN_INDEX_LOOP        0x0004  /* IN operator used as a loop */
13230 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*);
13231 
13232 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
13233 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
13234 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
13235 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
13236 SQLITE_PRIVATE   int sqlite3JournalExists(sqlite3_file *p);
13237 #else
13238   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
13239   #define sqlite3JournalExists(p) 1
13240 #endif
13241 
13242 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
13243 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
13244 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
13245 
13246 #if SQLITE_MAX_EXPR_DEPTH>0
13247 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
13248 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
13249 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
13250 #else
13251   #define sqlite3ExprSetHeight(x,y)
13252   #define sqlite3SelectExprHeight(x) 0
13253   #define sqlite3ExprCheckHeight(x,y)
13254 #endif
13255 
13256 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
13257 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
13258 
13259 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
13260 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
13261 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
13262 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
13263 #else
13264   #define sqlite3ConnectionBlocked(x,y)
13265   #define sqlite3ConnectionUnlocked(x)
13266   #define sqlite3ConnectionClosed(x)
13267 #endif
13268 
13269 #ifdef SQLITE_DEBUG
13270 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
13271 #endif
13272 
13273 /*
13274 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
13275 ** sqlite3IoTrace is a pointer to a printf-like routine used to
13276 ** print I/O tracing messages.
13277 */
13278 #ifdef SQLITE_ENABLE_IOTRACE
13279 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
13280 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
13281 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
13282 #else
13283 # define IOTRACE(A)
13284 # define sqlite3VdbeIOTraceSql(X)
13285 #endif
13286 
13287 /*
13288 ** These routines are available for the mem2.c debugging memory allocator
13289 ** only.  They are used to verify that different "types" of memory
13290 ** allocations are properly tracked by the system.
13291 **
13292 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
13293 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
13294 ** a single bit set.
13295 **
13296 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
13297 ** argument match the type set by the previous sqlite3MemdebugSetType().
13298 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
13299 **
13300 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
13301 ** argument match the type set by the previous sqlite3MemdebugSetType().
13302 **
13303 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
13304 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
13305 ** it might have been allocated by lookaside, except the allocation was
13306 ** too large or lookaside was already full.  It is important to verify
13307 ** that allocations that might have been satisfied by lookaside are not
13308 ** passed back to non-lookaside free() routines.  Asserts such as the
13309 ** example above are placed on the non-lookaside free() routines to verify
13310 ** this constraint.
13311 **
13312 ** All of this is no-op for a production build.  It only comes into
13313 ** play when the SQLITE_MEMDEBUG compile-time option is used.
13314 */
13315 #ifdef SQLITE_MEMDEBUG
13316 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
13317 SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
13318 SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
13319 #else
13320 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
13321 # define sqlite3MemdebugHasType(X,Y)  1
13322 # define sqlite3MemdebugNoType(X,Y)   1
13323 #endif
13324 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
13325 #define MEMTYPE_LOOKASIDE  0x02  /* Heap that might have been lookaside */
13326 #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
13327 #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
13328 
13329 /*
13330 ** Threading interface
13331 */
13332 #if SQLITE_MAX_WORKER_THREADS>0
13333 SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
13334 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
13335 #endif
13336 
13337 #endif /* _SQLITEINT_H_ */
13338 
13339 /************** End of sqliteInt.h *******************************************/
13340 /************** Begin file global.c ******************************************/
13341 /*
13342 ** 2008 June 13
13343 **
13344 ** The author disclaims copyright to this source code.  In place of
13345 ** a legal notice, here is a blessing:
13346 **
13347 **    May you do good and not evil.
13348 **    May you find forgiveness for yourself and forgive others.
13349 **    May you share freely, never taking more than you give.
13350 **
13351 *************************************************************************
13352 **
13353 ** This file contains definitions of global variables and constants.
13354 */
13355 
13356 /* An array to map all upper-case characters into their corresponding
13357 ** lower-case character.
13358 **
13359 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
13360 ** handle case conversions for the UTF character set since the tables
13361 ** involved are nearly as big or bigger than SQLite itself.
13362 */
13363 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
13364 #ifdef SQLITE_ASCII
13365       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
13366      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
13367      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
13368      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
13369     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
13370     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
13371     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
13372     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
13373     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
13374     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
13375     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
13376     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
13377     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
13378     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
13379     252,253,254,255
13380 #endif
13381 #ifdef SQLITE_EBCDIC
13382       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
13383      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
13384      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
13385      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
13386      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
13387      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
13388      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
13389     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
13390     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
13391     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
13392     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
13393     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
13394     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
13395     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
13396     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
13397     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
13398 #endif
13399 };
13400 
13401 /*
13402 ** The following 256 byte lookup table is used to support SQLites built-in
13403 ** equivalents to the following standard library functions:
13404 **
13405 **   isspace()                        0x01
13406 **   isalpha()                        0x02
13407 **   isdigit()                        0x04
13408 **   isalnum()                        0x06
13409 **   isxdigit()                       0x08
13410 **   toupper()                        0x20
13411 **   SQLite identifier character      0x40
13412 **
13413 ** Bit 0x20 is set if the mapped character requires translation to upper
13414 ** case. i.e. if the character is a lower-case ASCII character.
13415 ** If x is a lower-case ASCII character, then its upper-case equivalent
13416 ** is (x - 0x20). Therefore toupper() can be implemented as:
13417 **
13418 **   (x & ~(map[x]&0x20))
13419 **
13420 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
13421 ** array. tolower() is used more often than toupper() by SQLite.
13422 **
13423 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
13424 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
13425 ** non-ASCII UTF character. Hence the test for whether or not a character is
13426 ** part of an identifier is 0x46.
13427 **
13428 ** SQLite's versions are identical to the standard versions assuming a
13429 ** locale of "C". They are implemented as macros in sqliteInt.h.
13430 */
13431 #ifdef SQLITE_ASCII
13432 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
13433   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
13434   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
13435   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
13436   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
13437   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
13438   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
13439   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
13440   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
13441 
13442   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
13443   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
13444   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
13445   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
13446   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
13447   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
13448   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
13449   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
13450 
13451   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
13452   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
13453   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
13454   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
13455   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
13456   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
13457   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
13458   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
13459 
13460   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
13461   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
13462   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
13463   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
13464   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
13465   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
13466   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
13467   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
13468 };
13469 #endif
13470 
13471 /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
13472 ** compatibility for legacy applications, the URI filename capability is
13473 ** disabled by default.
13474 **
13475 ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
13476 ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
13477 */
13478 #ifndef SQLITE_USE_URI
13479 # define  SQLITE_USE_URI 0
13480 #endif
13481 
13482 #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
13483 # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
13484 #endif
13485 
13486 /*
13487 ** The following singleton contains the global configuration for
13488 ** the SQLite library.
13489 */
13490 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
13491    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
13492    1,                         /* bCoreMutex */
13493    SQLITE_THREADSAFE==1,      /* bFullMutex */
13494    SQLITE_USE_URI,            /* bOpenUri */
13495    SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
13496    0x7ffffffe,                /* mxStrlen */
13497    0,                         /* neverCorrupt */
13498    128,                       /* szLookaside */
13499    500,                       /* nLookaside */
13500    {0,0,0,0,0,0,0,0},         /* m */
13501    {0,0,0,0,0,0,0,0,0},       /* mutex */
13502    {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
13503    (void*)0,                  /* pHeap */
13504    0,                         /* nHeap */
13505    0, 0,                      /* mnHeap, mxHeap */
13506    SQLITE_DEFAULT_MMAP_SIZE,  /* szMmap */
13507    SQLITE_MAX_MMAP_SIZE,      /* mxMmap */
13508    (void*)0,                  /* pScratch */
13509    0,                         /* szScratch */
13510    0,                         /* nScratch */
13511    (void*)0,                  /* pPage */
13512    0,                         /* szPage */
13513    0,                         /* nPage */
13514    0,                         /* mxParserStack */
13515    0,                         /* sharedCacheEnabled */
13516    /* All the rest should always be initialized to zero */
13517    0,                         /* isInit */
13518    0,                         /* inProgress */
13519    0,                         /* isMutexInit */
13520    0,                         /* isMallocInit */
13521    0,                         /* isPCacheInit */
13522    0,                         /* nRefInitMutex */
13523    0,                         /* pInitMutex */
13524    0,                         /* xLog */
13525    0,                         /* pLogArg */
13526 #ifdef SQLITE_ENABLE_SQLLOG
13527    0,                         /* xSqllog */
13528    0,                         /* pSqllogArg */
13529 #endif
13530 #ifdef SQLITE_VDBE_COVERAGE
13531    0,                         /* xVdbeBranch */
13532    0,                         /* pVbeBranchArg */
13533 #endif
13534 #ifndef SQLITE_OMIT_BUILTIN_TEST
13535    0,                         /* xTestCallback */
13536 #endif
13537    0                          /* bLocaltimeFault */
13538 };
13539 
13540 /*
13541 ** Hash table for global functions - functions common to all
13542 ** database connections.  After initialization, this table is
13543 ** read-only.
13544 */
13545 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
13546 
13547 /*
13548 ** Constant tokens for values 0 and 1.
13549 */
13550 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
13551    { "0", 1 },
13552    { "1", 1 }
13553 };
13554 
13555 
13556 /*
13557 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
13558 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
13559 ** the database page that contains the pending byte.  It never attempts
13560 ** to read or write that page.  The pending byte page is set assign
13561 ** for use by the VFS layers as space for managing file locks.
13562 **
13563 ** During testing, it is often desirable to move the pending byte to
13564 ** a different position in the file.  This allows code that has to
13565 ** deal with the pending byte to run on files that are much smaller
13566 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
13567 ** move the pending byte.
13568 **
13569 ** IMPORTANT:  Changing the pending byte to any value other than
13570 ** 0x40000000 results in an incompatible database file format!
13571 ** Changing the pending byte during operating results in undefined
13572 ** and dileterious behavior.
13573 */
13574 #ifndef SQLITE_OMIT_WSD
13575 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
13576 #endif
13577 
13578 /*
13579 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
13580 ** created by mkopcodeh.awk during compilation.  Data is obtained
13581 ** from the comments following the "case OP_xxxx:" statements in
13582 ** the vdbe.c file.
13583 */
13584 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
13585 
13586 /************** End of global.c **********************************************/
13587 /************** Begin file ctime.c *******************************************/
13588 /*
13589 ** 2010 February 23
13590 **
13591 ** The author disclaims copyright to this source code.  In place of
13592 ** a legal notice, here is a blessing:
13593 **
13594 **    May you do good and not evil.
13595 **    May you find forgiveness for yourself and forgive others.
13596 **    May you share freely, never taking more than you give.
13597 **
13598 *************************************************************************
13599 **
13600 ** This file implements routines used to report what compile-time options
13601 ** SQLite was built with.
13602 */
13603 
13604 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
13605 
13606 
13607 /*
13608 ** An array of names of all compile-time options.  This array should
13609 ** be sorted A-Z.
13610 **
13611 ** This array looks large, but in a typical installation actually uses
13612 ** only a handful of compile-time options, so most times this array is usually
13613 ** rather short and uses little memory space.
13614 */
13615 static const char * const azCompileOpt[] = {
13616 
13617 /* These macros are provided to "stringify" the value of the define
13618 ** for those options in which the value is meaningful. */
13619 #define CTIMEOPT_VAL_(opt) #opt
13620 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
13621 
13622 #ifdef SQLITE_32BIT_ROWID
13623   "32BIT_ROWID",
13624 #endif
13625 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
13626   "4_BYTE_ALIGNED_MALLOC",
13627 #endif
13628 #ifdef SQLITE_CASE_SENSITIVE_LIKE
13629   "CASE_SENSITIVE_LIKE",
13630 #endif
13631 #ifdef SQLITE_CHECK_PAGES
13632   "CHECK_PAGES",
13633 #endif
13634 #ifdef SQLITE_COVERAGE_TEST
13635   "COVERAGE_TEST",
13636 #endif
13637 #ifdef SQLITE_DEBUG
13638   "DEBUG",
13639 #endif
13640 #ifdef SQLITE_DEFAULT_LOCKING_MODE
13641   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
13642 #endif
13643 #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
13644   "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
13645 #endif
13646 #ifdef SQLITE_DISABLE_DIRSYNC
13647   "DISABLE_DIRSYNC",
13648 #endif
13649 #ifdef SQLITE_DISABLE_LFS
13650   "DISABLE_LFS",
13651 #endif
13652 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
13653   "ENABLE_ATOMIC_WRITE",
13654 #endif
13655 #ifdef SQLITE_ENABLE_CEROD
13656   "ENABLE_CEROD",
13657 #endif
13658 #ifdef SQLITE_ENABLE_COLUMN_METADATA
13659   "ENABLE_COLUMN_METADATA",
13660 #endif
13661 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
13662   "ENABLE_EXPENSIVE_ASSERT",
13663 #endif
13664 #ifdef SQLITE_ENABLE_FTS1
13665   "ENABLE_FTS1",
13666 #endif
13667 #ifdef SQLITE_ENABLE_FTS2
13668   "ENABLE_FTS2",
13669 #endif
13670 #ifdef SQLITE_ENABLE_FTS3
13671   "ENABLE_FTS3",
13672 #endif
13673 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
13674   "ENABLE_FTS3_PARENTHESIS",
13675 #endif
13676 #ifdef SQLITE_ENABLE_FTS4
13677   "ENABLE_FTS4",
13678 #endif
13679 #ifdef SQLITE_ENABLE_ICU
13680   "ENABLE_ICU",
13681 #endif
13682 #ifdef SQLITE_ENABLE_IOTRACE
13683   "ENABLE_IOTRACE",
13684 #endif
13685 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
13686   "ENABLE_LOAD_EXTENSION",
13687 #endif
13688 #ifdef SQLITE_ENABLE_LOCKING_STYLE
13689   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
13690 #endif
13691 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
13692   "ENABLE_MEMORY_MANAGEMENT",
13693 #endif
13694 #ifdef SQLITE_ENABLE_MEMSYS3
13695   "ENABLE_MEMSYS3",
13696 #endif
13697 #ifdef SQLITE_ENABLE_MEMSYS5
13698   "ENABLE_MEMSYS5",
13699 #endif
13700 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
13701   "ENABLE_OVERSIZE_CELL_CHECK",
13702 #endif
13703 #ifdef SQLITE_ENABLE_RTREE
13704   "ENABLE_RTREE",
13705 #endif
13706 #if defined(SQLITE_ENABLE_STAT4)
13707   "ENABLE_STAT4",
13708 #elif defined(SQLITE_ENABLE_STAT3)
13709   "ENABLE_STAT3",
13710 #endif
13711 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
13712   "ENABLE_UNLOCK_NOTIFY",
13713 #endif
13714 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
13715   "ENABLE_UPDATE_DELETE_LIMIT",
13716 #endif
13717 #ifdef SQLITE_HAS_CODEC
13718   "HAS_CODEC",
13719 #endif
13720 #ifdef SQLITE_HAVE_ISNAN
13721   "HAVE_ISNAN",
13722 #endif
13723 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
13724   "HOMEGROWN_RECURSIVE_MUTEX",
13725 #endif
13726 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
13727   "IGNORE_AFP_LOCK_ERRORS",
13728 #endif
13729 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
13730   "IGNORE_FLOCK_LOCK_ERRORS",
13731 #endif
13732 #ifdef SQLITE_INT64_TYPE
13733   "INT64_TYPE",
13734 #endif
13735 #ifdef SQLITE_LOCK_TRACE
13736   "LOCK_TRACE",
13737 #endif
13738 #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
13739   "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
13740 #endif
13741 #ifdef SQLITE_MAX_SCHEMA_RETRY
13742   "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
13743 #endif
13744 #ifdef SQLITE_MEMDEBUG
13745   "MEMDEBUG",
13746 #endif
13747 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
13748   "MIXED_ENDIAN_64BIT_FLOAT",
13749 #endif
13750 #ifdef SQLITE_NO_SYNC
13751   "NO_SYNC",
13752 #endif
13753 #ifdef SQLITE_OMIT_ALTERTABLE
13754   "OMIT_ALTERTABLE",
13755 #endif
13756 #ifdef SQLITE_OMIT_ANALYZE
13757   "OMIT_ANALYZE",
13758 #endif
13759 #ifdef SQLITE_OMIT_ATTACH
13760   "OMIT_ATTACH",
13761 #endif
13762 #ifdef SQLITE_OMIT_AUTHORIZATION
13763   "OMIT_AUTHORIZATION",
13764 #endif
13765 #ifdef SQLITE_OMIT_AUTOINCREMENT
13766   "OMIT_AUTOINCREMENT",
13767 #endif
13768 #ifdef SQLITE_OMIT_AUTOINIT
13769   "OMIT_AUTOINIT",
13770 #endif
13771 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
13772   "OMIT_AUTOMATIC_INDEX",
13773 #endif
13774 #ifdef SQLITE_OMIT_AUTORESET
13775   "OMIT_AUTORESET",
13776 #endif
13777 #ifdef SQLITE_OMIT_AUTOVACUUM
13778   "OMIT_AUTOVACUUM",
13779 #endif
13780 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
13781   "OMIT_BETWEEN_OPTIMIZATION",
13782 #endif
13783 #ifdef SQLITE_OMIT_BLOB_LITERAL
13784   "OMIT_BLOB_LITERAL",
13785 #endif
13786 #ifdef SQLITE_OMIT_BTREECOUNT
13787   "OMIT_BTREECOUNT",
13788 #endif
13789 #ifdef SQLITE_OMIT_BUILTIN_TEST
13790   "OMIT_BUILTIN_TEST",
13791 #endif
13792 #ifdef SQLITE_OMIT_CAST
13793   "OMIT_CAST",
13794 #endif
13795 #ifdef SQLITE_OMIT_CHECK
13796   "OMIT_CHECK",
13797 #endif
13798 #ifdef SQLITE_OMIT_COMPLETE
13799   "OMIT_COMPLETE",
13800 #endif
13801 #ifdef SQLITE_OMIT_COMPOUND_SELECT
13802   "OMIT_COMPOUND_SELECT",
13803 #endif
13804 #ifdef SQLITE_OMIT_CTE
13805   "OMIT_CTE",
13806 #endif
13807 #ifdef SQLITE_OMIT_DATETIME_FUNCS
13808   "OMIT_DATETIME_FUNCS",
13809 #endif
13810 #ifdef SQLITE_OMIT_DECLTYPE
13811   "OMIT_DECLTYPE",
13812 #endif
13813 #ifdef SQLITE_OMIT_DEPRECATED
13814   "OMIT_DEPRECATED",
13815 #endif
13816 #ifdef SQLITE_OMIT_DISKIO
13817   "OMIT_DISKIO",
13818 #endif
13819 #ifdef SQLITE_OMIT_EXPLAIN
13820   "OMIT_EXPLAIN",
13821 #endif
13822 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
13823   "OMIT_FLAG_PRAGMAS",
13824 #endif
13825 #ifdef SQLITE_OMIT_FLOATING_POINT
13826   "OMIT_FLOATING_POINT",
13827 #endif
13828 #ifdef SQLITE_OMIT_FOREIGN_KEY
13829   "OMIT_FOREIGN_KEY",
13830 #endif
13831 #ifdef SQLITE_OMIT_GET_TABLE
13832   "OMIT_GET_TABLE",
13833 #endif
13834 #ifdef SQLITE_OMIT_INCRBLOB
13835   "OMIT_INCRBLOB",
13836 #endif
13837 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
13838   "OMIT_INTEGRITY_CHECK",
13839 #endif
13840 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
13841   "OMIT_LIKE_OPTIMIZATION",
13842 #endif
13843 #ifdef SQLITE_OMIT_LOAD_EXTENSION
13844   "OMIT_LOAD_EXTENSION",
13845 #endif
13846 #ifdef SQLITE_OMIT_LOCALTIME
13847   "OMIT_LOCALTIME",
13848 #endif
13849 #ifdef SQLITE_OMIT_LOOKASIDE
13850   "OMIT_LOOKASIDE",
13851 #endif
13852 #ifdef SQLITE_OMIT_MEMORYDB
13853   "OMIT_MEMORYDB",
13854 #endif
13855 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
13856   "OMIT_OR_OPTIMIZATION",
13857 #endif
13858 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
13859   "OMIT_PAGER_PRAGMAS",
13860 #endif
13861 #ifdef SQLITE_OMIT_PRAGMA
13862   "OMIT_PRAGMA",
13863 #endif
13864 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
13865   "OMIT_PROGRESS_CALLBACK",
13866 #endif
13867 #ifdef SQLITE_OMIT_QUICKBALANCE
13868   "OMIT_QUICKBALANCE",
13869 #endif
13870 #ifdef SQLITE_OMIT_REINDEX
13871   "OMIT_REINDEX",
13872 #endif
13873 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
13874   "OMIT_SCHEMA_PRAGMAS",
13875 #endif
13876 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
13877   "OMIT_SCHEMA_VERSION_PRAGMAS",
13878 #endif
13879 #ifdef SQLITE_OMIT_SHARED_CACHE
13880   "OMIT_SHARED_CACHE",
13881 #endif
13882 #ifdef SQLITE_OMIT_SUBQUERY
13883   "OMIT_SUBQUERY",
13884 #endif
13885 #ifdef SQLITE_OMIT_TCL_VARIABLE
13886   "OMIT_TCL_VARIABLE",
13887 #endif
13888 #ifdef SQLITE_OMIT_TEMPDB
13889   "OMIT_TEMPDB",
13890 #endif
13891 #ifdef SQLITE_OMIT_TRACE
13892   "OMIT_TRACE",
13893 #endif
13894 #ifdef SQLITE_OMIT_TRIGGER
13895   "OMIT_TRIGGER",
13896 #endif
13897 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
13898   "OMIT_TRUNCATE_OPTIMIZATION",
13899 #endif
13900 #ifdef SQLITE_OMIT_UTF16
13901   "OMIT_UTF16",
13902 #endif
13903 #ifdef SQLITE_OMIT_VACUUM
13904   "OMIT_VACUUM",
13905 #endif
13906 #ifdef SQLITE_OMIT_VIEW
13907   "OMIT_VIEW",
13908 #endif
13909 #ifdef SQLITE_OMIT_VIRTUALTABLE
13910   "OMIT_VIRTUALTABLE",
13911 #endif
13912 #ifdef SQLITE_OMIT_WAL
13913   "OMIT_WAL",
13914 #endif
13915 #ifdef SQLITE_OMIT_WSD
13916   "OMIT_WSD",
13917 #endif
13918 #ifdef SQLITE_OMIT_XFER_OPT
13919   "OMIT_XFER_OPT",
13920 #endif
13921 #ifdef SQLITE_PERFORMANCE_TRACE
13922   "PERFORMANCE_TRACE",
13923 #endif
13924 #ifdef SQLITE_PROXY_DEBUG
13925   "PROXY_DEBUG",
13926 #endif
13927 #ifdef SQLITE_RTREE_INT_ONLY
13928   "RTREE_INT_ONLY",
13929 #endif
13930 #ifdef SQLITE_SECURE_DELETE
13931   "SECURE_DELETE",
13932 #endif
13933 #ifdef SQLITE_SMALL_STACK
13934   "SMALL_STACK",
13935 #endif
13936 #ifdef SQLITE_SOUNDEX
13937   "SOUNDEX",
13938 #endif
13939 #ifdef SQLITE_SYSTEM_MALLOC
13940   "SYSTEM_MALLOC",
13941 #endif
13942 #ifdef SQLITE_TCL
13943   "TCL",
13944 #endif
13945 #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
13946   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
13947 #endif
13948 #ifdef SQLITE_TEST
13949   "TEST",
13950 #endif
13951 #if defined(SQLITE_THREADSAFE)
13952   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
13953 #endif
13954 #ifdef SQLITE_USE_ALLOCA
13955   "USE_ALLOCA",
13956 #endif
13957 #ifdef SQLITE_USER_AUTHENTICATION
13958   "USER_AUTHENTICATION",
13959 #endif
13960 #ifdef SQLITE_WIN32_MALLOC
13961   "WIN32_MALLOC",
13962 #endif
13963 #ifdef SQLITE_ZERO_MALLOC
13964   "ZERO_MALLOC"
13965 #endif
13966 };
13967 
13968 /*
13969 ** Given the name of a compile-time option, return true if that option
13970 ** was used and false if not.
13971 **
13972 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
13973 ** is not required for a match.
13974 */
13975 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
13976   int i, n;
13977   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
13978   n = sqlite3Strlen30(zOptName);
13979 
13980   /* Since ArraySize(azCompileOpt) is normally in single digits, a
13981   ** linear search is adequate.  No need for a binary search. */
13982   for(i=0; i<ArraySize(azCompileOpt); i++){
13983     if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
13984      && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
13985     ){
13986       return 1;
13987     }
13988   }
13989   return 0;
13990 }
13991 
13992 /*
13993 ** Return the N-th compile-time option string.  If N is out of range,
13994 ** return a NULL pointer.
13995 */
13996 SQLITE_API const char *sqlite3_compileoption_get(int N){
13997   if( N>=0 && N<ArraySize(azCompileOpt) ){
13998     return azCompileOpt[N];
13999   }
14000   return 0;
14001 }
14002 
14003 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
14004 
14005 /************** End of ctime.c ***********************************************/
14006 /************** Begin file status.c ******************************************/
14007 /*
14008 ** 2008 June 18
14009 **
14010 ** The author disclaims copyright to this source code.  In place of
14011 ** a legal notice, here is a blessing:
14012 **
14013 **    May you do good and not evil.
14014 **    May you find forgiveness for yourself and forgive others.
14015 **    May you share freely, never taking more than you give.
14016 **
14017 *************************************************************************
14018 **
14019 ** This module implements the sqlite3_status() interface and related
14020 ** functionality.
14021 */
14022 /************** Include vdbeInt.h in the middle of status.c ******************/
14023 /************** Begin file vdbeInt.h *****************************************/
14024 /*
14025 ** 2003 September 6
14026 **
14027 ** The author disclaims copyright to this source code.  In place of
14028 ** a legal notice, here is a blessing:
14029 **
14030 **    May you do good and not evil.
14031 **    May you find forgiveness for yourself and forgive others.
14032 **    May you share freely, never taking more than you give.
14033 **
14034 *************************************************************************
14035 ** This is the header file for information that is private to the
14036 ** VDBE.  This information used to all be at the top of the single
14037 ** source code file "vdbe.c".  When that file became too big (over
14038 ** 6000 lines long) it was split up into several smaller files and
14039 ** this header information was factored out.
14040 */
14041 #ifndef _VDBEINT_H_
14042 #define _VDBEINT_H_
14043 
14044 /*
14045 ** The maximum number of times that a statement will try to reparse
14046 ** itself before giving up and returning SQLITE_SCHEMA.
14047 */
14048 #ifndef SQLITE_MAX_SCHEMA_RETRY
14049 # define SQLITE_MAX_SCHEMA_RETRY 50
14050 #endif
14051 
14052 /*
14053 ** SQL is translated into a sequence of instructions to be
14054 ** executed by a virtual machine.  Each instruction is an instance
14055 ** of the following structure.
14056 */
14057 typedef struct VdbeOp Op;
14058 
14059 /*
14060 ** Boolean values
14061 */
14062 typedef unsigned Bool;
14063 
14064 /* Opaque type used by code in vdbesort.c */
14065 typedef struct VdbeSorter VdbeSorter;
14066 
14067 /* Opaque type used by the explainer */
14068 typedef struct Explain Explain;
14069 
14070 /* Elements of the linked list at Vdbe.pAuxData */
14071 typedef struct AuxData AuxData;
14072 
14073 /*
14074 ** A cursor is a pointer into a single BTree within a database file.
14075 ** The cursor can seek to a BTree entry with a particular key, or
14076 ** loop over all entries of the Btree.  You can also insert new BTree
14077 ** entries or retrieve the key or data from the entry that the cursor
14078 ** is currently pointing to.
14079 **
14080 ** Cursors can also point to virtual tables, sorters, or "pseudo-tables".
14081 ** A pseudo-table is a single-row table implemented by registers.
14082 **
14083 ** Every cursor that the virtual machine has open is represented by an
14084 ** instance of the following structure.
14085 */
14086 struct VdbeCursor {
14087   BtCursor *pCursor;    /* The cursor structure of the backend */
14088   Btree *pBt;           /* Separate file holding temporary table */
14089   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
14090   int seekResult;       /* Result of previous sqlite3BtreeMoveto() */
14091   int pseudoTableReg;   /* Register holding pseudotable content. */
14092   i16 nField;           /* Number of fields in the header */
14093   u16 nHdrParsed;       /* Number of header fields parsed so far */
14094 #ifdef SQLITE_DEBUG
14095   u8 seekOp;            /* Most recent seek operation on this cursor */
14096 #endif
14097   i8 iDb;               /* Index of cursor database in db->aDb[] (or -1) */
14098   u8 nullRow;           /* True if pointing to a row with no data */
14099   u8 deferredMoveto;    /* A call to sqlite3BtreeMoveto() is needed */
14100   Bool isEphemeral:1;   /* True for an ephemeral table */
14101   Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
14102   Bool isTable:1;       /* True if a table requiring integer keys */
14103   Bool isOrdered:1;     /* True if the underlying table is BTREE_UNORDERED */
14104   Pgno pgnoRoot;        /* Root page of the open btree cursor */
14105   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
14106   i64 seqCount;         /* Sequence counter */
14107   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
14108   VdbeSorter *pSorter;  /* Sorter object for OP_SorterOpen cursors */
14109 
14110   /* Cached information about the header for the data record that the
14111   ** cursor is currently pointing to.  Only valid if cacheStatus matches
14112   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
14113   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
14114   ** the cache is out of date.
14115   **
14116   ** aRow might point to (ephemeral) data for the current row, or it might
14117   ** be NULL.
14118   */
14119   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
14120   u32 payloadSize;      /* Total number of bytes in the record */
14121   u32 szRow;            /* Byte available in aRow */
14122   u32 iHdrOffset;       /* Offset to next unparsed byte of the header */
14123   const u8 *aRow;       /* Data for the current row, if all on one page */
14124   u32 *aOffset;         /* Pointer to aType[nField] */
14125   u32 aType[1];         /* Type values for all entries in the record */
14126   /* 2*nField extra array elements allocated for aType[], beyond the one
14127   ** static element declared in the structure.  nField total array slots for
14128   ** aType[] and nField+1 array slots for aOffset[] */
14129 };
14130 typedef struct VdbeCursor VdbeCursor;
14131 
14132 /*
14133 ** When a sub-program is executed (OP_Program), a structure of this type
14134 ** is allocated to store the current value of the program counter, as
14135 ** well as the current memory cell array and various other frame specific
14136 ** values stored in the Vdbe struct. When the sub-program is finished,
14137 ** these values are copied back to the Vdbe from the VdbeFrame structure,
14138 ** restoring the state of the VM to as it was before the sub-program
14139 ** began executing.
14140 **
14141 ** The memory for a VdbeFrame object is allocated and managed by a memory
14142 ** cell in the parent (calling) frame. When the memory cell is deleted or
14143 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
14144 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
14145 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
14146 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
14147 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
14148 ** child frame are released.
14149 **
14150 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
14151 ** set to NULL if the currently executing frame is the main program.
14152 */
14153 typedef struct VdbeFrame VdbeFrame;
14154 struct VdbeFrame {
14155   Vdbe *v;                /* VM this frame belongs to */
14156   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
14157   Op *aOp;                /* Program instructions for parent frame */
14158   Mem *aMem;              /* Array of memory cells for parent frame */
14159   u8 *aOnceFlag;          /* Array of OP_Once flags for parent frame */
14160   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
14161   void *token;            /* Copy of SubProgram.token */
14162   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
14163   int nCursor;            /* Number of entries in apCsr */
14164   int pc;                 /* Program Counter in parent (calling) frame */
14165   int nOp;                /* Size of aOp array */
14166   int nMem;               /* Number of entries in aMem */
14167   int nOnceFlag;          /* Number of entries in aOnceFlag */
14168   int nChildMem;          /* Number of memory cells for child frame */
14169   int nChildCsr;          /* Number of cursors for child frame */
14170   int nChange;            /* Statement changes (Vdbe.nChanges)     */
14171 };
14172 
14173 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
14174 
14175 /*
14176 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
14177 */
14178 #define CACHE_STALE 0
14179 
14180 /*
14181 ** Internally, the vdbe manipulates nearly all SQL values as Mem
14182 ** structures. Each Mem struct may cache multiple representations (string,
14183 ** integer etc.) of the same value.
14184 */
14185 struct Mem {
14186   union MemValue {
14187     double r;           /* Real value used when MEM_Real is set in flags */
14188     i64 i;              /* Integer value used when MEM_Int is set in flags */
14189     int nZero;          /* Used when bit MEM_Zero is set in flags */
14190     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
14191     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
14192     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
14193   } u;
14194   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
14195   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
14196   int n;              /* Number of characters in string value, excluding '\0' */
14197   char *z;            /* String or BLOB value */
14198   /* ShallowCopy only needs to copy the information above */
14199   char *zMalloc;      /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
14200   int szMalloc;       /* Size of the zMalloc allocation */
14201   u32 uTemp;          /* Transient storage for serial_type in OP_MakeRecord */
14202   sqlite3 *db;        /* The associated database connection */
14203   void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
14204 #ifdef SQLITE_DEBUG
14205   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
14206   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
14207 #endif
14208 };
14209 
14210 /* One or more of the following flags are set to indicate the validOK
14211 ** representations of the value stored in the Mem struct.
14212 **
14213 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
14214 ** No other flags may be set in this case.
14215 **
14216 ** If the MEM_Str flag is set then Mem.z points at a string representation.
14217 ** Usually this is encoded in the same unicode encoding as the main
14218 ** database (see below for exceptions). If the MEM_Term flag is also
14219 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
14220 ** flags may coexist with the MEM_Str flag.
14221 */
14222 #define MEM_Null      0x0001   /* Value is NULL */
14223 #define MEM_Str       0x0002   /* Value is a string */
14224 #define MEM_Int       0x0004   /* Value is an integer */
14225 #define MEM_Real      0x0008   /* Value is a real number */
14226 #define MEM_Blob      0x0010   /* Value is a BLOB */
14227 #define MEM_AffMask   0x001f   /* Mask of affinity bits */
14228 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
14229 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
14230 #define MEM_Undefined 0x0080   /* Value is undefined */
14231 #define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */
14232 #define MEM_TypeMask  0x01ff   /* Mask of type bits */
14233 
14234 
14235 /* Whenever Mem contains a valid string or blob representation, one of
14236 ** the following flags must be set to determine the memory management
14237 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
14238 ** string is \000 or \u0000 terminated
14239 */
14240 #define MEM_Term      0x0200   /* String rep is nul terminated */
14241 #define MEM_Dyn       0x0400   /* Need to call Mem.xDel() on Mem.z */
14242 #define MEM_Static    0x0800   /* Mem.z points to a static string */
14243 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
14244 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
14245 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
14246 #ifdef SQLITE_OMIT_INCRBLOB
14247   #undef MEM_Zero
14248   #define MEM_Zero 0x0000
14249 #endif
14250 
14251 /*
14252 ** Clear any existing type flags from a Mem and replace them with f
14253 */
14254 #define MemSetTypeFlag(p, f) \
14255    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
14256 
14257 /*
14258 ** Return true if a memory cell is not marked as invalid.  This macro
14259 ** is for use inside assert() statements only.
14260 */
14261 #ifdef SQLITE_DEBUG
14262 #define memIsValid(M)  ((M)->flags & MEM_Undefined)==0
14263 #endif
14264 
14265 /*
14266 ** Each auxiliary data pointer stored by a user defined function
14267 ** implementation calling sqlite3_set_auxdata() is stored in an instance
14268 ** of this structure. All such structures associated with a single VM
14269 ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
14270 ** when the VM is halted (if not before).
14271 */
14272 struct AuxData {
14273   int iOp;                        /* Instruction number of OP_Function opcode */
14274   int iArg;                       /* Index of function argument. */
14275   void *pAux;                     /* Aux data pointer */
14276   void (*xDelete)(void *);        /* Destructor for the aux data */
14277   AuxData *pNext;                 /* Next element in list */
14278 };
14279 
14280 /*
14281 ** The "context" argument for an installable function.  A pointer to an
14282 ** instance of this structure is the first argument to the routines used
14283 ** implement the SQL functions.
14284 **
14285 ** There is a typedef for this structure in sqlite.h.  So all routines,
14286 ** even the public interface to SQLite, can use a pointer to this structure.
14287 ** But this file is the only place where the internal details of this
14288 ** structure are known.
14289 **
14290 ** This structure is defined inside of vdbeInt.h because it uses substructures
14291 ** (Mem) which are only defined there.
14292 */
14293 struct sqlite3_context {
14294   Mem *pOut;            /* The return value is stored here */
14295   FuncDef *pFunc;       /* Pointer to function information */
14296   Mem *pMem;            /* Memory cell used to store aggregate context */
14297   Vdbe *pVdbe;          /* The VM that owns this context */
14298   int iOp;              /* Instruction number of OP_Function */
14299   int isError;          /* Error code returned by the function. */
14300   u8 skipFlag;          /* Skip accumulator loading if true */
14301   u8 fErrorOrAux;       /* isError!=0 or pVdbe->pAuxData modified */
14302 };
14303 
14304 /*
14305 ** An Explain object accumulates indented output which is helpful
14306 ** in describing recursive data structures.
14307 */
14308 struct Explain {
14309   Vdbe *pVdbe;       /* Attach the explanation to this Vdbe */
14310   StrAccum str;      /* The string being accumulated */
14311   int nIndent;       /* Number of elements in aIndent */
14312   u16 aIndent[100];  /* Levels of indentation */
14313   char zBase[100];   /* Initial space */
14314 };
14315 
14316 /* A bitfield type for use inside of structures.  Always follow with :N where
14317 ** N is the number of bits.
14318 */
14319 typedef unsigned bft;  /* Bit Field Type */
14320 
14321 /*
14322 ** An instance of the virtual machine.  This structure contains the complete
14323 ** state of the virtual machine.
14324 **
14325 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
14326 ** is really a pointer to an instance of this structure.
14327 **
14328 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
14329 ** any virtual table method invocations made by the vdbe program. It is
14330 ** set to 2 for xDestroy method calls and 1 for all other methods. This
14331 ** variable is used for two purposes: to allow xDestroy methods to execute
14332 ** "DROP TABLE" statements and to prevent some nasty side effects of
14333 ** malloc failure when SQLite is invoked recursively by a virtual table
14334 ** method function.
14335 */
14336 struct Vdbe {
14337   sqlite3 *db;            /* The database connection that owns this statement */
14338   Op *aOp;                /* Space to hold the virtual machine's program */
14339   Mem *aMem;              /* The memory locations */
14340   Mem **apArg;            /* Arguments to currently executing user function */
14341   Mem *aColName;          /* Column names to return */
14342   Mem *pResultSet;        /* Pointer to an array of results */
14343   Parse *pParse;          /* Parsing context used to create this Vdbe */
14344   int nMem;               /* Number of memory locations currently allocated */
14345   int nOp;                /* Number of instructions in the program */
14346   int nCursor;            /* Number of slots in apCsr[] */
14347   u32 magic;              /* Magic number for sanity checking */
14348   char *zErrMsg;          /* Error message written here */
14349   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
14350   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
14351   Mem *aVar;              /* Values for the OP_Variable opcode. */
14352   char **azVar;           /* Name of variables */
14353   ynVar nVar;             /* Number of entries in aVar[] */
14354   ynVar nzVar;            /* Number of entries in azVar[] */
14355   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
14356   int pc;                 /* The program counter */
14357   int rc;                 /* Value to return */
14358   u16 nResColumn;         /* Number of columns in one row of the result set */
14359   u8 errorAction;         /* Recovery action to do in case of an error */
14360   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
14361   bft explain:2;          /* True if EXPLAIN present on SQL command */
14362   bft inVtabMethod:2;     /* See comments above */
14363   bft changeCntOn:1;      /* True to update the change-counter */
14364   bft expired:1;          /* True if the VM needs to be recompiled */
14365   bft runOnlyOnce:1;      /* Automatically expire on reset */
14366   bft usesStmtJournal:1;  /* True if uses a statement journal */
14367   bft readOnly:1;         /* True for statements that do not write */
14368   bft bIsReader:1;        /* True for statements that read */
14369   bft isPrepareV2:1;      /* True if prepared with prepare_v2() */
14370   bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
14371   int nChange;            /* Number of db changes made since last reset */
14372   yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
14373   yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
14374   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
14375   u32 aCounter[5];        /* Counters used by sqlite3_stmt_status() */
14376 #ifndef SQLITE_OMIT_TRACE
14377   i64 startTime;          /* Time when query started - used for profiling */
14378 #endif
14379   i64 iCurrentTime;       /* Value of julianday('now') for this statement */
14380   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
14381   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
14382   i64 nStmtDefImmCons;    /* Number of def. imm constraints when stmt started */
14383   char *zSql;             /* Text of the SQL statement that generated this */
14384   void *pFree;            /* Free this when deleting the vdbe */
14385   VdbeFrame *pFrame;      /* Parent frame */
14386   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
14387   int nFrame;             /* Number of frames in pFrame list */
14388   u32 expmask;            /* Binding to these vars invalidates VM */
14389   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
14390   int nOnceFlag;          /* Size of array aOnceFlag[] */
14391   u8 *aOnceFlag;          /* Flags for OP_Once */
14392   AuxData *pAuxData;      /* Linked list of auxdata allocations */
14393 };
14394 
14395 /*
14396 ** The following are allowed values for Vdbe.magic
14397 */
14398 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
14399 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
14400 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
14401 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
14402 
14403 /*
14404 ** Function prototypes
14405 */
14406 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
14407 void sqliteVdbePopStack(Vdbe*,int);
14408 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
14409 SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
14410 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
14411 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
14412 #endif
14413 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
14414 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
14415 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
14416 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
14417 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
14418 
14419 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
14420 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
14421 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
14422 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
14423 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
14424 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
14425 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
14426 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
14427 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
14428 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
14429 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
14430 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
14431 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
14432 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
14433 #ifdef SQLITE_OMIT_FLOATING_POINT
14434 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
14435 #else
14436 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
14437 #endif
14438 SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
14439 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
14440 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
14441 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
14442 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
14443 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
14444 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
14445 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
14446 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
14447 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
14448 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
14449 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
14450 SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
14451 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*);
14452 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
14453 #define VdbeMemDynamic(X)  \
14454   (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
14455 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
14456 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
14457 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
14458 SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
14459 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
14460 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
14461 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
14462 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
14463 
14464 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
14465 SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
14466 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
14467 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
14468 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
14469 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
14470 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
14471 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
14472 
14473 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
14474 SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
14475 SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
14476 #else
14477 # define sqlite3VdbeEnter(X)
14478 # define sqlite3VdbeLeave(X)
14479 #endif
14480 
14481 #ifdef SQLITE_DEBUG
14482 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
14483 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
14484 #endif
14485 
14486 #ifndef SQLITE_OMIT_FOREIGN_KEY
14487 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
14488 #else
14489 # define sqlite3VdbeCheckFk(p,i) 0
14490 #endif
14491 
14492 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
14493 #ifdef SQLITE_DEBUG
14494 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
14495 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
14496 #endif
14497 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
14498 
14499 #ifndef SQLITE_OMIT_INCRBLOB
14500 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
14501   #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
14502 #else
14503   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
14504   #define ExpandBlob(P) SQLITE_OK
14505 #endif
14506 
14507 #endif /* !defined(_VDBEINT_H_) */
14508 
14509 /************** End of vdbeInt.h *********************************************/
14510 /************** Continuing where we left off in status.c *********************/
14511 
14512 /*
14513 ** Variables in which to record status information.
14514 */
14515 typedef struct sqlite3StatType sqlite3StatType;
14516 static SQLITE_WSD struct sqlite3StatType {
14517   int nowValue[10];         /* Current value */
14518   int mxValue[10];          /* Maximum value */
14519 } sqlite3Stat = { {0,}, {0,} };
14520 
14521 
14522 /* The "wsdStat" macro will resolve to the status information
14523 ** state vector.  If writable static data is unsupported on the target,
14524 ** we have to locate the state vector at run-time.  In the more common
14525 ** case where writable static data is supported, wsdStat can refer directly
14526 ** to the "sqlite3Stat" state vector declared above.
14527 */
14528 #ifdef SQLITE_OMIT_WSD
14529 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
14530 # define wsdStat x[0]
14531 #else
14532 # define wsdStatInit
14533 # define wsdStat sqlite3Stat
14534 #endif
14535 
14536 /*
14537 ** Return the current value of a status parameter.
14538 */
14539 SQLITE_PRIVATE int sqlite3StatusValue(int op){
14540   wsdStatInit;
14541   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
14542   return wsdStat.nowValue[op];
14543 }
14544 
14545 /*
14546 ** Add N to the value of a status record.  It is assumed that the
14547 ** caller holds appropriate locks.
14548 */
14549 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
14550   wsdStatInit;
14551   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
14552   wsdStat.nowValue[op] += N;
14553   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
14554     wsdStat.mxValue[op] = wsdStat.nowValue[op];
14555   }
14556 }
14557 
14558 /*
14559 ** Set the value of a status to X.
14560 */
14561 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
14562   wsdStatInit;
14563   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
14564   wsdStat.nowValue[op] = X;
14565   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
14566     wsdStat.mxValue[op] = wsdStat.nowValue[op];
14567   }
14568 }
14569 
14570 /*
14571 ** Query status information.
14572 **
14573 ** This implementation assumes that reading or writing an aligned
14574 ** 32-bit integer is an atomic operation.  If that assumption is not true,
14575 ** then this routine is not threadsafe.
14576 */
14577 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
14578   wsdStatInit;
14579   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
14580     return SQLITE_MISUSE_BKPT;
14581   }
14582   *pCurrent = wsdStat.nowValue[op];
14583   *pHighwater = wsdStat.mxValue[op];
14584   if( resetFlag ){
14585     wsdStat.mxValue[op] = wsdStat.nowValue[op];
14586   }
14587   return SQLITE_OK;
14588 }
14589 
14590 /*
14591 ** Query status information for a single database connection
14592 */
14593 SQLITE_API int sqlite3_db_status(
14594   sqlite3 *db,          /* The database connection whose status is desired */
14595   int op,               /* Status verb */
14596   int *pCurrent,        /* Write current value here */
14597   int *pHighwater,      /* Write high-water mark here */
14598   int resetFlag         /* Reset high-water mark if true */
14599 ){
14600   int rc = SQLITE_OK;   /* Return code */
14601   sqlite3_mutex_enter(db->mutex);
14602   switch( op ){
14603     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
14604       *pCurrent = db->lookaside.nOut;
14605       *pHighwater = db->lookaside.mxOut;
14606       if( resetFlag ){
14607         db->lookaside.mxOut = db->lookaside.nOut;
14608       }
14609       break;
14610     }
14611 
14612     case SQLITE_DBSTATUS_LOOKASIDE_HIT:
14613     case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
14614     case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
14615       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
14616       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
14617       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
14618       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
14619       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
14620       *pCurrent = 0;
14621       *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
14622       if( resetFlag ){
14623         db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
14624       }
14625       break;
14626     }
14627 
14628     /*
14629     ** Return an approximation for the amount of memory currently used
14630     ** by all pagers associated with the given database connection.  The
14631     ** highwater mark is meaningless and is returned as zero.
14632     */
14633     case SQLITE_DBSTATUS_CACHE_USED: {
14634       int totalUsed = 0;
14635       int i;
14636       sqlite3BtreeEnterAll(db);
14637       for(i=0; i<db->nDb; i++){
14638         Btree *pBt = db->aDb[i].pBt;
14639         if( pBt ){
14640           Pager *pPager = sqlite3BtreePager(pBt);
14641           totalUsed += sqlite3PagerMemUsed(pPager);
14642         }
14643       }
14644       sqlite3BtreeLeaveAll(db);
14645       *pCurrent = totalUsed;
14646       *pHighwater = 0;
14647       break;
14648     }
14649 
14650     /*
14651     ** *pCurrent gets an accurate estimate of the amount of memory used
14652     ** to store the schema for all databases (main, temp, and any ATTACHed
14653     ** databases.  *pHighwater is set to zero.
14654     */
14655     case SQLITE_DBSTATUS_SCHEMA_USED: {
14656       int i;                      /* Used to iterate through schemas */
14657       int nByte = 0;              /* Used to accumulate return value */
14658 
14659       sqlite3BtreeEnterAll(db);
14660       db->pnBytesFreed = &nByte;
14661       for(i=0; i<db->nDb; i++){
14662         Schema *pSchema = db->aDb[i].pSchema;
14663         if( ALWAYS(pSchema!=0) ){
14664           HashElem *p;
14665 
14666           nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
14667               pSchema->tblHash.count
14668             + pSchema->trigHash.count
14669             + pSchema->idxHash.count
14670             + pSchema->fkeyHash.count
14671           );
14672           nByte += sqlite3MallocSize(pSchema->tblHash.ht);
14673           nByte += sqlite3MallocSize(pSchema->trigHash.ht);
14674           nByte += sqlite3MallocSize(pSchema->idxHash.ht);
14675           nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
14676 
14677           for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
14678             sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
14679           }
14680           for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
14681             sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
14682           }
14683         }
14684       }
14685       db->pnBytesFreed = 0;
14686       sqlite3BtreeLeaveAll(db);
14687 
14688       *pHighwater = 0;
14689       *pCurrent = nByte;
14690       break;
14691     }
14692 
14693     /*
14694     ** *pCurrent gets an accurate estimate of the amount of memory used
14695     ** to store all prepared statements.
14696     ** *pHighwater is set to zero.
14697     */
14698     case SQLITE_DBSTATUS_STMT_USED: {
14699       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
14700       int nByte = 0;              /* Used to accumulate return value */
14701 
14702       db->pnBytesFreed = &nByte;
14703       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
14704         sqlite3VdbeClearObject(db, pVdbe);
14705         sqlite3DbFree(db, pVdbe);
14706       }
14707       db->pnBytesFreed = 0;
14708 
14709       *pHighwater = 0;  /* IMP: R-64479-57858 */
14710       *pCurrent = nByte;
14711 
14712       break;
14713     }
14714 
14715     /*
14716     ** Set *pCurrent to the total cache hits or misses encountered by all
14717     ** pagers the database handle is connected to. *pHighwater is always set
14718     ** to zero.
14719     */
14720     case SQLITE_DBSTATUS_CACHE_HIT:
14721     case SQLITE_DBSTATUS_CACHE_MISS:
14722     case SQLITE_DBSTATUS_CACHE_WRITE:{
14723       int i;
14724       int nRet = 0;
14725       assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
14726       assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
14727 
14728       for(i=0; i<db->nDb; i++){
14729         if( db->aDb[i].pBt ){
14730           Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
14731           sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
14732         }
14733       }
14734       *pHighwater = 0; /* IMP: R-42420-56072 */
14735                        /* IMP: R-54100-20147 */
14736                        /* IMP: R-29431-39229 */
14737       *pCurrent = nRet;
14738       break;
14739     }
14740 
14741     /* Set *pCurrent to non-zero if there are unresolved deferred foreign
14742     ** key constraints.  Set *pCurrent to zero if all foreign key constraints
14743     ** have been satisfied.  The *pHighwater is always set to zero.
14744     */
14745     case SQLITE_DBSTATUS_DEFERRED_FKS: {
14746       *pHighwater = 0;  /* IMP: R-11967-56545 */
14747       *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
14748       break;
14749     }
14750 
14751     default: {
14752       rc = SQLITE_ERROR;
14753     }
14754   }
14755   sqlite3_mutex_leave(db->mutex);
14756   return rc;
14757 }
14758 
14759 /************** End of status.c **********************************************/
14760 /************** Begin file date.c ********************************************/
14761 /*
14762 ** 2003 October 31
14763 **
14764 ** The author disclaims copyright to this source code.  In place of
14765 ** a legal notice, here is a blessing:
14766 **
14767 **    May you do good and not evil.
14768 **    May you find forgiveness for yourself and forgive others.
14769 **    May you share freely, never taking more than you give.
14770 **
14771 *************************************************************************
14772 ** This file contains the C functions that implement date and time
14773 ** functions for SQLite.
14774 **
14775 ** There is only one exported symbol in this file - the function
14776 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
14777 ** All other code has file scope.
14778 **
14779 ** SQLite processes all times and dates as Julian Day numbers.  The
14780 ** dates and times are stored as the number of days since noon
14781 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
14782 ** calendar system.
14783 **
14784 ** 1970-01-01 00:00:00 is JD 2440587.5
14785 ** 2000-01-01 00:00:00 is JD 2451544.5
14786 **
14787 ** This implementation requires years to be expressed as a 4-digit number
14788 ** which means that only dates between 0000-01-01 and 9999-12-31 can
14789 ** be represented, even though julian day numbers allow a much wider
14790 ** range of dates.
14791 **
14792 ** The Gregorian calendar system is used for all dates and times,
14793 ** even those that predate the Gregorian calendar.  Historians usually
14794 ** use the Julian calendar for dates prior to 1582-10-15 and for some
14795 ** dates afterwards, depending on locale.  Beware of this difference.
14796 **
14797 ** The conversion algorithms are implemented based on descriptions
14798 ** in the following text:
14799 **
14800 **      Jean Meeus
14801 **      Astronomical Algorithms, 2nd Edition, 1998
14802 **      ISBM 0-943396-61-1
14803 **      Willmann-Bell, Inc
14804 **      Richmond, Virginia (USA)
14805 */
14806 /* #include <stdlib.h> */
14807 /* #include <assert.h> */
14808 #include <time.h>
14809 
14810 #ifndef SQLITE_OMIT_DATETIME_FUNCS
14811 
14812 
14813 /*
14814 ** A structure for holding a single date and time.
14815 */
14816 typedef struct DateTime DateTime;
14817 struct DateTime {
14818   sqlite3_int64 iJD; /* The julian day number times 86400000 */
14819   int Y, M, D;       /* Year, month, and day */
14820   int h, m;          /* Hour and minutes */
14821   int tz;            /* Timezone offset in minutes */
14822   double s;          /* Seconds */
14823   char validYMD;     /* True (1) if Y,M,D are valid */
14824   char validHMS;     /* True (1) if h,m,s are valid */
14825   char validJD;      /* True (1) if iJD is valid */
14826   char validTZ;      /* True (1) if tz is valid */
14827 };
14828 
14829 
14830 /*
14831 ** Convert zDate into one or more integers.  Additional arguments
14832 ** come in groups of 5 as follows:
14833 **
14834 **       N       number of digits in the integer
14835 **       min     minimum allowed value of the integer
14836 **       max     maximum allowed value of the integer
14837 **       nextC   first character after the integer
14838 **       pVal    where to write the integers value.
14839 **
14840 ** Conversions continue until one with nextC==0 is encountered.
14841 ** The function returns the number of successful conversions.
14842 */
14843 static int getDigits(const char *zDate, ...){
14844   va_list ap;
14845   int val;
14846   int N;
14847   int min;
14848   int max;
14849   int nextC;
14850   int *pVal;
14851   int cnt = 0;
14852   va_start(ap, zDate);
14853   do{
14854     N = va_arg(ap, int);
14855     min = va_arg(ap, int);
14856     max = va_arg(ap, int);
14857     nextC = va_arg(ap, int);
14858     pVal = va_arg(ap, int*);
14859     val = 0;
14860     while( N-- ){
14861       if( !sqlite3Isdigit(*zDate) ){
14862         goto end_getDigits;
14863       }
14864       val = val*10 + *zDate - '0';
14865       zDate++;
14866     }
14867     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
14868       goto end_getDigits;
14869     }
14870     *pVal = val;
14871     zDate++;
14872     cnt++;
14873   }while( nextC );
14874 end_getDigits:
14875   va_end(ap);
14876   return cnt;
14877 }
14878 
14879 /*
14880 ** Parse a timezone extension on the end of a date-time.
14881 ** The extension is of the form:
14882 **
14883 **        (+/-)HH:MM
14884 **
14885 ** Or the "zulu" notation:
14886 **
14887 **        Z
14888 **
14889 ** If the parse is successful, write the number of minutes
14890 ** of change in p->tz and return 0.  If a parser error occurs,
14891 ** return non-zero.
14892 **
14893 ** A missing specifier is not considered an error.
14894 */
14895 static int parseTimezone(const char *zDate, DateTime *p){
14896   int sgn = 0;
14897   int nHr, nMn;
14898   int c;
14899   while( sqlite3Isspace(*zDate) ){ zDate++; }
14900   p->tz = 0;
14901   c = *zDate;
14902   if( c=='-' ){
14903     sgn = -1;
14904   }else if( c=='+' ){
14905     sgn = +1;
14906   }else if( c=='Z' || c=='z' ){
14907     zDate++;
14908     goto zulu_time;
14909   }else{
14910     return c!=0;
14911   }
14912   zDate++;
14913   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
14914     return 1;
14915   }
14916   zDate += 5;
14917   p->tz = sgn*(nMn + nHr*60);
14918 zulu_time:
14919   while( sqlite3Isspace(*zDate) ){ zDate++; }
14920   return *zDate!=0;
14921 }
14922 
14923 /*
14924 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
14925 ** The HH, MM, and SS must each be exactly 2 digits.  The
14926 ** fractional seconds FFFF can be one or more digits.
14927 **
14928 ** Return 1 if there is a parsing error and 0 on success.
14929 */
14930 static int parseHhMmSs(const char *zDate, DateTime *p){
14931   int h, m, s;
14932   double ms = 0.0;
14933   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
14934     return 1;
14935   }
14936   zDate += 5;
14937   if( *zDate==':' ){
14938     zDate++;
14939     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
14940       return 1;
14941     }
14942     zDate += 2;
14943     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
14944       double rScale = 1.0;
14945       zDate++;
14946       while( sqlite3Isdigit(*zDate) ){
14947         ms = ms*10.0 + *zDate - '0';
14948         rScale *= 10.0;
14949         zDate++;
14950       }
14951       ms /= rScale;
14952     }
14953   }else{
14954     s = 0;
14955   }
14956   p->validJD = 0;
14957   p->validHMS = 1;
14958   p->h = h;
14959   p->m = m;
14960   p->s = s + ms;
14961   if( parseTimezone(zDate, p) ) return 1;
14962   p->validTZ = (p->tz!=0)?1:0;
14963   return 0;
14964 }
14965 
14966 /*
14967 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
14968 ** that the YYYY-MM-DD is according to the Gregorian calendar.
14969 **
14970 ** Reference:  Meeus page 61
14971 */
14972 static void computeJD(DateTime *p){
14973   int Y, M, D, A, B, X1, X2;
14974 
14975   if( p->validJD ) return;
14976   if( p->validYMD ){
14977     Y = p->Y;
14978     M = p->M;
14979     D = p->D;
14980   }else{
14981     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
14982     M = 1;
14983     D = 1;
14984   }
14985   if( M<=2 ){
14986     Y--;
14987     M += 12;
14988   }
14989   A = Y/100;
14990   B = 2 - A + (A/4);
14991   X1 = 36525*(Y+4716)/100;
14992   X2 = 306001*(M+1)/10000;
14993   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
14994   p->validJD = 1;
14995   if( p->validHMS ){
14996     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
14997     if( p->validTZ ){
14998       p->iJD -= p->tz*60000;
14999       p->validYMD = 0;
15000       p->validHMS = 0;
15001       p->validTZ = 0;
15002     }
15003   }
15004 }
15005 
15006 /*
15007 ** Parse dates of the form
15008 **
15009 **     YYYY-MM-DD HH:MM:SS.FFF
15010 **     YYYY-MM-DD HH:MM:SS
15011 **     YYYY-MM-DD HH:MM
15012 **     YYYY-MM-DD
15013 **
15014 ** Write the result into the DateTime structure and return 0
15015 ** on success and 1 if the input string is not a well-formed
15016 ** date.
15017 */
15018 static int parseYyyyMmDd(const char *zDate, DateTime *p){
15019   int Y, M, D, neg;
15020 
15021   if( zDate[0]=='-' ){
15022     zDate++;
15023     neg = 1;
15024   }else{
15025     neg = 0;
15026   }
15027   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
15028     return 1;
15029   }
15030   zDate += 10;
15031   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
15032   if( parseHhMmSs(zDate, p)==0 ){
15033     /* We got the time */
15034   }else if( *zDate==0 ){
15035     p->validHMS = 0;
15036   }else{
15037     return 1;
15038   }
15039   p->validJD = 0;
15040   p->validYMD = 1;
15041   p->Y = neg ? -Y : Y;
15042   p->M = M;
15043   p->D = D;
15044   if( p->validTZ ){
15045     computeJD(p);
15046   }
15047   return 0;
15048 }
15049 
15050 /*
15051 ** Set the time to the current time reported by the VFS.
15052 **
15053 ** Return the number of errors.
15054 */
15055 static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
15056   p->iJD = sqlite3StmtCurrentTime(context);
15057   if( p->iJD>0 ){
15058     p->validJD = 1;
15059     return 0;
15060   }else{
15061     return 1;
15062   }
15063 }
15064 
15065 /*
15066 ** Attempt to parse the given string into a Julian Day Number.  Return
15067 ** the number of errors.
15068 **
15069 ** The following are acceptable forms for the input string:
15070 **
15071 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
15072 **      DDDD.DD
15073 **      now
15074 **
15075 ** In the first form, the +/-HH:MM is always optional.  The fractional
15076 ** seconds extension (the ".FFF") is optional.  The seconds portion
15077 ** (":SS.FFF") is option.  The year and date can be omitted as long
15078 ** as there is a time string.  The time string can be omitted as long
15079 ** as there is a year and date.
15080 */
15081 static int parseDateOrTime(
15082   sqlite3_context *context,
15083   const char *zDate,
15084   DateTime *p
15085 ){
15086   double r;
15087   if( parseYyyyMmDd(zDate,p)==0 ){
15088     return 0;
15089   }else if( parseHhMmSs(zDate, p)==0 ){
15090     return 0;
15091   }else if( sqlite3StrICmp(zDate,"now")==0){
15092     return setDateTimeToCurrent(context, p);
15093   }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
15094     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
15095     p->validJD = 1;
15096     return 0;
15097   }
15098   return 1;
15099 }
15100 
15101 /*
15102 ** Compute the Year, Month, and Day from the julian day number.
15103 */
15104 static void computeYMD(DateTime *p){
15105   int Z, A, B, C, D, E, X1;
15106   if( p->validYMD ) return;
15107   if( !p->validJD ){
15108     p->Y = 2000;
15109     p->M = 1;
15110     p->D = 1;
15111   }else{
15112     Z = (int)((p->iJD + 43200000)/86400000);
15113     A = (int)((Z - 1867216.25)/36524.25);
15114     A = Z + 1 + A - (A/4);
15115     B = A + 1524;
15116     C = (int)((B - 122.1)/365.25);
15117     D = (36525*C)/100;
15118     E = (int)((B-D)/30.6001);
15119     X1 = (int)(30.6001*E);
15120     p->D = B - D - X1;
15121     p->M = E<14 ? E-1 : E-13;
15122     p->Y = p->M>2 ? C - 4716 : C - 4715;
15123   }
15124   p->validYMD = 1;
15125 }
15126 
15127 /*
15128 ** Compute the Hour, Minute, and Seconds from the julian day number.
15129 */
15130 static void computeHMS(DateTime *p){
15131   int s;
15132   if( p->validHMS ) return;
15133   computeJD(p);
15134   s = (int)((p->iJD + 43200000) % 86400000);
15135   p->s = s/1000.0;
15136   s = (int)p->s;
15137   p->s -= s;
15138   p->h = s/3600;
15139   s -= p->h*3600;
15140   p->m = s/60;
15141   p->s += s - p->m*60;
15142   p->validHMS = 1;
15143 }
15144 
15145 /*
15146 ** Compute both YMD and HMS
15147 */
15148 static void computeYMD_HMS(DateTime *p){
15149   computeYMD(p);
15150   computeHMS(p);
15151 }
15152 
15153 /*
15154 ** Clear the YMD and HMS and the TZ
15155 */
15156 static void clearYMD_HMS_TZ(DateTime *p){
15157   p->validYMD = 0;
15158   p->validHMS = 0;
15159   p->validTZ = 0;
15160 }
15161 
15162 /*
15163 ** On recent Windows platforms, the localtime_s() function is available
15164 ** as part of the "Secure CRT". It is essentially equivalent to
15165 ** localtime_r() available under most POSIX platforms, except that the
15166 ** order of the parameters is reversed.
15167 **
15168 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
15169 **
15170 ** If the user has not indicated to use localtime_r() or localtime_s()
15171 ** already, check for an MSVC build environment that provides
15172 ** localtime_s().
15173 */
15174 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
15175      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
15176 #define HAVE_LOCALTIME_S 1
15177 #endif
15178 
15179 #ifndef SQLITE_OMIT_LOCALTIME
15180 /*
15181 ** The following routine implements the rough equivalent of localtime_r()
15182 ** using whatever operating-system specific localtime facility that
15183 ** is available.  This routine returns 0 on success and
15184 ** non-zero on any kind of error.
15185 **
15186 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
15187 ** routine will always fail.
15188 **
15189 ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
15190 ** library function localtime_r() is used to assist in the calculation of
15191 ** local time.
15192 */
15193 static int osLocaltime(time_t *t, struct tm *pTm){
15194   int rc;
15195 #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
15196       && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
15197   struct tm *pX;
15198 #if SQLITE_THREADSAFE>0
15199   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15200 #endif
15201   sqlite3_mutex_enter(mutex);
15202   pX = localtime(t);
15203 #ifndef SQLITE_OMIT_BUILTIN_TEST
15204   if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
15205 #endif
15206   if( pX ) *pTm = *pX;
15207   sqlite3_mutex_leave(mutex);
15208   rc = pX==0;
15209 #else
15210 #ifndef SQLITE_OMIT_BUILTIN_TEST
15211   if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
15212 #endif
15213 #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
15214   rc = localtime_r(t, pTm)==0;
15215 #else
15216   rc = localtime_s(pTm, t);
15217 #endif /* HAVE_LOCALTIME_R */
15218 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
15219   return rc;
15220 }
15221 #endif /* SQLITE_OMIT_LOCALTIME */
15222 
15223 
15224 #ifndef SQLITE_OMIT_LOCALTIME
15225 /*
15226 ** Compute the difference (in milliseconds) between localtime and UTC
15227 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
15228 ** return this value and set *pRc to SQLITE_OK.
15229 **
15230 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
15231 ** is undefined in this case.
15232 */
15233 static sqlite3_int64 localtimeOffset(
15234   DateTime *p,                    /* Date at which to calculate offset */
15235   sqlite3_context *pCtx,          /* Write error here if one occurs */
15236   int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
15237 ){
15238   DateTime x, y;
15239   time_t t;
15240   struct tm sLocal;
15241 
15242   /* Initialize the contents of sLocal to avoid a compiler warning. */
15243   memset(&sLocal, 0, sizeof(sLocal));
15244 
15245   x = *p;
15246   computeYMD_HMS(&x);
15247   if( x.Y<1971 || x.Y>=2038 ){
15248     /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
15249     ** works for years between 1970 and 2037. For dates outside this range,
15250     ** SQLite attempts to map the year into an equivalent year within this
15251     ** range, do the calculation, then map the year back.
15252     */
15253     x.Y = 2000;
15254     x.M = 1;
15255     x.D = 1;
15256     x.h = 0;
15257     x.m = 0;
15258     x.s = 0.0;
15259   } else {
15260     int s = (int)(x.s + 0.5);
15261     x.s = s;
15262   }
15263   x.tz = 0;
15264   x.validJD = 0;
15265   computeJD(&x);
15266   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
15267   if( osLocaltime(&t, &sLocal) ){
15268     sqlite3_result_error(pCtx, "local time unavailable", -1);
15269     *pRc = SQLITE_ERROR;
15270     return 0;
15271   }
15272   y.Y = sLocal.tm_year + 1900;
15273   y.M = sLocal.tm_mon + 1;
15274   y.D = sLocal.tm_mday;
15275   y.h = sLocal.tm_hour;
15276   y.m = sLocal.tm_min;
15277   y.s = sLocal.tm_sec;
15278   y.validYMD = 1;
15279   y.validHMS = 1;
15280   y.validJD = 0;
15281   y.validTZ = 0;
15282   computeJD(&y);
15283   *pRc = SQLITE_OK;
15284   return y.iJD - x.iJD;
15285 }
15286 #endif /* SQLITE_OMIT_LOCALTIME */
15287 
15288 /*
15289 ** Process a modifier to a date-time stamp.  The modifiers are
15290 ** as follows:
15291 **
15292 **     NNN days
15293 **     NNN hours
15294 **     NNN minutes
15295 **     NNN.NNNN seconds
15296 **     NNN months
15297 **     NNN years
15298 **     start of month
15299 **     start of year
15300 **     start of week
15301 **     start of day
15302 **     weekday N
15303 **     unixepoch
15304 **     localtime
15305 **     utc
15306 **
15307 ** Return 0 on success and 1 if there is any kind of error. If the error
15308 ** is in a system call (i.e. localtime()), then an error message is written
15309 ** to context pCtx. If the error is an unrecognized modifier, no error is
15310 ** written to pCtx.
15311 */
15312 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
15313   int rc = 1;
15314   int n;
15315   double r;
15316   char *z, zBuf[30];
15317   z = zBuf;
15318   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
15319     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
15320   }
15321   z[n] = 0;
15322   switch( z[0] ){
15323 #ifndef SQLITE_OMIT_LOCALTIME
15324     case 'l': {
15325       /*    localtime
15326       **
15327       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
15328       ** show local time.
15329       */
15330       if( strcmp(z, "localtime")==0 ){
15331         computeJD(p);
15332         p->iJD += localtimeOffset(p, pCtx, &rc);
15333         clearYMD_HMS_TZ(p);
15334       }
15335       break;
15336     }
15337 #endif
15338     case 'u': {
15339       /*
15340       **    unixepoch
15341       **
15342       ** Treat the current value of p->iJD as the number of
15343       ** seconds since 1970.  Convert to a real julian day number.
15344       */
15345       if( strcmp(z, "unixepoch")==0 && p->validJD ){
15346         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
15347         clearYMD_HMS_TZ(p);
15348         rc = 0;
15349       }
15350 #ifndef SQLITE_OMIT_LOCALTIME
15351       else if( strcmp(z, "utc")==0 ){
15352         sqlite3_int64 c1;
15353         computeJD(p);
15354         c1 = localtimeOffset(p, pCtx, &rc);
15355         if( rc==SQLITE_OK ){
15356           p->iJD -= c1;
15357           clearYMD_HMS_TZ(p);
15358           p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
15359         }
15360       }
15361 #endif
15362       break;
15363     }
15364     case 'w': {
15365       /*
15366       **    weekday N
15367       **
15368       ** Move the date to the same time on the next occurrence of
15369       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
15370       ** date is already on the appropriate weekday, this is a no-op.
15371       */
15372       if( strncmp(z, "weekday ", 8)==0
15373                && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
15374                && (n=(int)r)==r && n>=0 && r<7 ){
15375         sqlite3_int64 Z;
15376         computeYMD_HMS(p);
15377         p->validTZ = 0;
15378         p->validJD = 0;
15379         computeJD(p);
15380         Z = ((p->iJD + 129600000)/86400000) % 7;
15381         if( Z>n ) Z -= 7;
15382         p->iJD += (n - Z)*86400000;
15383         clearYMD_HMS_TZ(p);
15384         rc = 0;
15385       }
15386       break;
15387     }
15388     case 's': {
15389       /*
15390       **    start of TTTTT
15391       **
15392       ** Move the date backwards to the beginning of the current day,
15393       ** or month or year.
15394       */
15395       if( strncmp(z, "start of ", 9)!=0 ) break;
15396       z += 9;
15397       computeYMD(p);
15398       p->validHMS = 1;
15399       p->h = p->m = 0;
15400       p->s = 0.0;
15401       p->validTZ = 0;
15402       p->validJD = 0;
15403       if( strcmp(z,"month")==0 ){
15404         p->D = 1;
15405         rc = 0;
15406       }else if( strcmp(z,"year")==0 ){
15407         computeYMD(p);
15408         p->M = 1;
15409         p->D = 1;
15410         rc = 0;
15411       }else if( strcmp(z,"day")==0 ){
15412         rc = 0;
15413       }
15414       break;
15415     }
15416     case '+':
15417     case '-':
15418     case '0':
15419     case '1':
15420     case '2':
15421     case '3':
15422     case '4':
15423     case '5':
15424     case '6':
15425     case '7':
15426     case '8':
15427     case '9': {
15428       double rRounder;
15429       for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
15430       if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
15431         rc = 1;
15432         break;
15433       }
15434       if( z[n]==':' ){
15435         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
15436         ** specified number of hours, minutes, seconds, and fractional seconds
15437         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
15438         ** omitted.
15439         */
15440         const char *z2 = z;
15441         DateTime tx;
15442         sqlite3_int64 day;
15443         if( !sqlite3Isdigit(*z2) ) z2++;
15444         memset(&tx, 0, sizeof(tx));
15445         if( parseHhMmSs(z2, &tx) ) break;
15446         computeJD(&tx);
15447         tx.iJD -= 43200000;
15448         day = tx.iJD/86400000;
15449         tx.iJD -= day*86400000;
15450         if( z[0]=='-' ) tx.iJD = -tx.iJD;
15451         computeJD(p);
15452         clearYMD_HMS_TZ(p);
15453         p->iJD += tx.iJD;
15454         rc = 0;
15455         break;
15456       }
15457       z += n;
15458       while( sqlite3Isspace(*z) ) z++;
15459       n = sqlite3Strlen30(z);
15460       if( n>10 || n<3 ) break;
15461       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
15462       computeJD(p);
15463       rc = 0;
15464       rRounder = r<0 ? -0.5 : +0.5;
15465       if( n==3 && strcmp(z,"day")==0 ){
15466         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
15467       }else if( n==4 && strcmp(z,"hour")==0 ){
15468         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
15469       }else if( n==6 && strcmp(z,"minute")==0 ){
15470         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
15471       }else if( n==6 && strcmp(z,"second")==0 ){
15472         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
15473       }else if( n==5 && strcmp(z,"month")==0 ){
15474         int x, y;
15475         computeYMD_HMS(p);
15476         p->M += (int)r;
15477         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
15478         p->Y += x;
15479         p->M -= x*12;
15480         p->validJD = 0;
15481         computeJD(p);
15482         y = (int)r;
15483         if( y!=r ){
15484           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
15485         }
15486       }else if( n==4 && strcmp(z,"year")==0 ){
15487         int y = (int)r;
15488         computeYMD_HMS(p);
15489         p->Y += y;
15490         p->validJD = 0;
15491         computeJD(p);
15492         if( y!=r ){
15493           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
15494         }
15495       }else{
15496         rc = 1;
15497       }
15498       clearYMD_HMS_TZ(p);
15499       break;
15500     }
15501     default: {
15502       break;
15503     }
15504   }
15505   return rc;
15506 }
15507 
15508 /*
15509 ** Process time function arguments.  argv[0] is a date-time stamp.
15510 ** argv[1] and following are modifiers.  Parse them all and write
15511 ** the resulting time into the DateTime structure p.  Return 0
15512 ** on success and 1 if there are any errors.
15513 **
15514 ** If there are zero parameters (if even argv[0] is undefined)
15515 ** then assume a default value of "now" for argv[0].
15516 */
15517 static int isDate(
15518   sqlite3_context *context,
15519   int argc,
15520   sqlite3_value **argv,
15521   DateTime *p
15522 ){
15523   int i;
15524   const unsigned char *z;
15525   int eType;
15526   memset(p, 0, sizeof(*p));
15527   if( argc==0 ){
15528     return setDateTimeToCurrent(context, p);
15529   }
15530   if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
15531                    || eType==SQLITE_INTEGER ){
15532     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
15533     p->validJD = 1;
15534   }else{
15535     z = sqlite3_value_text(argv[0]);
15536     if( !z || parseDateOrTime(context, (char*)z, p) ){
15537       return 1;
15538     }
15539   }
15540   for(i=1; i<argc; i++){
15541     z = sqlite3_value_text(argv[i]);
15542     if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
15543   }
15544   return 0;
15545 }
15546 
15547 
15548 /*
15549 ** The following routines implement the various date and time functions
15550 ** of SQLite.
15551 */
15552 
15553 /*
15554 **    julianday( TIMESTRING, MOD, MOD, ...)
15555 **
15556 ** Return the julian day number of the date specified in the arguments
15557 */
15558 static void juliandayFunc(
15559   sqlite3_context *context,
15560   int argc,
15561   sqlite3_value **argv
15562 ){
15563   DateTime x;
15564   if( isDate(context, argc, argv, &x)==0 ){
15565     computeJD(&x);
15566     sqlite3_result_double(context, x.iJD/86400000.0);
15567   }
15568 }
15569 
15570 /*
15571 **    datetime( TIMESTRING, MOD, MOD, ...)
15572 **
15573 ** Return YYYY-MM-DD HH:MM:SS
15574 */
15575 static void datetimeFunc(
15576   sqlite3_context *context,
15577   int argc,
15578   sqlite3_value **argv
15579 ){
15580   DateTime x;
15581   if( isDate(context, argc, argv, &x)==0 ){
15582     char zBuf[100];
15583     computeYMD_HMS(&x);
15584     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
15585                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
15586     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15587   }
15588 }
15589 
15590 /*
15591 **    time( TIMESTRING, MOD, MOD, ...)
15592 **
15593 ** Return HH:MM:SS
15594 */
15595 static void timeFunc(
15596   sqlite3_context *context,
15597   int argc,
15598   sqlite3_value **argv
15599 ){
15600   DateTime x;
15601   if( isDate(context, argc, argv, &x)==0 ){
15602     char zBuf[100];
15603     computeHMS(&x);
15604     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
15605     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15606   }
15607 }
15608 
15609 /*
15610 **    date( TIMESTRING, MOD, MOD, ...)
15611 **
15612 ** Return YYYY-MM-DD
15613 */
15614 static void dateFunc(
15615   sqlite3_context *context,
15616   int argc,
15617   sqlite3_value **argv
15618 ){
15619   DateTime x;
15620   if( isDate(context, argc, argv, &x)==0 ){
15621     char zBuf[100];
15622     computeYMD(&x);
15623     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
15624     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15625   }
15626 }
15627 
15628 /*
15629 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
15630 **
15631 ** Return a string described by FORMAT.  Conversions as follows:
15632 **
15633 **   %d  day of month
15634 **   %f  ** fractional seconds  SS.SSS
15635 **   %H  hour 00-24
15636 **   %j  day of year 000-366
15637 **   %J  ** Julian day number
15638 **   %m  month 01-12
15639 **   %M  minute 00-59
15640 **   %s  seconds since 1970-01-01
15641 **   %S  seconds 00-59
15642 **   %w  day of week 0-6  sunday==0
15643 **   %W  week of year 00-53
15644 **   %Y  year 0000-9999
15645 **   %%  %
15646 */
15647 static void strftimeFunc(
15648   sqlite3_context *context,
15649   int argc,
15650   sqlite3_value **argv
15651 ){
15652   DateTime x;
15653   u64 n;
15654   size_t i,j;
15655   char *z;
15656   sqlite3 *db;
15657   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
15658   char zBuf[100];
15659   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
15660   db = sqlite3_context_db_handle(context);
15661   for(i=0, n=1; zFmt[i]; i++, n++){
15662     if( zFmt[i]=='%' ){
15663       switch( zFmt[i+1] ){
15664         case 'd':
15665         case 'H':
15666         case 'm':
15667         case 'M':
15668         case 'S':
15669         case 'W':
15670           n++;
15671           /* fall thru */
15672         case 'w':
15673         case '%':
15674           break;
15675         case 'f':
15676           n += 8;
15677           break;
15678         case 'j':
15679           n += 3;
15680           break;
15681         case 'Y':
15682           n += 8;
15683           break;
15684         case 's':
15685         case 'J':
15686           n += 50;
15687           break;
15688         default:
15689           return;  /* ERROR.  return a NULL */
15690       }
15691       i++;
15692     }
15693   }
15694   testcase( n==sizeof(zBuf)-1 );
15695   testcase( n==sizeof(zBuf) );
15696   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
15697   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
15698   if( n<sizeof(zBuf) ){
15699     z = zBuf;
15700   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
15701     sqlite3_result_error_toobig(context);
15702     return;
15703   }else{
15704     z = sqlite3DbMallocRaw(db, (int)n);
15705     if( z==0 ){
15706       sqlite3_result_error_nomem(context);
15707       return;
15708     }
15709   }
15710   computeJD(&x);
15711   computeYMD_HMS(&x);
15712   for(i=j=0; zFmt[i]; i++){
15713     if( zFmt[i]!='%' ){
15714       z[j++] = zFmt[i];
15715     }else{
15716       i++;
15717       switch( zFmt[i] ){
15718         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
15719         case 'f': {
15720           double s = x.s;
15721           if( s>59.999 ) s = 59.999;
15722           sqlite3_snprintf(7, &z[j],"%06.3f", s);
15723           j += sqlite3Strlen30(&z[j]);
15724           break;
15725         }
15726         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
15727         case 'W': /* Fall thru */
15728         case 'j': {
15729           int nDay;             /* Number of days since 1st day of year */
15730           DateTime y = x;
15731           y.validJD = 0;
15732           y.M = 1;
15733           y.D = 1;
15734           computeJD(&y);
15735           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
15736           if( zFmt[i]=='W' ){
15737             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
15738             wd = (int)(((x.iJD+43200000)/86400000)%7);
15739             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
15740             j += 2;
15741           }else{
15742             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
15743             j += 3;
15744           }
15745           break;
15746         }
15747         case 'J': {
15748           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
15749           j+=sqlite3Strlen30(&z[j]);
15750           break;
15751         }
15752         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
15753         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
15754         case 's': {
15755           sqlite3_snprintf(30,&z[j],"%lld",
15756                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
15757           j += sqlite3Strlen30(&z[j]);
15758           break;
15759         }
15760         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
15761         case 'w': {
15762           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
15763           break;
15764         }
15765         case 'Y': {
15766           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
15767           break;
15768         }
15769         default:   z[j++] = '%'; break;
15770       }
15771     }
15772   }
15773   z[j] = 0;
15774   sqlite3_result_text(context, z, -1,
15775                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
15776 }
15777 
15778 /*
15779 ** current_time()
15780 **
15781 ** This function returns the same value as time('now').
15782 */
15783 static void ctimeFunc(
15784   sqlite3_context *context,
15785   int NotUsed,
15786   sqlite3_value **NotUsed2
15787 ){
15788   UNUSED_PARAMETER2(NotUsed, NotUsed2);
15789   timeFunc(context, 0, 0);
15790 }
15791 
15792 /*
15793 ** current_date()
15794 **
15795 ** This function returns the same value as date('now').
15796 */
15797 static void cdateFunc(
15798   sqlite3_context *context,
15799   int NotUsed,
15800   sqlite3_value **NotUsed2
15801 ){
15802   UNUSED_PARAMETER2(NotUsed, NotUsed2);
15803   dateFunc(context, 0, 0);
15804 }
15805 
15806 /*
15807 ** current_timestamp()
15808 **
15809 ** This function returns the same value as datetime('now').
15810 */
15811 static void ctimestampFunc(
15812   sqlite3_context *context,
15813   int NotUsed,
15814   sqlite3_value **NotUsed2
15815 ){
15816   UNUSED_PARAMETER2(NotUsed, NotUsed2);
15817   datetimeFunc(context, 0, 0);
15818 }
15819 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
15820 
15821 #ifdef SQLITE_OMIT_DATETIME_FUNCS
15822 /*
15823 ** If the library is compiled to omit the full-scale date and time
15824 ** handling (to get a smaller binary), the following minimal version
15825 ** of the functions current_time(), current_date() and current_timestamp()
15826 ** are included instead. This is to support column declarations that
15827 ** include "DEFAULT CURRENT_TIME" etc.
15828 **
15829 ** This function uses the C-library functions time(), gmtime()
15830 ** and strftime(). The format string to pass to strftime() is supplied
15831 ** as the user-data for the function.
15832 */
15833 static void currentTimeFunc(
15834   sqlite3_context *context,
15835   int argc,
15836   sqlite3_value **argv
15837 ){
15838   time_t t;
15839   char *zFormat = (char *)sqlite3_user_data(context);
15840   sqlite3 *db;
15841   sqlite3_int64 iT;
15842   struct tm *pTm;
15843   struct tm sNow;
15844   char zBuf[20];
15845 
15846   UNUSED_PARAMETER(argc);
15847   UNUSED_PARAMETER(argv);
15848 
15849   iT = sqlite3StmtCurrentTime(context);
15850   if( iT<=0 ) return;
15851   t = iT/1000 - 10000*(sqlite3_int64)21086676;
15852 #ifdef HAVE_GMTIME_R
15853   pTm = gmtime_r(&t, &sNow);
15854 #else
15855   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
15856   pTm = gmtime(&t);
15857   if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
15858   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
15859 #endif
15860   if( pTm ){
15861     strftime(zBuf, 20, zFormat, &sNow);
15862     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15863   }
15864 }
15865 #endif
15866 
15867 /*
15868 ** This function registered all of the above C functions as SQL
15869 ** functions.  This should be the only routine in this file with
15870 ** external linkage.
15871 */
15872 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
15873   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
15874 #ifndef SQLITE_OMIT_DATETIME_FUNCS
15875     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
15876     FUNCTION(date,             -1, 0, 0, dateFunc      ),
15877     FUNCTION(time,             -1, 0, 0, timeFunc      ),
15878     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
15879     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
15880     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
15881     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
15882     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
15883 #else
15884     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
15885     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
15886     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
15887 #endif
15888   };
15889   int i;
15890   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
15891   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
15892 
15893   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
15894     sqlite3FuncDefInsert(pHash, &aFunc[i]);
15895   }
15896 }
15897 
15898 /************** End of date.c ************************************************/
15899 /************** Begin file os.c **********************************************/
15900 /*
15901 ** 2005 November 29
15902 **
15903 ** The author disclaims copyright to this source code.  In place of
15904 ** a legal notice, here is a blessing:
15905 **
15906 **    May you do good and not evil.
15907 **    May you find forgiveness for yourself and forgive others.
15908 **    May you share freely, never taking more than you give.
15909 **
15910 ******************************************************************************
15911 **
15912 ** This file contains OS interface code that is common to all
15913 ** architectures.
15914 */
15915 #define _SQLITE_OS_C_ 1
15916 #undef _SQLITE_OS_C_
15917 
15918 /*
15919 ** The default SQLite sqlite3_vfs implementations do not allocate
15920 ** memory (actually, os_unix.c allocates a small amount of memory
15921 ** from within OsOpen()), but some third-party implementations may.
15922 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
15923 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
15924 **
15925 ** The following functions are instrumented for malloc() failure
15926 ** testing:
15927 **
15928 **     sqlite3OsRead()
15929 **     sqlite3OsWrite()
15930 **     sqlite3OsSync()
15931 **     sqlite3OsFileSize()
15932 **     sqlite3OsLock()
15933 **     sqlite3OsCheckReservedLock()
15934 **     sqlite3OsFileControl()
15935 **     sqlite3OsShmMap()
15936 **     sqlite3OsOpen()
15937 **     sqlite3OsDelete()
15938 **     sqlite3OsAccess()
15939 **     sqlite3OsFullPathname()
15940 **
15941 */
15942 #if defined(SQLITE_TEST)
15943 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
15944   #define DO_OS_MALLOC_TEST(x)                                       \
15945   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
15946     void *pTstAlloc = sqlite3Malloc(10);                             \
15947     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
15948     sqlite3_free(pTstAlloc);                                         \
15949   }
15950 #else
15951   #define DO_OS_MALLOC_TEST(x)
15952 #endif
15953 
15954 /*
15955 ** The following routines are convenience wrappers around methods
15956 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
15957 ** of this would be completely automatic if SQLite were coded using
15958 ** C++ instead of plain old C.
15959 */
15960 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
15961   int rc = SQLITE_OK;
15962   if( pId->pMethods ){
15963     rc = pId->pMethods->xClose(pId);
15964     pId->pMethods = 0;
15965   }
15966   return rc;
15967 }
15968 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
15969   DO_OS_MALLOC_TEST(id);
15970   return id->pMethods->xRead(id, pBuf, amt, offset);
15971 }
15972 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
15973   DO_OS_MALLOC_TEST(id);
15974   return id->pMethods->xWrite(id, pBuf, amt, offset);
15975 }
15976 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
15977   return id->pMethods->xTruncate(id, size);
15978 }
15979 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
15980   DO_OS_MALLOC_TEST(id);
15981   return id->pMethods->xSync(id, flags);
15982 }
15983 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
15984   DO_OS_MALLOC_TEST(id);
15985   return id->pMethods->xFileSize(id, pSize);
15986 }
15987 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
15988   DO_OS_MALLOC_TEST(id);
15989   return id->pMethods->xLock(id, lockType);
15990 }
15991 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
15992   return id->pMethods->xUnlock(id, lockType);
15993 }
15994 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
15995   DO_OS_MALLOC_TEST(id);
15996   return id->pMethods->xCheckReservedLock(id, pResOut);
15997 }
15998 
15999 /*
16000 ** Use sqlite3OsFileControl() when we are doing something that might fail
16001 ** and we need to know about the failures.  Use sqlite3OsFileControlHint()
16002 ** when simply tossing information over the wall to the VFS and we do not
16003 ** really care if the VFS receives and understands the information since it
16004 ** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
16005 ** routine has no return value since the return value would be meaningless.
16006 */
16007 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
16008 #ifdef SQLITE_TEST
16009   if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
16010     /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
16011     ** is using a regular VFS, it is called after the corresponding
16012     ** transaction has been committed. Injecting a fault at this point
16013     ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
16014     ** but the transaction is committed anyway.
16015     **
16016     ** The core must call OsFileControl() though, not OsFileControlHint(),
16017     ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
16018     ** means the commit really has failed and an error should be returned
16019     ** to the user.  */
16020     DO_OS_MALLOC_TEST(id);
16021   }
16022 #endif
16023   return id->pMethods->xFileControl(id, op, pArg);
16024 }
16025 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
16026   (void)id->pMethods->xFileControl(id, op, pArg);
16027 }
16028 
16029 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
16030   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
16031   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
16032 }
16033 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
16034   return id->pMethods->xDeviceCharacteristics(id);
16035 }
16036 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
16037   return id->pMethods->xShmLock(id, offset, n, flags);
16038 }
16039 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
16040   id->pMethods->xShmBarrier(id);
16041 }
16042 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
16043   return id->pMethods->xShmUnmap(id, deleteFlag);
16044 }
16045 SQLITE_PRIVATE int sqlite3OsShmMap(
16046   sqlite3_file *id,               /* Database file handle */
16047   int iPage,
16048   int pgsz,
16049   int bExtend,                    /* True to extend file if necessary */
16050   void volatile **pp              /* OUT: Pointer to mapping */
16051 ){
16052   DO_OS_MALLOC_TEST(id);
16053   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
16054 }
16055 
16056 #if SQLITE_MAX_MMAP_SIZE>0
16057 /* The real implementation of xFetch and xUnfetch */
16058 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
16059   DO_OS_MALLOC_TEST(id);
16060   return id->pMethods->xFetch(id, iOff, iAmt, pp);
16061 }
16062 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
16063   return id->pMethods->xUnfetch(id, iOff, p);
16064 }
16065 #else
16066 /* No-op stubs to use when memory-mapped I/O is disabled */
16067 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
16068   *pp = 0;
16069   return SQLITE_OK;
16070 }
16071 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
16072   return SQLITE_OK;
16073 }
16074 #endif
16075 
16076 /*
16077 ** The next group of routines are convenience wrappers around the
16078 ** VFS methods.
16079 */
16080 SQLITE_PRIVATE int sqlite3OsOpen(
16081   sqlite3_vfs *pVfs,
16082   const char *zPath,
16083   sqlite3_file *pFile,
16084   int flags,
16085   int *pFlagsOut
16086 ){
16087   int rc;
16088   DO_OS_MALLOC_TEST(0);
16089   /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
16090   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
16091   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
16092   ** reaching the VFS. */
16093   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
16094   assert( rc==SQLITE_OK || pFile->pMethods==0 );
16095   return rc;
16096 }
16097 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
16098   DO_OS_MALLOC_TEST(0);
16099   assert( dirSync==0 || dirSync==1 );
16100   return pVfs->xDelete(pVfs, zPath, dirSync);
16101 }
16102 SQLITE_PRIVATE int sqlite3OsAccess(
16103   sqlite3_vfs *pVfs,
16104   const char *zPath,
16105   int flags,
16106   int *pResOut
16107 ){
16108   DO_OS_MALLOC_TEST(0);
16109   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
16110 }
16111 SQLITE_PRIVATE int sqlite3OsFullPathname(
16112   sqlite3_vfs *pVfs,
16113   const char *zPath,
16114   int nPathOut,
16115   char *zPathOut
16116 ){
16117   DO_OS_MALLOC_TEST(0);
16118   zPathOut[0] = 0;
16119   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
16120 }
16121 #ifndef SQLITE_OMIT_LOAD_EXTENSION
16122 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
16123   return pVfs->xDlOpen(pVfs, zPath);
16124 }
16125 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
16126   pVfs->xDlError(pVfs, nByte, zBufOut);
16127 }
16128 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
16129   return pVfs->xDlSym(pVfs, pHdle, zSym);
16130 }
16131 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
16132   pVfs->xDlClose(pVfs, pHandle);
16133 }
16134 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
16135 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
16136   return pVfs->xRandomness(pVfs, nByte, zBufOut);
16137 }
16138 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
16139   return pVfs->xSleep(pVfs, nMicro);
16140 }
16141 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
16142   int rc;
16143   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
16144   ** method to get the current date and time if that method is available
16145   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
16146   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
16147   ** unavailable.
16148   */
16149   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
16150     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
16151   }else{
16152     double r;
16153     rc = pVfs->xCurrentTime(pVfs, &r);
16154     *pTimeOut = (sqlite3_int64)(r*86400000.0);
16155   }
16156   return rc;
16157 }
16158 
16159 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
16160   sqlite3_vfs *pVfs,
16161   const char *zFile,
16162   sqlite3_file **ppFile,
16163   int flags,
16164   int *pOutFlags
16165 ){
16166   int rc = SQLITE_NOMEM;
16167   sqlite3_file *pFile;
16168   pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
16169   if( pFile ){
16170     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
16171     if( rc!=SQLITE_OK ){
16172       sqlite3_free(pFile);
16173     }else{
16174       *ppFile = pFile;
16175     }
16176   }
16177   return rc;
16178 }
16179 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
16180   int rc = SQLITE_OK;
16181   assert( pFile );
16182   rc = sqlite3OsClose(pFile);
16183   sqlite3_free(pFile);
16184   return rc;
16185 }
16186 
16187 /*
16188 ** This function is a wrapper around the OS specific implementation of
16189 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
16190 ** ability to simulate a malloc failure, so that the handling of an
16191 ** error in sqlite3_os_init() by the upper layers can be tested.
16192 */
16193 SQLITE_PRIVATE int sqlite3OsInit(void){
16194   void *p = sqlite3_malloc(10);
16195   if( p==0 ) return SQLITE_NOMEM;
16196   sqlite3_free(p);
16197   return sqlite3_os_init();
16198 }
16199 
16200 /*
16201 ** The list of all registered VFS implementations.
16202 */
16203 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
16204 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
16205 
16206 /*
16207 ** Locate a VFS by name.  If no name is given, simply return the
16208 ** first VFS on the list.
16209 */
16210 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
16211   sqlite3_vfs *pVfs = 0;
16212 #if SQLITE_THREADSAFE
16213   sqlite3_mutex *mutex;
16214 #endif
16215 #ifndef SQLITE_OMIT_AUTOINIT
16216   int rc = sqlite3_initialize();
16217   if( rc ) return 0;
16218 #endif
16219 #if SQLITE_THREADSAFE
16220   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
16221 #endif
16222   sqlite3_mutex_enter(mutex);
16223   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
16224     if( zVfs==0 ) break;
16225     if( strcmp(zVfs, pVfs->zName)==0 ) break;
16226   }
16227   sqlite3_mutex_leave(mutex);
16228   return pVfs;
16229 }
16230 
16231 /*
16232 ** Unlink a VFS from the linked list
16233 */
16234 static void vfsUnlink(sqlite3_vfs *pVfs){
16235   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
16236   if( pVfs==0 ){
16237     /* No-op */
16238   }else if( vfsList==pVfs ){
16239     vfsList = pVfs->pNext;
16240   }else if( vfsList ){
16241     sqlite3_vfs *p = vfsList;
16242     while( p->pNext && p->pNext!=pVfs ){
16243       p = p->pNext;
16244     }
16245     if( p->pNext==pVfs ){
16246       p->pNext = pVfs->pNext;
16247     }
16248   }
16249 }
16250 
16251 /*
16252 ** Register a VFS with the system.  It is harmless to register the same
16253 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
16254 ** true.
16255 */
16256 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
16257   MUTEX_LOGIC(sqlite3_mutex *mutex;)
16258 #ifndef SQLITE_OMIT_AUTOINIT
16259   int rc = sqlite3_initialize();
16260   if( rc ) return rc;
16261 #endif
16262   MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
16263   sqlite3_mutex_enter(mutex);
16264   vfsUnlink(pVfs);
16265   if( makeDflt || vfsList==0 ){
16266     pVfs->pNext = vfsList;
16267     vfsList = pVfs;
16268   }else{
16269     pVfs->pNext = vfsList->pNext;
16270     vfsList->pNext = pVfs;
16271   }
16272   assert(vfsList);
16273   sqlite3_mutex_leave(mutex);
16274   return SQLITE_OK;
16275 }
16276 
16277 /*
16278 ** Unregister a VFS so that it is no longer accessible.
16279 */
16280 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
16281 #if SQLITE_THREADSAFE
16282   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
16283 #endif
16284   sqlite3_mutex_enter(mutex);
16285   vfsUnlink(pVfs);
16286   sqlite3_mutex_leave(mutex);
16287   return SQLITE_OK;
16288 }
16289 
16290 /************** End of os.c **************************************************/
16291 /************** Begin file fault.c *******************************************/
16292 /*
16293 ** 2008 Jan 22
16294 **
16295 ** The author disclaims copyright to this source code.  In place of
16296 ** a legal notice, here is a blessing:
16297 **
16298 **    May you do good and not evil.
16299 **    May you find forgiveness for yourself and forgive others.
16300 **    May you share freely, never taking more than you give.
16301 **
16302 *************************************************************************
16303 **
16304 ** This file contains code to support the concept of "benign"
16305 ** malloc failures (when the xMalloc() or xRealloc() method of the
16306 ** sqlite3_mem_methods structure fails to allocate a block of memory
16307 ** and returns 0).
16308 **
16309 ** Most malloc failures are non-benign. After they occur, SQLite
16310 ** abandons the current operation and returns an error code (usually
16311 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
16312 ** fatal. For example, if a malloc fails while resizing a hash table, this
16313 ** is completely recoverable simply by not carrying out the resize. The
16314 ** hash table will continue to function normally.  So a malloc failure
16315 ** during a hash table resize is a benign fault.
16316 */
16317 
16318 
16319 #ifndef SQLITE_OMIT_BUILTIN_TEST
16320 
16321 /*
16322 ** Global variables.
16323 */
16324 typedef struct BenignMallocHooks BenignMallocHooks;
16325 static SQLITE_WSD struct BenignMallocHooks {
16326   void (*xBenignBegin)(void);
16327   void (*xBenignEnd)(void);
16328 } sqlite3Hooks = { 0, 0 };
16329 
16330 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
16331 ** structure.  If writable static data is unsupported on the target,
16332 ** we have to locate the state vector at run-time.  In the more common
16333 ** case where writable static data is supported, wsdHooks can refer directly
16334 ** to the "sqlite3Hooks" state vector declared above.
16335 */
16336 #ifdef SQLITE_OMIT_WSD
16337 # define wsdHooksInit \
16338   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
16339 # define wsdHooks x[0]
16340 #else
16341 # define wsdHooksInit
16342 # define wsdHooks sqlite3Hooks
16343 #endif
16344 
16345 
16346 /*
16347 ** Register hooks to call when sqlite3BeginBenignMalloc() and
16348 ** sqlite3EndBenignMalloc() are called, respectively.
16349 */
16350 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
16351   void (*xBenignBegin)(void),
16352   void (*xBenignEnd)(void)
16353 ){
16354   wsdHooksInit;
16355   wsdHooks.xBenignBegin = xBenignBegin;
16356   wsdHooks.xBenignEnd = xBenignEnd;
16357 }
16358 
16359 /*
16360 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
16361 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
16362 ** indicates that subsequent malloc failures are non-benign.
16363 */
16364 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
16365   wsdHooksInit;
16366   if( wsdHooks.xBenignBegin ){
16367     wsdHooks.xBenignBegin();
16368   }
16369 }
16370 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
16371   wsdHooksInit;
16372   if( wsdHooks.xBenignEnd ){
16373     wsdHooks.xBenignEnd();
16374   }
16375 }
16376 
16377 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
16378 
16379 /************** End of fault.c ***********************************************/
16380 /************** Begin file mem0.c ********************************************/
16381 /*
16382 ** 2008 October 28
16383 **
16384 ** The author disclaims copyright to this source code.  In place of
16385 ** a legal notice, here is a blessing:
16386 **
16387 **    May you do good and not evil.
16388 **    May you find forgiveness for yourself and forgive others.
16389 **    May you share freely, never taking more than you give.
16390 **
16391 *************************************************************************
16392 **
16393 ** This file contains a no-op memory allocation drivers for use when
16394 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
16395 ** here always fail.  SQLite will not operate with these drivers.  These
16396 ** are merely placeholders.  Real drivers must be substituted using
16397 ** sqlite3_config() before SQLite will operate.
16398 */
16399 
16400 /*
16401 ** This version of the memory allocator is the default.  It is
16402 ** used when no other memory allocator is specified using compile-time
16403 ** macros.
16404 */
16405 #ifdef SQLITE_ZERO_MALLOC
16406 
16407 /*
16408 ** No-op versions of all memory allocation routines
16409 */
16410 static void *sqlite3MemMalloc(int nByte){ return 0; }
16411 static void sqlite3MemFree(void *pPrior){ return; }
16412 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
16413 static int sqlite3MemSize(void *pPrior){ return 0; }
16414 static int sqlite3MemRoundup(int n){ return n; }
16415 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
16416 static void sqlite3MemShutdown(void *NotUsed){ return; }
16417 
16418 /*
16419 ** This routine is the only routine in this file with external linkage.
16420 **
16421 ** Populate the low-level memory allocation function pointers in
16422 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
16423 */
16424 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
16425   static const sqlite3_mem_methods defaultMethods = {
16426      sqlite3MemMalloc,
16427      sqlite3MemFree,
16428      sqlite3MemRealloc,
16429      sqlite3MemSize,
16430      sqlite3MemRoundup,
16431      sqlite3MemInit,
16432      sqlite3MemShutdown,
16433      0
16434   };
16435   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
16436 }
16437 
16438 #endif /* SQLITE_ZERO_MALLOC */
16439 
16440 /************** End of mem0.c ************************************************/
16441 /************** Begin file mem1.c ********************************************/
16442 /*
16443 ** 2007 August 14
16444 **
16445 ** The author disclaims copyright to this source code.  In place of
16446 ** a legal notice, here is a blessing:
16447 **
16448 **    May you do good and not evil.
16449 **    May you find forgiveness for yourself and forgive others.
16450 **    May you share freely, never taking more than you give.
16451 **
16452 *************************************************************************
16453 **
16454 ** This file contains low-level memory allocation drivers for when
16455 ** SQLite will use the standard C-library malloc/realloc/free interface
16456 ** to obtain the memory it needs.
16457 **
16458 ** This file contains implementations of the low-level memory allocation
16459 ** routines specified in the sqlite3_mem_methods object.  The content of
16460 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
16461 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
16462 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
16463 ** default configuration is to use memory allocation routines in this
16464 ** file.
16465 **
16466 ** C-preprocessor macro summary:
16467 **
16468 **    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
16469 **                                the malloc_usable_size() interface exists
16470 **                                on the target platform.  Or, this symbol
16471 **                                can be set manually, if desired.
16472 **                                If an equivalent interface exists by
16473 **                                a different name, using a separate -D
16474 **                                option to rename it.
16475 **
16476 **    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
16477 **                                memory allocator.  Set this symbol to enable
16478 **                                building on older macs.
16479 **
16480 **    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
16481 **                                _msize() on windows systems.  This might
16482 **                                be necessary when compiling for Delphi,
16483 **                                for example.
16484 */
16485 
16486 /*
16487 ** This version of the memory allocator is the default.  It is
16488 ** used when no other memory allocator is specified using compile-time
16489 ** macros.
16490 */
16491 #ifdef SQLITE_SYSTEM_MALLOC
16492 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
16493 
16494 /*
16495 ** Use the zone allocator available on apple products unless the
16496 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
16497 */
16498 #include <sys/sysctl.h>
16499 #include <malloc/malloc.h>
16500 #include <libkern/OSAtomic.h>
16501 static malloc_zone_t* _sqliteZone_;
16502 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
16503 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
16504 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
16505 #define SQLITE_MALLOCSIZE(x) \
16506         (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
16507 
16508 #else /* if not __APPLE__ */
16509 
16510 /*
16511 ** Use standard C library malloc and free on non-Apple systems.
16512 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
16513 */
16514 #define SQLITE_MALLOC(x)             malloc(x)
16515 #define SQLITE_FREE(x)               free(x)
16516 #define SQLITE_REALLOC(x,y)          realloc((x),(y))
16517 
16518 /*
16519 ** The malloc.h header file is needed for malloc_usable_size() function
16520 ** on some systems (e.g. Linux).
16521 */
16522 #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE)
16523 #  define SQLITE_USE_MALLOC_H
16524 #  define SQLITE_USE_MALLOC_USABLE_SIZE
16525 /*
16526 ** The MSVCRT has malloc_usable_size(), but it is called _msize().  The
16527 ** use of _msize() is automatic, but can be disabled by compiling with
16528 ** -DSQLITE_WITHOUT_MSIZE.  Using the _msize() function also requires
16529 ** the malloc.h header file.
16530 */
16531 #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
16532 #  define SQLITE_USE_MALLOC_H
16533 #  define SQLITE_USE_MSIZE
16534 #endif
16535 
16536 /*
16537 ** Include the malloc.h header file, if necessary.  Also set define macro
16538 ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
16539 ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
16540 ** The memory size function can always be overridden manually by defining
16541 ** the macro SQLITE_MALLOCSIZE to the desired function name.
16542 */
16543 #if defined(SQLITE_USE_MALLOC_H)
16544 #  include <malloc.h>
16545 #  if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
16546 #    if !defined(SQLITE_MALLOCSIZE)
16547 #      define SQLITE_MALLOCSIZE(x)   malloc_usable_size(x)
16548 #    endif
16549 #  elif defined(SQLITE_USE_MSIZE)
16550 #    if !defined(SQLITE_MALLOCSIZE)
16551 #      define SQLITE_MALLOCSIZE      _msize
16552 #    endif
16553 #  endif
16554 #endif /* defined(SQLITE_USE_MALLOC_H) */
16555 
16556 #endif /* __APPLE__ or not __APPLE__ */
16557 
16558 /*
16559 ** Like malloc(), but remember the size of the allocation
16560 ** so that we can find it later using sqlite3MemSize().
16561 **
16562 ** For this low-level routine, we are guaranteed that nByte>0 because
16563 ** cases of nByte<=0 will be intercepted and dealt with by higher level
16564 ** routines.
16565 */
16566 static void *sqlite3MemMalloc(int nByte){
16567 #ifdef SQLITE_MALLOCSIZE
16568   void *p = SQLITE_MALLOC( nByte );
16569   if( p==0 ){
16570     testcase( sqlite3GlobalConfig.xLog!=0 );
16571     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
16572   }
16573   return p;
16574 #else
16575   sqlite3_int64 *p;
16576   assert( nByte>0 );
16577   nByte = ROUND8(nByte);
16578   p = SQLITE_MALLOC( nByte+8 );
16579   if( p ){
16580     p[0] = nByte;
16581     p++;
16582   }else{
16583     testcase( sqlite3GlobalConfig.xLog!=0 );
16584     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
16585   }
16586   return (void *)p;
16587 #endif
16588 }
16589 
16590 /*
16591 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
16592 ** or sqlite3MemRealloc().
16593 **
16594 ** For this low-level routine, we already know that pPrior!=0 since
16595 ** cases where pPrior==0 will have been intecepted and dealt with
16596 ** by higher-level routines.
16597 */
16598 static void sqlite3MemFree(void *pPrior){
16599 #ifdef SQLITE_MALLOCSIZE
16600   SQLITE_FREE(pPrior);
16601 #else
16602   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
16603   assert( pPrior!=0 );
16604   p--;
16605   SQLITE_FREE(p);
16606 #endif
16607 }
16608 
16609 /*
16610 ** Report the allocated size of a prior return from xMalloc()
16611 ** or xRealloc().
16612 */
16613 static int sqlite3MemSize(void *pPrior){
16614 #ifdef SQLITE_MALLOCSIZE
16615   return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
16616 #else
16617   sqlite3_int64 *p;
16618   if( pPrior==0 ) return 0;
16619   p = (sqlite3_int64*)pPrior;
16620   p--;
16621   return (int)p[0];
16622 #endif
16623 }
16624 
16625 /*
16626 ** Like realloc().  Resize an allocation previously obtained from
16627 ** sqlite3MemMalloc().
16628 **
16629 ** For this low-level interface, we know that pPrior!=0.  Cases where
16630 ** pPrior==0 while have been intercepted by higher-level routine and
16631 ** redirected to xMalloc.  Similarly, we know that nByte>0 because
16632 ** cases where nByte<=0 will have been intercepted by higher-level
16633 ** routines and redirected to xFree.
16634 */
16635 static void *sqlite3MemRealloc(void *pPrior, int nByte){
16636 #ifdef SQLITE_MALLOCSIZE
16637   void *p = SQLITE_REALLOC(pPrior, nByte);
16638   if( p==0 ){
16639     testcase( sqlite3GlobalConfig.xLog!=0 );
16640     sqlite3_log(SQLITE_NOMEM,
16641       "failed memory resize %u to %u bytes",
16642       SQLITE_MALLOCSIZE(pPrior), nByte);
16643   }
16644   return p;
16645 #else
16646   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
16647   assert( pPrior!=0 && nByte>0 );
16648   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
16649   p--;
16650   p = SQLITE_REALLOC(p, nByte+8 );
16651   if( p ){
16652     p[0] = nByte;
16653     p++;
16654   }else{
16655     testcase( sqlite3GlobalConfig.xLog!=0 );
16656     sqlite3_log(SQLITE_NOMEM,
16657       "failed memory resize %u to %u bytes",
16658       sqlite3MemSize(pPrior), nByte);
16659   }
16660   return (void*)p;
16661 #endif
16662 }
16663 
16664 /*
16665 ** Round up a request size to the next valid allocation size.
16666 */
16667 static int sqlite3MemRoundup(int n){
16668   return ROUND8(n);
16669 }
16670 
16671 /*
16672 ** Initialize this module.
16673 */
16674 static int sqlite3MemInit(void *NotUsed){
16675 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
16676   int cpuCount;
16677   size_t len;
16678   if( _sqliteZone_ ){
16679     return SQLITE_OK;
16680   }
16681   len = sizeof(cpuCount);
16682   /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
16683   sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
16684   if( cpuCount>1 ){
16685     /* defer MT decisions to system malloc */
16686     _sqliteZone_ = malloc_default_zone();
16687   }else{
16688     /* only 1 core, use our own zone to contention over global locks,
16689     ** e.g. we have our own dedicated locks */
16690     bool success;
16691     malloc_zone_t* newzone = malloc_create_zone(4096, 0);
16692     malloc_set_zone_name(newzone, "Sqlite_Heap");
16693     do{
16694       success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
16695                                  (void * volatile *)&_sqliteZone_);
16696     }while(!_sqliteZone_);
16697     if( !success ){
16698       /* somebody registered a zone first */
16699       malloc_destroy_zone(newzone);
16700     }
16701   }
16702 #endif
16703   UNUSED_PARAMETER(NotUsed);
16704   return SQLITE_OK;
16705 }
16706 
16707 /*
16708 ** Deinitialize this module.
16709 */
16710 static void sqlite3MemShutdown(void *NotUsed){
16711   UNUSED_PARAMETER(NotUsed);
16712   return;
16713 }
16714 
16715 /*
16716 ** This routine is the only routine in this file with external linkage.
16717 **
16718 ** Populate the low-level memory allocation function pointers in
16719 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
16720 */
16721 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
16722   static const sqlite3_mem_methods defaultMethods = {
16723      sqlite3MemMalloc,
16724      sqlite3MemFree,
16725      sqlite3MemRealloc,
16726      sqlite3MemSize,
16727      sqlite3MemRoundup,
16728      sqlite3MemInit,
16729      sqlite3MemShutdown,
16730      0
16731   };
16732   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
16733 }
16734 
16735 #endif /* SQLITE_SYSTEM_MALLOC */
16736 
16737 /************** End of mem1.c ************************************************/
16738 /************** Begin file mem2.c ********************************************/
16739 /*
16740 ** 2007 August 15
16741 **
16742 ** The author disclaims copyright to this source code.  In place of
16743 ** a legal notice, here is a blessing:
16744 **
16745 **    May you do good and not evil.
16746 **    May you find forgiveness for yourself and forgive others.
16747 **    May you share freely, never taking more than you give.
16748 **
16749 *************************************************************************
16750 **
16751 ** This file contains low-level memory allocation drivers for when
16752 ** SQLite will use the standard C-library malloc/realloc/free interface
16753 ** to obtain the memory it needs while adding lots of additional debugging
16754 ** information to each allocation in order to help detect and fix memory
16755 ** leaks and memory usage errors.
16756 **
16757 ** This file contains implementations of the low-level memory allocation
16758 ** routines specified in the sqlite3_mem_methods object.
16759 */
16760 
16761 /*
16762 ** This version of the memory allocator is used only if the
16763 ** SQLITE_MEMDEBUG macro is defined
16764 */
16765 #ifdef SQLITE_MEMDEBUG
16766 
16767 /*
16768 ** The backtrace functionality is only available with GLIBC
16769 */
16770 #ifdef __GLIBC__
16771   extern int backtrace(void**,int);
16772   extern void backtrace_symbols_fd(void*const*,int,int);
16773 #else
16774 # define backtrace(A,B) 1
16775 # define backtrace_symbols_fd(A,B,C)
16776 #endif
16777 /* #include <stdio.h> */
16778 
16779 /*
16780 ** Each memory allocation looks like this:
16781 **
16782 **  ------------------------------------------------------------------------
16783 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
16784 **  ------------------------------------------------------------------------
16785 **
16786 ** The application code sees only a pointer to the allocation.  We have
16787 ** to back up from the allocation pointer to find the MemBlockHdr.  The
16788 ** MemBlockHdr tells us the size of the allocation and the number of
16789 ** backtrace pointers.  There is also a guard word at the end of the
16790 ** MemBlockHdr.
16791 */
16792 struct MemBlockHdr {
16793   i64 iSize;                          /* Size of this allocation */
16794   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
16795   char nBacktrace;                    /* Number of backtraces on this alloc */
16796   char nBacktraceSlots;               /* Available backtrace slots */
16797   u8 nTitle;                          /* Bytes of title; includes '\0' */
16798   u8 eType;                           /* Allocation type code */
16799   int iForeGuard;                     /* Guard word for sanity */
16800 };
16801 
16802 /*
16803 ** Guard words
16804 */
16805 #define FOREGUARD 0x80F5E153
16806 #define REARGUARD 0xE4676B53
16807 
16808 /*
16809 ** Number of malloc size increments to track.
16810 */
16811 #define NCSIZE  1000
16812 
16813 /*
16814 ** All of the static variables used by this module are collected
16815 ** into a single structure named "mem".  This is to keep the
16816 ** static variables organized and to reduce namespace pollution
16817 ** when this module is combined with other in the amalgamation.
16818 */
16819 static struct {
16820 
16821   /*
16822   ** Mutex to control access to the memory allocation subsystem.
16823   */
16824   sqlite3_mutex *mutex;
16825 
16826   /*
16827   ** Head and tail of a linked list of all outstanding allocations
16828   */
16829   struct MemBlockHdr *pFirst;
16830   struct MemBlockHdr *pLast;
16831 
16832   /*
16833   ** The number of levels of backtrace to save in new allocations.
16834   */
16835   int nBacktrace;
16836   void (*xBacktrace)(int, int, void **);
16837 
16838   /*
16839   ** Title text to insert in front of each block
16840   */
16841   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
16842   char zTitle[100];  /* The title text */
16843 
16844   /*
16845   ** sqlite3MallocDisallow() increments the following counter.
16846   ** sqlite3MallocAllow() decrements it.
16847   */
16848   int disallow; /* Do not allow memory allocation */
16849 
16850   /*
16851   ** Gather statistics on the sizes of memory allocations.
16852   ** nAlloc[i] is the number of allocation attempts of i*8
16853   ** bytes.  i==NCSIZE is the number of allocation attempts for
16854   ** sizes more than NCSIZE*8 bytes.
16855   */
16856   int nAlloc[NCSIZE];      /* Total number of allocations */
16857   int nCurrent[NCSIZE];    /* Current number of allocations */
16858   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
16859 
16860 } mem;
16861 
16862 
16863 /*
16864 ** Adjust memory usage statistics
16865 */
16866 static void adjustStats(int iSize, int increment){
16867   int i = ROUND8(iSize)/8;
16868   if( i>NCSIZE-1 ){
16869     i = NCSIZE - 1;
16870   }
16871   if( increment>0 ){
16872     mem.nAlloc[i]++;
16873     mem.nCurrent[i]++;
16874     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
16875       mem.mxCurrent[i] = mem.nCurrent[i];
16876     }
16877   }else{
16878     mem.nCurrent[i]--;
16879     assert( mem.nCurrent[i]>=0 );
16880   }
16881 }
16882 
16883 /*
16884 ** Given an allocation, find the MemBlockHdr for that allocation.
16885 **
16886 ** This routine checks the guards at either end of the allocation and
16887 ** if they are incorrect it asserts.
16888 */
16889 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
16890   struct MemBlockHdr *p;
16891   int *pInt;
16892   u8 *pU8;
16893   int nReserve;
16894 
16895   p = (struct MemBlockHdr*)pAllocation;
16896   p--;
16897   assert( p->iForeGuard==(int)FOREGUARD );
16898   nReserve = ROUND8(p->iSize);
16899   pInt = (int*)pAllocation;
16900   pU8 = (u8*)pAllocation;
16901   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
16902   /* This checks any of the "extra" bytes allocated due
16903   ** to rounding up to an 8 byte boundary to ensure
16904   ** they haven't been overwritten.
16905   */
16906   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
16907   return p;
16908 }
16909 
16910 /*
16911 ** Return the number of bytes currently allocated at address p.
16912 */
16913 static int sqlite3MemSize(void *p){
16914   struct MemBlockHdr *pHdr;
16915   if( !p ){
16916     return 0;
16917   }
16918   pHdr = sqlite3MemsysGetHeader(p);
16919   return (int)pHdr->iSize;
16920 }
16921 
16922 /*
16923 ** Initialize the memory allocation subsystem.
16924 */
16925 static int sqlite3MemInit(void *NotUsed){
16926   UNUSED_PARAMETER(NotUsed);
16927   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
16928   if( !sqlite3GlobalConfig.bMemstat ){
16929     /* If memory status is enabled, then the malloc.c wrapper will already
16930     ** hold the STATIC_MEM mutex when the routines here are invoked. */
16931     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16932   }
16933   return SQLITE_OK;
16934 }
16935 
16936 /*
16937 ** Deinitialize the memory allocation subsystem.
16938 */
16939 static void sqlite3MemShutdown(void *NotUsed){
16940   UNUSED_PARAMETER(NotUsed);
16941   mem.mutex = 0;
16942 }
16943 
16944 /*
16945 ** Round up a request size to the next valid allocation size.
16946 */
16947 static int sqlite3MemRoundup(int n){
16948   return ROUND8(n);
16949 }
16950 
16951 /*
16952 ** Fill a buffer with pseudo-random bytes.  This is used to preset
16953 ** the content of a new memory allocation to unpredictable values and
16954 ** to clear the content of a freed allocation to unpredictable values.
16955 */
16956 static void randomFill(char *pBuf, int nByte){
16957   unsigned int x, y, r;
16958   x = SQLITE_PTR_TO_INT(pBuf);
16959   y = nByte | 1;
16960   while( nByte >= 4 ){
16961     x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
16962     y = y*1103515245 + 12345;
16963     r = x ^ y;
16964     *(int*)pBuf = r;
16965     pBuf += 4;
16966     nByte -= 4;
16967   }
16968   while( nByte-- > 0 ){
16969     x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
16970     y = y*1103515245 + 12345;
16971     r = x ^ y;
16972     *(pBuf++) = r & 0xff;
16973   }
16974 }
16975 
16976 /*
16977 ** Allocate nByte bytes of memory.
16978 */
16979 static void *sqlite3MemMalloc(int nByte){
16980   struct MemBlockHdr *pHdr;
16981   void **pBt;
16982   char *z;
16983   int *pInt;
16984   void *p = 0;
16985   int totalSize;
16986   int nReserve;
16987   sqlite3_mutex_enter(mem.mutex);
16988   assert( mem.disallow==0 );
16989   nReserve = ROUND8(nByte);
16990   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
16991                mem.nBacktrace*sizeof(void*) + mem.nTitle;
16992   p = malloc(totalSize);
16993   if( p ){
16994     z = p;
16995     pBt = (void**)&z[mem.nTitle];
16996     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
16997     pHdr->pNext = 0;
16998     pHdr->pPrev = mem.pLast;
16999     if( mem.pLast ){
17000       mem.pLast->pNext = pHdr;
17001     }else{
17002       mem.pFirst = pHdr;
17003     }
17004     mem.pLast = pHdr;
17005     pHdr->iForeGuard = FOREGUARD;
17006     pHdr->eType = MEMTYPE_HEAP;
17007     pHdr->nBacktraceSlots = mem.nBacktrace;
17008     pHdr->nTitle = mem.nTitle;
17009     if( mem.nBacktrace ){
17010       void *aAddr[40];
17011       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
17012       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
17013       assert(pBt[0]);
17014       if( mem.xBacktrace ){
17015         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
17016       }
17017     }else{
17018       pHdr->nBacktrace = 0;
17019     }
17020     if( mem.nTitle ){
17021       memcpy(z, mem.zTitle, mem.nTitle);
17022     }
17023     pHdr->iSize = nByte;
17024     adjustStats(nByte, +1);
17025     pInt = (int*)&pHdr[1];
17026     pInt[nReserve/sizeof(int)] = REARGUARD;
17027     randomFill((char*)pInt, nByte);
17028     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
17029     p = (void*)pInt;
17030   }
17031   sqlite3_mutex_leave(mem.mutex);
17032   return p;
17033 }
17034 
17035 /*
17036 ** Free memory.
17037 */
17038 static void sqlite3MemFree(void *pPrior){
17039   struct MemBlockHdr *pHdr;
17040   void **pBt;
17041   char *z;
17042   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
17043        || mem.mutex!=0 );
17044   pHdr = sqlite3MemsysGetHeader(pPrior);
17045   pBt = (void**)pHdr;
17046   pBt -= pHdr->nBacktraceSlots;
17047   sqlite3_mutex_enter(mem.mutex);
17048   if( pHdr->pPrev ){
17049     assert( pHdr->pPrev->pNext==pHdr );
17050     pHdr->pPrev->pNext = pHdr->pNext;
17051   }else{
17052     assert( mem.pFirst==pHdr );
17053     mem.pFirst = pHdr->pNext;
17054   }
17055   if( pHdr->pNext ){
17056     assert( pHdr->pNext->pPrev==pHdr );
17057     pHdr->pNext->pPrev = pHdr->pPrev;
17058   }else{
17059     assert( mem.pLast==pHdr );
17060     mem.pLast = pHdr->pPrev;
17061   }
17062   z = (char*)pBt;
17063   z -= pHdr->nTitle;
17064   adjustStats((int)pHdr->iSize, -1);
17065   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
17066                 (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
17067   free(z);
17068   sqlite3_mutex_leave(mem.mutex);
17069 }
17070 
17071 /*
17072 ** Change the size of an existing memory allocation.
17073 **
17074 ** For this debugging implementation, we *always* make a copy of the
17075 ** allocation into a new place in memory.  In this way, if the
17076 ** higher level code is using pointer to the old allocation, it is
17077 ** much more likely to break and we are much more liking to find
17078 ** the error.
17079 */
17080 static void *sqlite3MemRealloc(void *pPrior, int nByte){
17081   struct MemBlockHdr *pOldHdr;
17082   void *pNew;
17083   assert( mem.disallow==0 );
17084   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
17085   pOldHdr = sqlite3MemsysGetHeader(pPrior);
17086   pNew = sqlite3MemMalloc(nByte);
17087   if( pNew ){
17088     memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
17089     if( nByte>pOldHdr->iSize ){
17090       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
17091     }
17092     sqlite3MemFree(pPrior);
17093   }
17094   return pNew;
17095 }
17096 
17097 /*
17098 ** Populate the low-level memory allocation function pointers in
17099 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
17100 */
17101 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
17102   static const sqlite3_mem_methods defaultMethods = {
17103      sqlite3MemMalloc,
17104      sqlite3MemFree,
17105      sqlite3MemRealloc,
17106      sqlite3MemSize,
17107      sqlite3MemRoundup,
17108      sqlite3MemInit,
17109      sqlite3MemShutdown,
17110      0
17111   };
17112   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
17113 }
17114 
17115 /*
17116 ** Set the "type" of an allocation.
17117 */
17118 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
17119   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
17120     struct MemBlockHdr *pHdr;
17121     pHdr = sqlite3MemsysGetHeader(p);
17122     assert( pHdr->iForeGuard==FOREGUARD );
17123     pHdr->eType = eType;
17124   }
17125 }
17126 
17127 /*
17128 ** Return TRUE if the mask of type in eType matches the type of the
17129 ** allocation p.  Also return true if p==NULL.
17130 **
17131 ** This routine is designed for use within an assert() statement, to
17132 ** verify the type of an allocation.  For example:
17133 **
17134 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
17135 */
17136 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
17137   int rc = 1;
17138   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
17139     struct MemBlockHdr *pHdr;
17140     pHdr = sqlite3MemsysGetHeader(p);
17141     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
17142     if( (pHdr->eType&eType)==0 ){
17143       rc = 0;
17144     }
17145   }
17146   return rc;
17147 }
17148 
17149 /*
17150 ** Return TRUE if the mask of type in eType matches no bits of the type of the
17151 ** allocation p.  Also return true if p==NULL.
17152 **
17153 ** This routine is designed for use within an assert() statement, to
17154 ** verify the type of an allocation.  For example:
17155 **
17156 **     assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
17157 */
17158 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
17159   int rc = 1;
17160   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
17161     struct MemBlockHdr *pHdr;
17162     pHdr = sqlite3MemsysGetHeader(p);
17163     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
17164     if( (pHdr->eType&eType)!=0 ){
17165       rc = 0;
17166     }
17167   }
17168   return rc;
17169 }
17170 
17171 /*
17172 ** Set the number of backtrace levels kept for each allocation.
17173 ** A value of zero turns off backtracing.  The number is always rounded
17174 ** up to a multiple of 2.
17175 */
17176 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
17177   if( depth<0 ){ depth = 0; }
17178   if( depth>20 ){ depth = 20; }
17179   depth = (depth+1)&0xfe;
17180   mem.nBacktrace = depth;
17181 }
17182 
17183 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
17184   mem.xBacktrace = xBacktrace;
17185 }
17186 
17187 /*
17188 ** Set the title string for subsequent allocations.
17189 */
17190 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
17191   unsigned int n = sqlite3Strlen30(zTitle) + 1;
17192   sqlite3_mutex_enter(mem.mutex);
17193   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
17194   memcpy(mem.zTitle, zTitle, n);
17195   mem.zTitle[n] = 0;
17196   mem.nTitle = ROUND8(n);
17197   sqlite3_mutex_leave(mem.mutex);
17198 }
17199 
17200 SQLITE_PRIVATE void sqlite3MemdebugSync(){
17201   struct MemBlockHdr *pHdr;
17202   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
17203     void **pBt = (void**)pHdr;
17204     pBt -= pHdr->nBacktraceSlots;
17205     mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
17206   }
17207 }
17208 
17209 /*
17210 ** Open the file indicated and write a log of all unfreed memory
17211 ** allocations into that log.
17212 */
17213 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
17214   FILE *out;
17215   struct MemBlockHdr *pHdr;
17216   void **pBt;
17217   int i;
17218   out = fopen(zFilename, "w");
17219   if( out==0 ){
17220     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17221                     zFilename);
17222     return;
17223   }
17224   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
17225     char *z = (char*)pHdr;
17226     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
17227     fprintf(out, "**** %lld bytes at %p from %s ****\n",
17228             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
17229     if( pHdr->nBacktrace ){
17230       fflush(out);
17231       pBt = (void**)pHdr;
17232       pBt -= pHdr->nBacktraceSlots;
17233       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
17234       fprintf(out, "\n");
17235     }
17236   }
17237   fprintf(out, "COUNTS:\n");
17238   for(i=0; i<NCSIZE-1; i++){
17239     if( mem.nAlloc[i] ){
17240       fprintf(out, "   %5d: %10d %10d %10d\n",
17241             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
17242     }
17243   }
17244   if( mem.nAlloc[NCSIZE-1] ){
17245     fprintf(out, "   %5d: %10d %10d %10d\n",
17246              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
17247              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
17248   }
17249   fclose(out);
17250 }
17251 
17252 /*
17253 ** Return the number of times sqlite3MemMalloc() has been called.
17254 */
17255 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
17256   int i;
17257   int nTotal = 0;
17258   for(i=0; i<NCSIZE; i++){
17259     nTotal += mem.nAlloc[i];
17260   }
17261   return nTotal;
17262 }
17263 
17264 
17265 #endif /* SQLITE_MEMDEBUG */
17266 
17267 /************** End of mem2.c ************************************************/
17268 /************** Begin file mem3.c ********************************************/
17269 /*
17270 ** 2007 October 14
17271 **
17272 ** The author disclaims copyright to this source code.  In place of
17273 ** a legal notice, here is a blessing:
17274 **
17275 **    May you do good and not evil.
17276 **    May you find forgiveness for yourself and forgive others.
17277 **    May you share freely, never taking more than you give.
17278 **
17279 *************************************************************************
17280 ** This file contains the C functions that implement a memory
17281 ** allocation subsystem for use by SQLite.
17282 **
17283 ** This version of the memory allocation subsystem omits all
17284 ** use of malloc(). The SQLite user supplies a block of memory
17285 ** before calling sqlite3_initialize() from which allocations
17286 ** are made and returned by the xMalloc() and xRealloc()
17287 ** implementations. Once sqlite3_initialize() has been called,
17288 ** the amount of memory available to SQLite is fixed and cannot
17289 ** be changed.
17290 **
17291 ** This version of the memory allocation subsystem is included
17292 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
17293 */
17294 
17295 /*
17296 ** This version of the memory allocator is only built into the library
17297 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
17298 ** mean that the library will use a memory-pool by default, just that
17299 ** it is available. The mempool allocator is activated by calling
17300 ** sqlite3_config().
17301 */
17302 #ifdef SQLITE_ENABLE_MEMSYS3
17303 
17304 /*
17305 ** Maximum size (in Mem3Blocks) of a "small" chunk.
17306 */
17307 #define MX_SMALL 10
17308 
17309 
17310 /*
17311 ** Number of freelist hash slots
17312 */
17313 #define N_HASH  61
17314 
17315 /*
17316 ** A memory allocation (also called a "chunk") consists of two or
17317 ** more blocks where each block is 8 bytes.  The first 8 bytes are
17318 ** a header that is not returned to the user.
17319 **
17320 ** A chunk is two or more blocks that is either checked out or
17321 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
17322 ** size of the allocation in blocks if the allocation is free.
17323 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
17324 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
17325 ** is true if the previous chunk is checked out and false if the
17326 ** previous chunk is free.  The u.hdr.prevSize field is the size of
17327 ** the previous chunk in blocks if the previous chunk is on the
17328 ** freelist. If the previous chunk is checked out, then
17329 ** u.hdr.prevSize can be part of the data for that chunk and should
17330 ** not be read or written.
17331 **
17332 ** We often identify a chunk by its index in mem3.aPool[].  When
17333 ** this is done, the chunk index refers to the second block of
17334 ** the chunk.  In this way, the first chunk has an index of 1.
17335 ** A chunk index of 0 means "no such chunk" and is the equivalent
17336 ** of a NULL pointer.
17337 **
17338 ** The second block of free chunks is of the form u.list.  The
17339 ** two fields form a double-linked list of chunks of related sizes.
17340 ** Pointers to the head of the list are stored in mem3.aiSmall[]
17341 ** for smaller chunks and mem3.aiHash[] for larger chunks.
17342 **
17343 ** The second block of a chunk is user data if the chunk is checked
17344 ** out.  If a chunk is checked out, the user data may extend into
17345 ** the u.hdr.prevSize value of the following chunk.
17346 */
17347 typedef struct Mem3Block Mem3Block;
17348 struct Mem3Block {
17349   union {
17350     struct {
17351       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
17352       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
17353     } hdr;
17354     struct {
17355       u32 next;       /* Index in mem3.aPool[] of next free chunk */
17356       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
17357     } list;
17358   } u;
17359 };
17360 
17361 /*
17362 ** All of the static variables used by this module are collected
17363 ** into a single structure named "mem3".  This is to keep the
17364 ** static variables organized and to reduce namespace pollution
17365 ** when this module is combined with other in the amalgamation.
17366 */
17367 static SQLITE_WSD struct Mem3Global {
17368   /*
17369   ** Memory available for allocation. nPool is the size of the array
17370   ** (in Mem3Blocks) pointed to by aPool less 2.
17371   */
17372   u32 nPool;
17373   Mem3Block *aPool;
17374 
17375   /*
17376   ** True if we are evaluating an out-of-memory callback.
17377   */
17378   int alarmBusy;
17379 
17380   /*
17381   ** Mutex to control access to the memory allocation subsystem.
17382   */
17383   sqlite3_mutex *mutex;
17384 
17385   /*
17386   ** The minimum amount of free space that we have seen.
17387   */
17388   u32 mnMaster;
17389 
17390   /*
17391   ** iMaster is the index of the master chunk.  Most new allocations
17392   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
17393   ** of the current master.  iMaster is 0 if there is not master chunk.
17394   ** The master chunk is not in either the aiHash[] or aiSmall[].
17395   */
17396   u32 iMaster;
17397   u32 szMaster;
17398 
17399   /*
17400   ** Array of lists of free blocks according to the block size
17401   ** for smaller chunks, or a hash on the block size for larger
17402   ** chunks.
17403   */
17404   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
17405   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
17406 } mem3 = { 97535575 };
17407 
17408 #define mem3 GLOBAL(struct Mem3Global, mem3)
17409 
17410 /*
17411 ** Unlink the chunk at mem3.aPool[i] from list it is currently
17412 ** on.  *pRoot is the list that i is a member of.
17413 */
17414 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
17415   u32 next = mem3.aPool[i].u.list.next;
17416   u32 prev = mem3.aPool[i].u.list.prev;
17417   assert( sqlite3_mutex_held(mem3.mutex) );
17418   if( prev==0 ){
17419     *pRoot = next;
17420   }else{
17421     mem3.aPool[prev].u.list.next = next;
17422   }
17423   if( next ){
17424     mem3.aPool[next].u.list.prev = prev;
17425   }
17426   mem3.aPool[i].u.list.next = 0;
17427   mem3.aPool[i].u.list.prev = 0;
17428 }
17429 
17430 /*
17431 ** Unlink the chunk at index i from
17432 ** whatever list is currently a member of.
17433 */
17434 static void memsys3Unlink(u32 i){
17435   u32 size, hash;
17436   assert( sqlite3_mutex_held(mem3.mutex) );
17437   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
17438   assert( i>=1 );
17439   size = mem3.aPool[i-1].u.hdr.size4x/4;
17440   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
17441   assert( size>=2 );
17442   if( size <= MX_SMALL ){
17443     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
17444   }else{
17445     hash = size % N_HASH;
17446     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
17447   }
17448 }
17449 
17450 /*
17451 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
17452 ** at *pRoot.
17453 */
17454 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
17455   assert( sqlite3_mutex_held(mem3.mutex) );
17456   mem3.aPool[i].u.list.next = *pRoot;
17457   mem3.aPool[i].u.list.prev = 0;
17458   if( *pRoot ){
17459     mem3.aPool[*pRoot].u.list.prev = i;
17460   }
17461   *pRoot = i;
17462 }
17463 
17464 /*
17465 ** Link the chunk at index i into either the appropriate
17466 ** small chunk list, or into the large chunk hash table.
17467 */
17468 static void memsys3Link(u32 i){
17469   u32 size, hash;
17470   assert( sqlite3_mutex_held(mem3.mutex) );
17471   assert( i>=1 );
17472   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
17473   size = mem3.aPool[i-1].u.hdr.size4x/4;
17474   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
17475   assert( size>=2 );
17476   if( size <= MX_SMALL ){
17477     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
17478   }else{
17479     hash = size % N_HASH;
17480     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
17481   }
17482 }
17483 
17484 /*
17485 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
17486 ** will already be held (obtained by code in malloc.c) if
17487 ** sqlite3GlobalConfig.bMemStat is true.
17488 */
17489 static void memsys3Enter(void){
17490   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
17491     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17492   }
17493   sqlite3_mutex_enter(mem3.mutex);
17494 }
17495 static void memsys3Leave(void){
17496   sqlite3_mutex_leave(mem3.mutex);
17497 }
17498 
17499 /*
17500 ** Called when we are unable to satisfy an allocation of nBytes.
17501 */
17502 static void memsys3OutOfMemory(int nByte){
17503   if( !mem3.alarmBusy ){
17504     mem3.alarmBusy = 1;
17505     assert( sqlite3_mutex_held(mem3.mutex) );
17506     sqlite3_mutex_leave(mem3.mutex);
17507     sqlite3_release_memory(nByte);
17508     sqlite3_mutex_enter(mem3.mutex);
17509     mem3.alarmBusy = 0;
17510   }
17511 }
17512 
17513 
17514 /*
17515 ** Chunk i is a free chunk that has been unlinked.  Adjust its
17516 ** size parameters for check-out and return a pointer to the
17517 ** user portion of the chunk.
17518 */
17519 static void *memsys3Checkout(u32 i, u32 nBlock){
17520   u32 x;
17521   assert( sqlite3_mutex_held(mem3.mutex) );
17522   assert( i>=1 );
17523   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
17524   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
17525   x = mem3.aPool[i-1].u.hdr.size4x;
17526   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
17527   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
17528   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
17529   return &mem3.aPool[i];
17530 }
17531 
17532 /*
17533 ** Carve a piece off of the end of the mem3.iMaster free chunk.
17534 ** Return a pointer to the new allocation.  Or, if the master chunk
17535 ** is not large enough, return 0.
17536 */
17537 static void *memsys3FromMaster(u32 nBlock){
17538   assert( sqlite3_mutex_held(mem3.mutex) );
17539   assert( mem3.szMaster>=nBlock );
17540   if( nBlock>=mem3.szMaster-1 ){
17541     /* Use the entire master */
17542     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
17543     mem3.iMaster = 0;
17544     mem3.szMaster = 0;
17545     mem3.mnMaster = 0;
17546     return p;
17547   }else{
17548     /* Split the master block.  Return the tail. */
17549     u32 newi, x;
17550     newi = mem3.iMaster + mem3.szMaster - nBlock;
17551     assert( newi > mem3.iMaster+1 );
17552     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
17553     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
17554     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
17555     mem3.szMaster -= nBlock;
17556     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
17557     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
17558     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
17559     if( mem3.szMaster < mem3.mnMaster ){
17560       mem3.mnMaster = mem3.szMaster;
17561     }
17562     return (void*)&mem3.aPool[newi];
17563   }
17564 }
17565 
17566 /*
17567 ** *pRoot is the head of a list of free chunks of the same size
17568 ** or same size hash.  In other words, *pRoot is an entry in either
17569 ** mem3.aiSmall[] or mem3.aiHash[].
17570 **
17571 ** This routine examines all entries on the given list and tries
17572 ** to coalesce each entries with adjacent free chunks.
17573 **
17574 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
17575 ** the current mem3.iMaster with the new larger chunk.  In order for
17576 ** this mem3.iMaster replacement to work, the master chunk must be
17577 ** linked into the hash tables.  That is not the normal state of
17578 ** affairs, of course.  The calling routine must link the master
17579 ** chunk before invoking this routine, then must unlink the (possibly
17580 ** changed) master chunk once this routine has finished.
17581 */
17582 static void memsys3Merge(u32 *pRoot){
17583   u32 iNext, prev, size, i, x;
17584 
17585   assert( sqlite3_mutex_held(mem3.mutex) );
17586   for(i=*pRoot; i>0; i=iNext){
17587     iNext = mem3.aPool[i].u.list.next;
17588     size = mem3.aPool[i-1].u.hdr.size4x;
17589     assert( (size&1)==0 );
17590     if( (size&2)==0 ){
17591       memsys3UnlinkFromList(i, pRoot);
17592       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
17593       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
17594       if( prev==iNext ){
17595         iNext = mem3.aPool[prev].u.list.next;
17596       }
17597       memsys3Unlink(prev);
17598       size = i + size/4 - prev;
17599       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
17600       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
17601       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
17602       memsys3Link(prev);
17603       i = prev;
17604     }else{
17605       size /= 4;
17606     }
17607     if( size>mem3.szMaster ){
17608       mem3.iMaster = i;
17609       mem3.szMaster = size;
17610     }
17611   }
17612 }
17613 
17614 /*
17615 ** Return a block of memory of at least nBytes in size.
17616 ** Return NULL if unable.
17617 **
17618 ** This function assumes that the necessary mutexes, if any, are
17619 ** already held by the caller. Hence "Unsafe".
17620 */
17621 static void *memsys3MallocUnsafe(int nByte){
17622   u32 i;
17623   u32 nBlock;
17624   u32 toFree;
17625 
17626   assert( sqlite3_mutex_held(mem3.mutex) );
17627   assert( sizeof(Mem3Block)==8 );
17628   if( nByte<=12 ){
17629     nBlock = 2;
17630   }else{
17631     nBlock = (nByte + 11)/8;
17632   }
17633   assert( nBlock>=2 );
17634 
17635   /* STEP 1:
17636   ** Look for an entry of the correct size in either the small
17637   ** chunk table or in the large chunk hash table.  This is
17638   ** successful most of the time (about 9 times out of 10).
17639   */
17640   if( nBlock <= MX_SMALL ){
17641     i = mem3.aiSmall[nBlock-2];
17642     if( i>0 ){
17643       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
17644       return memsys3Checkout(i, nBlock);
17645     }
17646   }else{
17647     int hash = nBlock % N_HASH;
17648     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
17649       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
17650         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
17651         return memsys3Checkout(i, nBlock);
17652       }
17653     }
17654   }
17655 
17656   /* STEP 2:
17657   ** Try to satisfy the allocation by carving a piece off of the end
17658   ** of the master chunk.  This step usually works if step 1 fails.
17659   */
17660   if( mem3.szMaster>=nBlock ){
17661     return memsys3FromMaster(nBlock);
17662   }
17663 
17664 
17665   /* STEP 3:
17666   ** Loop through the entire memory pool.  Coalesce adjacent free
17667   ** chunks.  Recompute the master chunk as the largest free chunk.
17668   ** Then try again to satisfy the allocation by carving a piece off
17669   ** of the end of the master chunk.  This step happens very
17670   ** rarely (we hope!)
17671   */
17672   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
17673     memsys3OutOfMemory(toFree);
17674     if( mem3.iMaster ){
17675       memsys3Link(mem3.iMaster);
17676       mem3.iMaster = 0;
17677       mem3.szMaster = 0;
17678     }
17679     for(i=0; i<N_HASH; i++){
17680       memsys3Merge(&mem3.aiHash[i]);
17681     }
17682     for(i=0; i<MX_SMALL-1; i++){
17683       memsys3Merge(&mem3.aiSmall[i]);
17684     }
17685     if( mem3.szMaster ){
17686       memsys3Unlink(mem3.iMaster);
17687       if( mem3.szMaster>=nBlock ){
17688         return memsys3FromMaster(nBlock);
17689       }
17690     }
17691   }
17692 
17693   /* If none of the above worked, then we fail. */
17694   return 0;
17695 }
17696 
17697 /*
17698 ** Free an outstanding memory allocation.
17699 **
17700 ** This function assumes that the necessary mutexes, if any, are
17701 ** already held by the caller. Hence "Unsafe".
17702 */
17703 static void memsys3FreeUnsafe(void *pOld){
17704   Mem3Block *p = (Mem3Block*)pOld;
17705   int i;
17706   u32 size, x;
17707   assert( sqlite3_mutex_held(mem3.mutex) );
17708   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
17709   i = p - mem3.aPool;
17710   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
17711   size = mem3.aPool[i-1].u.hdr.size4x/4;
17712   assert( i+size<=mem3.nPool+1 );
17713   mem3.aPool[i-1].u.hdr.size4x &= ~1;
17714   mem3.aPool[i+size-1].u.hdr.prevSize = size;
17715   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
17716   memsys3Link(i);
17717 
17718   /* Try to expand the master using the newly freed chunk */
17719   if( mem3.iMaster ){
17720     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
17721       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
17722       mem3.iMaster -= size;
17723       mem3.szMaster += size;
17724       memsys3Unlink(mem3.iMaster);
17725       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
17726       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
17727       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
17728     }
17729     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
17730     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
17731       memsys3Unlink(mem3.iMaster+mem3.szMaster);
17732       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
17733       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
17734       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
17735     }
17736   }
17737 }
17738 
17739 /*
17740 ** Return the size of an outstanding allocation, in bytes.  The
17741 ** size returned omits the 8-byte header overhead.  This only
17742 ** works for chunks that are currently checked out.
17743 */
17744 static int memsys3Size(void *p){
17745   Mem3Block *pBlock;
17746   if( p==0 ) return 0;
17747   pBlock = (Mem3Block*)p;
17748   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
17749   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
17750 }
17751 
17752 /*
17753 ** Round up a request size to the next valid allocation size.
17754 */
17755 static int memsys3Roundup(int n){
17756   if( n<=12 ){
17757     return 12;
17758   }else{
17759     return ((n+11)&~7) - 4;
17760   }
17761 }
17762 
17763 /*
17764 ** Allocate nBytes of memory.
17765 */
17766 static void *memsys3Malloc(int nBytes){
17767   sqlite3_int64 *p;
17768   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
17769   memsys3Enter();
17770   p = memsys3MallocUnsafe(nBytes);
17771   memsys3Leave();
17772   return (void*)p;
17773 }
17774 
17775 /*
17776 ** Free memory.
17777 */
17778 static void memsys3Free(void *pPrior){
17779   assert( pPrior );
17780   memsys3Enter();
17781   memsys3FreeUnsafe(pPrior);
17782   memsys3Leave();
17783 }
17784 
17785 /*
17786 ** Change the size of an existing memory allocation
17787 */
17788 static void *memsys3Realloc(void *pPrior, int nBytes){
17789   int nOld;
17790   void *p;
17791   if( pPrior==0 ){
17792     return sqlite3_malloc(nBytes);
17793   }
17794   if( nBytes<=0 ){
17795     sqlite3_free(pPrior);
17796     return 0;
17797   }
17798   nOld = memsys3Size(pPrior);
17799   if( nBytes<=nOld && nBytes>=nOld-128 ){
17800     return pPrior;
17801   }
17802   memsys3Enter();
17803   p = memsys3MallocUnsafe(nBytes);
17804   if( p ){
17805     if( nOld<nBytes ){
17806       memcpy(p, pPrior, nOld);
17807     }else{
17808       memcpy(p, pPrior, nBytes);
17809     }
17810     memsys3FreeUnsafe(pPrior);
17811   }
17812   memsys3Leave();
17813   return p;
17814 }
17815 
17816 /*
17817 ** Initialize this module.
17818 */
17819 static int memsys3Init(void *NotUsed){
17820   UNUSED_PARAMETER(NotUsed);
17821   if( !sqlite3GlobalConfig.pHeap ){
17822     return SQLITE_ERROR;
17823   }
17824 
17825   /* Store a pointer to the memory block in global structure mem3. */
17826   assert( sizeof(Mem3Block)==8 );
17827   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
17828   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
17829 
17830   /* Initialize the master block. */
17831   mem3.szMaster = mem3.nPool;
17832   mem3.mnMaster = mem3.szMaster;
17833   mem3.iMaster = 1;
17834   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
17835   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
17836   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
17837 
17838   return SQLITE_OK;
17839 }
17840 
17841 /*
17842 ** Deinitialize this module.
17843 */
17844 static void memsys3Shutdown(void *NotUsed){
17845   UNUSED_PARAMETER(NotUsed);
17846   mem3.mutex = 0;
17847   return;
17848 }
17849 
17850 
17851 
17852 /*
17853 ** Open the file indicated and write a log of all unfreed memory
17854 ** allocations into that log.
17855 */
17856 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
17857 #ifdef SQLITE_DEBUG
17858   FILE *out;
17859   u32 i, j;
17860   u32 size;
17861   if( zFilename==0 || zFilename[0]==0 ){
17862     out = stdout;
17863   }else{
17864     out = fopen(zFilename, "w");
17865     if( out==0 ){
17866       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17867                       zFilename);
17868       return;
17869     }
17870   }
17871   memsys3Enter();
17872   fprintf(out, "CHUNKS:\n");
17873   for(i=1; i<=mem3.nPool; i+=size/4){
17874     size = mem3.aPool[i-1].u.hdr.size4x;
17875     if( size/4<=1 ){
17876       fprintf(out, "%p size error\n", &mem3.aPool[i]);
17877       assert( 0 );
17878       break;
17879     }
17880     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
17881       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
17882       assert( 0 );
17883       break;
17884     }
17885     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
17886       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
17887       assert( 0 );
17888       break;
17889     }
17890     if( size&1 ){
17891       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
17892     }else{
17893       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
17894                   i==mem3.iMaster ? " **master**" : "");
17895     }
17896   }
17897   for(i=0; i<MX_SMALL-1; i++){
17898     if( mem3.aiSmall[i]==0 ) continue;
17899     fprintf(out, "small(%2d):", i);
17900     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
17901       fprintf(out, " %p(%d)", &mem3.aPool[j],
17902               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
17903     }
17904     fprintf(out, "\n");
17905   }
17906   for(i=0; i<N_HASH; i++){
17907     if( mem3.aiHash[i]==0 ) continue;
17908     fprintf(out, "hash(%2d):", i);
17909     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
17910       fprintf(out, " %p(%d)", &mem3.aPool[j],
17911               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
17912     }
17913     fprintf(out, "\n");
17914   }
17915   fprintf(out, "master=%d\n", mem3.iMaster);
17916   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
17917   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
17918   sqlite3_mutex_leave(mem3.mutex);
17919   if( out==stdout ){
17920     fflush(stdout);
17921   }else{
17922     fclose(out);
17923   }
17924 #else
17925   UNUSED_PARAMETER(zFilename);
17926 #endif
17927 }
17928 
17929 /*
17930 ** This routine is the only routine in this file with external
17931 ** linkage.
17932 **
17933 ** Populate the low-level memory allocation function pointers in
17934 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
17935 ** arguments specify the block of memory to manage.
17936 **
17937 ** This routine is only called by sqlite3_config(), and therefore
17938 ** is not required to be threadsafe (it is not).
17939 */
17940 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
17941   static const sqlite3_mem_methods mempoolMethods = {
17942      memsys3Malloc,
17943      memsys3Free,
17944      memsys3Realloc,
17945      memsys3Size,
17946      memsys3Roundup,
17947      memsys3Init,
17948      memsys3Shutdown,
17949      0
17950   };
17951   return &mempoolMethods;
17952 }
17953 
17954 #endif /* SQLITE_ENABLE_MEMSYS3 */
17955 
17956 /************** End of mem3.c ************************************************/
17957 /************** Begin file mem5.c ********************************************/
17958 /*
17959 ** 2007 October 14
17960 **
17961 ** The author disclaims copyright to this source code.  In place of
17962 ** a legal notice, here is a blessing:
17963 **
17964 **    May you do good and not evil.
17965 **    May you find forgiveness for yourself and forgive others.
17966 **    May you share freely, never taking more than you give.
17967 **
17968 *************************************************************************
17969 ** This file contains the C functions that implement a memory
17970 ** allocation subsystem for use by SQLite.
17971 **
17972 ** This version of the memory allocation subsystem omits all
17973 ** use of malloc(). The application gives SQLite a block of memory
17974 ** before calling sqlite3_initialize() from which allocations
17975 ** are made and returned by the xMalloc() and xRealloc()
17976 ** implementations. Once sqlite3_initialize() has been called,
17977 ** the amount of memory available to SQLite is fixed and cannot
17978 ** be changed.
17979 **
17980 ** This version of the memory allocation subsystem is included
17981 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
17982 **
17983 ** This memory allocator uses the following algorithm:
17984 **
17985 **   1.  All memory allocations sizes are rounded up to a power of 2.
17986 **
17987 **   2.  If two adjacent free blocks are the halves of a larger block,
17988 **       then the two blocks are coalesced into the single larger block.
17989 **
17990 **   3.  New memory is allocated from the first available free block.
17991 **
17992 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
17993 ** Concerning Dynamic Storage Allocation". Journal of the Association for
17994 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
17995 **
17996 ** Let n be the size of the largest allocation divided by the minimum
17997 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
17998 ** be the maximum amount of memory ever outstanding at one time.  Let
17999 ** N be the total amount of memory available for allocation.  Robson
18000 ** proved that this memory allocator will never breakdown due to
18001 ** fragmentation as long as the following constraint holds:
18002 **
18003 **      N >=  M*(1 + log2(n)/2) - n + 1
18004 **
18005 ** The sqlite3_status() logic tracks the maximum values of n and M so
18006 ** that an application can, at any time, verify this constraint.
18007 */
18008 
18009 /*
18010 ** This version of the memory allocator is used only when
18011 ** SQLITE_ENABLE_MEMSYS5 is defined.
18012 */
18013 #ifdef SQLITE_ENABLE_MEMSYS5
18014 
18015 /*
18016 ** A minimum allocation is an instance of the following structure.
18017 ** Larger allocations are an array of these structures where the
18018 ** size of the array is a power of 2.
18019 **
18020 ** The size of this object must be a power of two.  That fact is
18021 ** verified in memsys5Init().
18022 */
18023 typedef struct Mem5Link Mem5Link;
18024 struct Mem5Link {
18025   int next;       /* Index of next free chunk */
18026   int prev;       /* Index of previous free chunk */
18027 };
18028 
18029 /*
18030 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
18031 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
18032 ** it is not actually possible to reach this limit.
18033 */
18034 #define LOGMAX 30
18035 
18036 /*
18037 ** Masks used for mem5.aCtrl[] elements.
18038 */
18039 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
18040 #define CTRL_FREE     0x20    /* True if not checked out */
18041 
18042 /*
18043 ** All of the static variables used by this module are collected
18044 ** into a single structure named "mem5".  This is to keep the
18045 ** static variables organized and to reduce namespace pollution
18046 ** when this module is combined with other in the amalgamation.
18047 */
18048 static SQLITE_WSD struct Mem5Global {
18049   /*
18050   ** Memory available for allocation
18051   */
18052   int szAtom;      /* Smallest possible allocation in bytes */
18053   int nBlock;      /* Number of szAtom sized blocks in zPool */
18054   u8 *zPool;       /* Memory available to be allocated */
18055 
18056   /*
18057   ** Mutex to control access to the memory allocation subsystem.
18058   */
18059   sqlite3_mutex *mutex;
18060 
18061   /*
18062   ** Performance statistics
18063   */
18064   u64 nAlloc;         /* Total number of calls to malloc */
18065   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
18066   u64 totalExcess;    /* Total internal fragmentation */
18067   u32 currentOut;     /* Current checkout, including internal fragmentation */
18068   u32 currentCount;   /* Current number of distinct checkouts */
18069   u32 maxOut;         /* Maximum instantaneous currentOut */
18070   u32 maxCount;       /* Maximum instantaneous currentCount */
18071   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
18072 
18073   /*
18074   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
18075   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
18076   ** and so forth.
18077   */
18078   int aiFreelist[LOGMAX+1];
18079 
18080   /*
18081   ** Space for tracking which blocks are checked out and the size
18082   ** of each block.  One byte per block.
18083   */
18084   u8 *aCtrl;
18085 
18086 } mem5;
18087 
18088 /*
18089 ** Access the static variable through a macro for SQLITE_OMIT_WSD.
18090 */
18091 #define mem5 GLOBAL(struct Mem5Global, mem5)
18092 
18093 /*
18094 ** Assuming mem5.zPool is divided up into an array of Mem5Link
18095 ** structures, return a pointer to the idx-th such link.
18096 */
18097 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
18098 
18099 /*
18100 ** Unlink the chunk at mem5.aPool[i] from list it is currently
18101 ** on.  It should be found on mem5.aiFreelist[iLogsize].
18102 */
18103 static void memsys5Unlink(int i, int iLogsize){
18104   int next, prev;
18105   assert( i>=0 && i<mem5.nBlock );
18106   assert( iLogsize>=0 && iLogsize<=LOGMAX );
18107   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
18108 
18109   next = MEM5LINK(i)->next;
18110   prev = MEM5LINK(i)->prev;
18111   if( prev<0 ){
18112     mem5.aiFreelist[iLogsize] = next;
18113   }else{
18114     MEM5LINK(prev)->next = next;
18115   }
18116   if( next>=0 ){
18117     MEM5LINK(next)->prev = prev;
18118   }
18119 }
18120 
18121 /*
18122 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
18123 ** free list.
18124 */
18125 static void memsys5Link(int i, int iLogsize){
18126   int x;
18127   assert( sqlite3_mutex_held(mem5.mutex) );
18128   assert( i>=0 && i<mem5.nBlock );
18129   assert( iLogsize>=0 && iLogsize<=LOGMAX );
18130   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
18131 
18132   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
18133   MEM5LINK(i)->prev = -1;
18134   if( x>=0 ){
18135     assert( x<mem5.nBlock );
18136     MEM5LINK(x)->prev = i;
18137   }
18138   mem5.aiFreelist[iLogsize] = i;
18139 }
18140 
18141 /*
18142 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
18143 ** will already be held (obtained by code in malloc.c) if
18144 ** sqlite3GlobalConfig.bMemStat is true.
18145 */
18146 static void memsys5Enter(void){
18147   sqlite3_mutex_enter(mem5.mutex);
18148 }
18149 static void memsys5Leave(void){
18150   sqlite3_mutex_leave(mem5.mutex);
18151 }
18152 
18153 /*
18154 ** Return the size of an outstanding allocation, in bytes.  The
18155 ** size returned omits the 8-byte header overhead.  This only
18156 ** works for chunks that are currently checked out.
18157 */
18158 static int memsys5Size(void *p){
18159   int iSize = 0;
18160   if( p ){
18161     int i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
18162     assert( i>=0 && i<mem5.nBlock );
18163     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
18164   }
18165   return iSize;
18166 }
18167 
18168 /*
18169 ** Return a block of memory of at least nBytes in size.
18170 ** Return NULL if unable.  Return NULL if nBytes==0.
18171 **
18172 ** The caller guarantees that nByte is positive.
18173 **
18174 ** The caller has obtained a mutex prior to invoking this
18175 ** routine so there is never any chance that two or more
18176 ** threads can be in this routine at the same time.
18177 */
18178 static void *memsys5MallocUnsafe(int nByte){
18179   int i;           /* Index of a mem5.aPool[] slot */
18180   int iBin;        /* Index into mem5.aiFreelist[] */
18181   int iFullSz;     /* Size of allocation rounded up to power of 2 */
18182   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
18183 
18184   /* nByte must be a positive */
18185   assert( nByte>0 );
18186 
18187   /* Keep track of the maximum allocation request.  Even unfulfilled
18188   ** requests are counted */
18189   if( (u32)nByte>mem5.maxRequest ){
18190     mem5.maxRequest = nByte;
18191   }
18192 
18193   /* Abort if the requested allocation size is larger than the largest
18194   ** power of two that we can represent using 32-bit signed integers.
18195   */
18196   if( nByte > 0x40000000 ){
18197     return 0;
18198   }
18199 
18200   /* Round nByte up to the next valid power of two */
18201   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
18202 
18203   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
18204   ** block.  If not, then split a block of the next larger power of
18205   ** two in order to create a new free block of size iLogsize.
18206   */
18207   for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
18208   if( iBin>LOGMAX ){
18209     testcase( sqlite3GlobalConfig.xLog!=0 );
18210     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
18211     return 0;
18212   }
18213   i = mem5.aiFreelist[iBin];
18214   memsys5Unlink(i, iBin);
18215   while( iBin>iLogsize ){
18216     int newSize;
18217 
18218     iBin--;
18219     newSize = 1 << iBin;
18220     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
18221     memsys5Link(i+newSize, iBin);
18222   }
18223   mem5.aCtrl[i] = iLogsize;
18224 
18225   /* Update allocator performance statistics. */
18226   mem5.nAlloc++;
18227   mem5.totalAlloc += iFullSz;
18228   mem5.totalExcess += iFullSz - nByte;
18229   mem5.currentCount++;
18230   mem5.currentOut += iFullSz;
18231   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
18232   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
18233 
18234 #ifdef SQLITE_DEBUG
18235   /* Make sure the allocated memory does not assume that it is set to zero
18236   ** or retains a value from a previous allocation */
18237   memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
18238 #endif
18239 
18240   /* Return a pointer to the allocated memory. */
18241   return (void*)&mem5.zPool[i*mem5.szAtom];
18242 }
18243 
18244 /*
18245 ** Free an outstanding memory allocation.
18246 */
18247 static void memsys5FreeUnsafe(void *pOld){
18248   u32 size, iLogsize;
18249   int iBlock;
18250 
18251   /* Set iBlock to the index of the block pointed to by pOld in
18252   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
18253   */
18254   iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
18255 
18256   /* Check that the pointer pOld points to a valid, non-free block. */
18257   assert( iBlock>=0 && iBlock<mem5.nBlock );
18258   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
18259   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
18260 
18261   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
18262   size = 1<<iLogsize;
18263   assert( iBlock+size-1<(u32)mem5.nBlock );
18264 
18265   mem5.aCtrl[iBlock] |= CTRL_FREE;
18266   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
18267   assert( mem5.currentCount>0 );
18268   assert( mem5.currentOut>=(size*mem5.szAtom) );
18269   mem5.currentCount--;
18270   mem5.currentOut -= size*mem5.szAtom;
18271   assert( mem5.currentOut>0 || mem5.currentCount==0 );
18272   assert( mem5.currentCount>0 || mem5.currentOut==0 );
18273 
18274   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
18275   while( ALWAYS(iLogsize<LOGMAX) ){
18276     int iBuddy;
18277     if( (iBlock>>iLogsize) & 1 ){
18278       iBuddy = iBlock - size;
18279     }else{
18280       iBuddy = iBlock + size;
18281     }
18282     assert( iBuddy>=0 );
18283     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
18284     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
18285     memsys5Unlink(iBuddy, iLogsize);
18286     iLogsize++;
18287     if( iBuddy<iBlock ){
18288       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
18289       mem5.aCtrl[iBlock] = 0;
18290       iBlock = iBuddy;
18291     }else{
18292       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
18293       mem5.aCtrl[iBuddy] = 0;
18294     }
18295     size *= 2;
18296   }
18297 
18298 #ifdef SQLITE_DEBUG
18299   /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
18300   ** not used after being freed */
18301   memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
18302 #endif
18303 
18304   memsys5Link(iBlock, iLogsize);
18305 }
18306 
18307 /*
18308 ** Allocate nBytes of memory.
18309 */
18310 static void *memsys5Malloc(int nBytes){
18311   sqlite3_int64 *p = 0;
18312   if( nBytes>0 ){
18313     memsys5Enter();
18314     p = memsys5MallocUnsafe(nBytes);
18315     memsys5Leave();
18316   }
18317   return (void*)p;
18318 }
18319 
18320 /*
18321 ** Free memory.
18322 **
18323 ** The outer layer memory allocator prevents this routine from
18324 ** being called with pPrior==0.
18325 */
18326 static void memsys5Free(void *pPrior){
18327   assert( pPrior!=0 );
18328   memsys5Enter();
18329   memsys5FreeUnsafe(pPrior);
18330   memsys5Leave();
18331 }
18332 
18333 /*
18334 ** Change the size of an existing memory allocation.
18335 **
18336 ** The outer layer memory allocator prevents this routine from
18337 ** being called with pPrior==0.
18338 **
18339 ** nBytes is always a value obtained from a prior call to
18340 ** memsys5Round().  Hence nBytes is always a non-negative power
18341 ** of two.  If nBytes==0 that means that an oversize allocation
18342 ** (an allocation larger than 0x40000000) was requested and this
18343 ** routine should return 0 without freeing pPrior.
18344 */
18345 static void *memsys5Realloc(void *pPrior, int nBytes){
18346   int nOld;
18347   void *p;
18348   assert( pPrior!=0 );
18349   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
18350   assert( nBytes>=0 );
18351   if( nBytes==0 ){
18352     return 0;
18353   }
18354   nOld = memsys5Size(pPrior);
18355   if( nBytes<=nOld ){
18356     return pPrior;
18357   }
18358   memsys5Enter();
18359   p = memsys5MallocUnsafe(nBytes);
18360   if( p ){
18361     memcpy(p, pPrior, nOld);
18362     memsys5FreeUnsafe(pPrior);
18363   }
18364   memsys5Leave();
18365   return p;
18366 }
18367 
18368 /*
18369 ** Round up a request size to the next valid allocation size.  If
18370 ** the allocation is too large to be handled by this allocation system,
18371 ** return 0.
18372 **
18373 ** All allocations must be a power of two and must be expressed by a
18374 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
18375 ** or 1073741824 bytes.
18376 */
18377 static int memsys5Roundup(int n){
18378   int iFullSz;
18379   if( n > 0x40000000 ) return 0;
18380   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
18381   return iFullSz;
18382 }
18383 
18384 /*
18385 ** Return the ceiling of the logarithm base 2 of iValue.
18386 **
18387 ** Examples:   memsys5Log(1) -> 0
18388 **             memsys5Log(2) -> 1
18389 **             memsys5Log(4) -> 2
18390 **             memsys5Log(5) -> 3
18391 **             memsys5Log(8) -> 3
18392 **             memsys5Log(9) -> 4
18393 */
18394 static int memsys5Log(int iValue){
18395   int iLog;
18396   for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
18397   return iLog;
18398 }
18399 
18400 /*
18401 ** Initialize the memory allocator.
18402 **
18403 ** This routine is not threadsafe.  The caller must be holding a mutex
18404 ** to prevent multiple threads from entering at the same time.
18405 */
18406 static int memsys5Init(void *NotUsed){
18407   int ii;            /* Loop counter */
18408   int nByte;         /* Number of bytes of memory available to this allocator */
18409   u8 *zByte;         /* Memory usable by this allocator */
18410   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
18411   int iOffset;       /* An offset into mem5.aCtrl[] */
18412 
18413   UNUSED_PARAMETER(NotUsed);
18414 
18415   /* For the purposes of this routine, disable the mutex */
18416   mem5.mutex = 0;
18417 
18418   /* The size of a Mem5Link object must be a power of two.  Verify that
18419   ** this is case.
18420   */
18421   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
18422 
18423   nByte = sqlite3GlobalConfig.nHeap;
18424   zByte = (u8*)sqlite3GlobalConfig.pHeap;
18425   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
18426 
18427   /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
18428   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
18429   mem5.szAtom = (1<<nMinLog);
18430   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
18431     mem5.szAtom = mem5.szAtom << 1;
18432   }
18433 
18434   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
18435   mem5.zPool = zByte;
18436   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
18437 
18438   for(ii=0; ii<=LOGMAX; ii++){
18439     mem5.aiFreelist[ii] = -1;
18440   }
18441 
18442   iOffset = 0;
18443   for(ii=LOGMAX; ii>=0; ii--){
18444     int nAlloc = (1<<ii);
18445     if( (iOffset+nAlloc)<=mem5.nBlock ){
18446       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
18447       memsys5Link(iOffset, ii);
18448       iOffset += nAlloc;
18449     }
18450     assert((iOffset+nAlloc)>mem5.nBlock);
18451   }
18452 
18453   /* If a mutex is required for normal operation, allocate one */
18454   if( sqlite3GlobalConfig.bMemstat==0 ){
18455     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18456   }
18457 
18458   return SQLITE_OK;
18459 }
18460 
18461 /*
18462 ** Deinitialize this module.
18463 */
18464 static void memsys5Shutdown(void *NotUsed){
18465   UNUSED_PARAMETER(NotUsed);
18466   mem5.mutex = 0;
18467   return;
18468 }
18469 
18470 #ifdef SQLITE_TEST
18471 /*
18472 ** Open the file indicated and write a log of all unfreed memory
18473 ** allocations into that log.
18474 */
18475 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
18476   FILE *out;
18477   int i, j, n;
18478   int nMinLog;
18479 
18480   if( zFilename==0 || zFilename[0]==0 ){
18481     out = stdout;
18482   }else{
18483     out = fopen(zFilename, "w");
18484     if( out==0 ){
18485       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
18486                       zFilename);
18487       return;
18488     }
18489   }
18490   memsys5Enter();
18491   nMinLog = memsys5Log(mem5.szAtom);
18492   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
18493     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
18494     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
18495   }
18496   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
18497   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
18498   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
18499   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
18500   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
18501   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
18502   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
18503   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
18504   memsys5Leave();
18505   if( out==stdout ){
18506     fflush(stdout);
18507   }else{
18508     fclose(out);
18509   }
18510 }
18511 #endif
18512 
18513 /*
18514 ** This routine is the only routine in this file with external
18515 ** linkage. It returns a pointer to a static sqlite3_mem_methods
18516 ** struct populated with the memsys5 methods.
18517 */
18518 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
18519   static const sqlite3_mem_methods memsys5Methods = {
18520      memsys5Malloc,
18521      memsys5Free,
18522      memsys5Realloc,
18523      memsys5Size,
18524      memsys5Roundup,
18525      memsys5Init,
18526      memsys5Shutdown,
18527      0
18528   };
18529   return &memsys5Methods;
18530 }
18531 
18532 #endif /* SQLITE_ENABLE_MEMSYS5 */
18533 
18534 /************** End of mem5.c ************************************************/
18535 /************** Begin file mutex.c *******************************************/
18536 /*
18537 ** 2007 August 14
18538 **
18539 ** The author disclaims copyright to this source code.  In place of
18540 ** a legal notice, here is a blessing:
18541 **
18542 **    May you do good and not evil.
18543 **    May you find forgiveness for yourself and forgive others.
18544 **    May you share freely, never taking more than you give.
18545 **
18546 *************************************************************************
18547 ** This file contains the C functions that implement mutexes.
18548 **
18549 ** This file contains code that is common across all mutex implementations.
18550 */
18551 
18552 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
18553 /*
18554 ** For debugging purposes, record when the mutex subsystem is initialized
18555 ** and uninitialized so that we can assert() if there is an attempt to
18556 ** allocate a mutex while the system is uninitialized.
18557 */
18558 static SQLITE_WSD int mutexIsInit = 0;
18559 #endif /* SQLITE_DEBUG */
18560 
18561 
18562 #ifndef SQLITE_MUTEX_OMIT
18563 /*
18564 ** Initialize the mutex system.
18565 */
18566 SQLITE_PRIVATE int sqlite3MutexInit(void){
18567   int rc = SQLITE_OK;
18568   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
18569     /* If the xMutexAlloc method has not been set, then the user did not
18570     ** install a mutex implementation via sqlite3_config() prior to
18571     ** sqlite3_initialize() being called. This block copies pointers to
18572     ** the default implementation into the sqlite3GlobalConfig structure.
18573     */
18574     sqlite3_mutex_methods const *pFrom;
18575     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
18576 
18577     if( sqlite3GlobalConfig.bCoreMutex ){
18578       pFrom = sqlite3DefaultMutex();
18579     }else{
18580       pFrom = sqlite3NoopMutex();
18581     }
18582     memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
18583     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
18584            sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
18585     pTo->xMutexAlloc = pFrom->xMutexAlloc;
18586   }
18587   rc = sqlite3GlobalConfig.mutex.xMutexInit();
18588 
18589 #ifdef SQLITE_DEBUG
18590   GLOBAL(int, mutexIsInit) = 1;
18591 #endif
18592 
18593   return rc;
18594 }
18595 
18596 /*
18597 ** Shutdown the mutex system. This call frees resources allocated by
18598 ** sqlite3MutexInit().
18599 */
18600 SQLITE_PRIVATE int sqlite3MutexEnd(void){
18601   int rc = SQLITE_OK;
18602   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
18603     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
18604   }
18605 
18606 #ifdef SQLITE_DEBUG
18607   GLOBAL(int, mutexIsInit) = 0;
18608 #endif
18609 
18610   return rc;
18611 }
18612 
18613 /*
18614 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
18615 */
18616 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
18617 #ifndef SQLITE_OMIT_AUTOINIT
18618   if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
18619 #endif
18620   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
18621 }
18622 
18623 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
18624   if( !sqlite3GlobalConfig.bCoreMutex ){
18625     return 0;
18626   }
18627   assert( GLOBAL(int, mutexIsInit) );
18628   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
18629 }
18630 
18631 /*
18632 ** Free a dynamic mutex.
18633 */
18634 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
18635   if( p ){
18636     sqlite3GlobalConfig.mutex.xMutexFree(p);
18637   }
18638 }
18639 
18640 /*
18641 ** Obtain the mutex p. If some other thread already has the mutex, block
18642 ** until it can be obtained.
18643 */
18644 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
18645   if( p ){
18646     sqlite3GlobalConfig.mutex.xMutexEnter(p);
18647   }
18648 }
18649 
18650 /*
18651 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
18652 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
18653 */
18654 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
18655   int rc = SQLITE_OK;
18656   if( p ){
18657     return sqlite3GlobalConfig.mutex.xMutexTry(p);
18658   }
18659   return rc;
18660 }
18661 
18662 /*
18663 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
18664 ** entered by the same thread.  The behavior is undefined if the mutex
18665 ** is not currently entered. If a NULL pointer is passed as an argument
18666 ** this function is a no-op.
18667 */
18668 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
18669   if( p ){
18670     sqlite3GlobalConfig.mutex.xMutexLeave(p);
18671   }
18672 }
18673 
18674 #ifndef NDEBUG
18675 /*
18676 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18677 ** intended for use inside assert() statements.
18678 */
18679 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
18680   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
18681 }
18682 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
18683   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
18684 }
18685 #endif
18686 
18687 #endif /* !defined(SQLITE_MUTEX_OMIT) */
18688 
18689 /************** End of mutex.c ***********************************************/
18690 /************** Begin file mutex_noop.c **************************************/
18691 /*
18692 ** 2008 October 07
18693 **
18694 ** The author disclaims copyright to this source code.  In place of
18695 ** a legal notice, here is a blessing:
18696 **
18697 **    May you do good and not evil.
18698 **    May you find forgiveness for yourself and forgive others.
18699 **    May you share freely, never taking more than you give.
18700 **
18701 *************************************************************************
18702 ** This file contains the C functions that implement mutexes.
18703 **
18704 ** This implementation in this file does not provide any mutual
18705 ** exclusion and is thus suitable for use only in applications
18706 ** that use SQLite in a single thread.  The routines defined
18707 ** here are place-holders.  Applications can substitute working
18708 ** mutex routines at start-time using the
18709 **
18710 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
18711 **
18712 ** interface.
18713 **
18714 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
18715 ** that does error checking on mutexes to make sure they are being
18716 ** called correctly.
18717 */
18718 
18719 #ifndef SQLITE_MUTEX_OMIT
18720 
18721 #ifndef SQLITE_DEBUG
18722 /*
18723 ** Stub routines for all mutex methods.
18724 **
18725 ** This routines provide no mutual exclusion or error checking.
18726 */
18727 static int noopMutexInit(void){ return SQLITE_OK; }
18728 static int noopMutexEnd(void){ return SQLITE_OK; }
18729 static sqlite3_mutex *noopMutexAlloc(int id){
18730   UNUSED_PARAMETER(id);
18731   return (sqlite3_mutex*)8;
18732 }
18733 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
18734 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
18735 static int noopMutexTry(sqlite3_mutex *p){
18736   UNUSED_PARAMETER(p);
18737   return SQLITE_OK;
18738 }
18739 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
18740 
18741 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
18742   static const sqlite3_mutex_methods sMutex = {
18743     noopMutexInit,
18744     noopMutexEnd,
18745     noopMutexAlloc,
18746     noopMutexFree,
18747     noopMutexEnter,
18748     noopMutexTry,
18749     noopMutexLeave,
18750 
18751     0,
18752     0,
18753   };
18754 
18755   return &sMutex;
18756 }
18757 #endif /* !SQLITE_DEBUG */
18758 
18759 #ifdef SQLITE_DEBUG
18760 /*
18761 ** In this implementation, error checking is provided for testing
18762 ** and debugging purposes.  The mutexes still do not provide any
18763 ** mutual exclusion.
18764 */
18765 
18766 /*
18767 ** The mutex object
18768 */
18769 typedef struct sqlite3_debug_mutex {
18770   int id;     /* The mutex type */
18771   int cnt;    /* Number of entries without a matching leave */
18772 } sqlite3_debug_mutex;
18773 
18774 /*
18775 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18776 ** intended for use inside assert() statements.
18777 */
18778 static int debugMutexHeld(sqlite3_mutex *pX){
18779   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18780   return p==0 || p->cnt>0;
18781 }
18782 static int debugMutexNotheld(sqlite3_mutex *pX){
18783   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18784   return p==0 || p->cnt==0;
18785 }
18786 
18787 /*
18788 ** Initialize and deinitialize the mutex subsystem.
18789 */
18790 static int debugMutexInit(void){ return SQLITE_OK; }
18791 static int debugMutexEnd(void){ return SQLITE_OK; }
18792 
18793 /*
18794 ** The sqlite3_mutex_alloc() routine allocates a new
18795 ** mutex and returns a pointer to it.  If it returns NULL
18796 ** that means that a mutex could not be allocated.
18797 */
18798 static sqlite3_mutex *debugMutexAlloc(int id){
18799   static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_APP3 - 1];
18800   sqlite3_debug_mutex *pNew = 0;
18801   switch( id ){
18802     case SQLITE_MUTEX_FAST:
18803     case SQLITE_MUTEX_RECURSIVE: {
18804       pNew = sqlite3Malloc(sizeof(*pNew));
18805       if( pNew ){
18806         pNew->id = id;
18807         pNew->cnt = 0;
18808       }
18809       break;
18810     }
18811     default: {
18812       assert( id-2 >= 0 );
18813       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
18814       pNew = &aStatic[id-2];
18815       pNew->id = id;
18816       break;
18817     }
18818   }
18819   return (sqlite3_mutex*)pNew;
18820 }
18821 
18822 /*
18823 ** This routine deallocates a previously allocated mutex.
18824 */
18825 static void debugMutexFree(sqlite3_mutex *pX){
18826   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18827   assert( p->cnt==0 );
18828   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18829   sqlite3_free(p);
18830 }
18831 
18832 /*
18833 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18834 ** to enter a mutex.  If another thread is already within the mutex,
18835 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18836 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18837 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18838 ** be entered multiple times by the same thread.  In such cases the,
18839 ** mutex must be exited an equal number of times before another thread
18840 ** can enter.  If the same thread tries to enter any other kind of mutex
18841 ** more than once, the behavior is undefined.
18842 */
18843 static void debugMutexEnter(sqlite3_mutex *pX){
18844   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18845   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18846   p->cnt++;
18847 }
18848 static int debugMutexTry(sqlite3_mutex *pX){
18849   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18850   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18851   p->cnt++;
18852   return SQLITE_OK;
18853 }
18854 
18855 /*
18856 ** The sqlite3_mutex_leave() routine exits a mutex that was
18857 ** previously entered by the same thread.  The behavior
18858 ** is undefined if the mutex is not currently entered or
18859 ** is not currently allocated.  SQLite will never do either.
18860 */
18861 static void debugMutexLeave(sqlite3_mutex *pX){
18862   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18863   assert( debugMutexHeld(pX) );
18864   p->cnt--;
18865   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18866 }
18867 
18868 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
18869   static const sqlite3_mutex_methods sMutex = {
18870     debugMutexInit,
18871     debugMutexEnd,
18872     debugMutexAlloc,
18873     debugMutexFree,
18874     debugMutexEnter,
18875     debugMutexTry,
18876     debugMutexLeave,
18877 
18878     debugMutexHeld,
18879     debugMutexNotheld
18880   };
18881 
18882   return &sMutex;
18883 }
18884 #endif /* SQLITE_DEBUG */
18885 
18886 /*
18887 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
18888 ** is used regardless of the run-time threadsafety setting.
18889 */
18890 #ifdef SQLITE_MUTEX_NOOP
18891 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18892   return sqlite3NoopMutex();
18893 }
18894 #endif /* defined(SQLITE_MUTEX_NOOP) */
18895 #endif /* !defined(SQLITE_MUTEX_OMIT) */
18896 
18897 /************** End of mutex_noop.c ******************************************/
18898 /************** Begin file mutex_unix.c **************************************/
18899 /*
18900 ** 2007 August 28
18901 **
18902 ** The author disclaims copyright to this source code.  In place of
18903 ** a legal notice, here is a blessing:
18904 **
18905 **    May you do good and not evil.
18906 **    May you find forgiveness for yourself and forgive others.
18907 **    May you share freely, never taking more than you give.
18908 **
18909 *************************************************************************
18910 ** This file contains the C functions that implement mutexes for pthreads
18911 */
18912 
18913 /*
18914 ** The code in this file is only used if we are compiling threadsafe
18915 ** under unix with pthreads.
18916 **
18917 ** Note that this implementation requires a version of pthreads that
18918 ** supports recursive mutexes.
18919 */
18920 #ifdef SQLITE_MUTEX_PTHREADS
18921 
18922 #include <pthread.h>
18923 
18924 /*
18925 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
18926 ** are necessary under two condidtions:  (1) Debug builds and (2) using
18927 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
18928 */
18929 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
18930 # define SQLITE_MUTEX_NREF 1
18931 #else
18932 # define SQLITE_MUTEX_NREF 0
18933 #endif
18934 
18935 /*
18936 ** Each recursive mutex is an instance of the following structure.
18937 */
18938 struct sqlite3_mutex {
18939   pthread_mutex_t mutex;     /* Mutex controlling the lock */
18940 #if SQLITE_MUTEX_NREF
18941   int id;                    /* Mutex type */
18942   volatile int nRef;         /* Number of entrances */
18943   volatile pthread_t owner;  /* Thread that is within this mutex */
18944   int trace;                 /* True to trace changes */
18945 #endif
18946 };
18947 #if SQLITE_MUTEX_NREF
18948 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
18949 #else
18950 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
18951 #endif
18952 
18953 /*
18954 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18955 ** intended for use only inside assert() statements.  On some platforms,
18956 ** there might be race conditions that can cause these routines to
18957 ** deliver incorrect results.  In particular, if pthread_equal() is
18958 ** not an atomic operation, then these routines might delivery
18959 ** incorrect results.  On most platforms, pthread_equal() is a
18960 ** comparison of two integers and is therefore atomic.  But we are
18961 ** told that HPUX is not such a platform.  If so, then these routines
18962 ** will not always work correctly on HPUX.
18963 **
18964 ** On those platforms where pthread_equal() is not atomic, SQLite
18965 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
18966 ** make sure no assert() statements are evaluated and hence these
18967 ** routines are never called.
18968 */
18969 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
18970 static int pthreadMutexHeld(sqlite3_mutex *p){
18971   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
18972 }
18973 static int pthreadMutexNotheld(sqlite3_mutex *p){
18974   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
18975 }
18976 #endif
18977 
18978 /*
18979 ** Initialize and deinitialize the mutex subsystem.
18980 */
18981 static int pthreadMutexInit(void){ return SQLITE_OK; }
18982 static int pthreadMutexEnd(void){ return SQLITE_OK; }
18983 
18984 /*
18985 ** The sqlite3_mutex_alloc() routine allocates a new
18986 ** mutex and returns a pointer to it.  If it returns NULL
18987 ** that means that a mutex could not be allocated.  SQLite
18988 ** will unwind its stack and return an error.  The argument
18989 ** to sqlite3_mutex_alloc() is one of these integer constants:
18990 **
18991 ** <ul>
18992 ** <li>  SQLITE_MUTEX_FAST
18993 ** <li>  SQLITE_MUTEX_RECURSIVE
18994 ** <li>  SQLITE_MUTEX_STATIC_MASTER
18995 ** <li>  SQLITE_MUTEX_STATIC_MEM
18996 ** <li>  SQLITE_MUTEX_STATIC_OPEN
18997 ** <li>  SQLITE_MUTEX_STATIC_PRNG
18998 ** <li>  SQLITE_MUTEX_STATIC_LRU
18999 ** <li>  SQLITE_MUTEX_STATIC_PMEM
19000 ** <li>  SQLITE_MUTEX_STATIC_APP1
19001 ** <li>  SQLITE_MUTEX_STATIC_APP2
19002 ** <li>  SQLITE_MUTEX_STATIC_APP3
19003 ** </ul>
19004 **
19005 ** The first two constants cause sqlite3_mutex_alloc() to create
19006 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
19007 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
19008 ** The mutex implementation does not need to make a distinction
19009 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
19010 ** not want to.  But SQLite will only request a recursive mutex in
19011 ** cases where it really needs one.  If a faster non-recursive mutex
19012 ** implementation is available on the host platform, the mutex subsystem
19013 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
19014 **
19015 ** The other allowed parameters to sqlite3_mutex_alloc() each return
19016 ** a pointer to a static preexisting mutex.  Six static mutexes are
19017 ** used by the current version of SQLite.  Future versions of SQLite
19018 ** may add additional static mutexes.  Static mutexes are for internal
19019 ** use by SQLite only.  Applications that use SQLite mutexes should
19020 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
19021 ** SQLITE_MUTEX_RECURSIVE.
19022 **
19023 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
19024 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
19025 ** returns a different mutex on every call.  But for the static
19026 ** mutex types, the same mutex is returned on every call that has
19027 ** the same type number.
19028 */
19029 static sqlite3_mutex *pthreadMutexAlloc(int iType){
19030   static sqlite3_mutex staticMutexes[] = {
19031     SQLITE3_MUTEX_INITIALIZER,
19032     SQLITE3_MUTEX_INITIALIZER,
19033     SQLITE3_MUTEX_INITIALIZER,
19034     SQLITE3_MUTEX_INITIALIZER,
19035     SQLITE3_MUTEX_INITIALIZER,
19036     SQLITE3_MUTEX_INITIALIZER,
19037     SQLITE3_MUTEX_INITIALIZER,
19038     SQLITE3_MUTEX_INITIALIZER,
19039     SQLITE3_MUTEX_INITIALIZER
19040   };
19041   sqlite3_mutex *p;
19042   switch( iType ){
19043     case SQLITE_MUTEX_RECURSIVE: {
19044       p = sqlite3MallocZero( sizeof(*p) );
19045       if( p ){
19046 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
19047         /* If recursive mutexes are not available, we will have to
19048         ** build our own.  See below. */
19049         pthread_mutex_init(&p->mutex, 0);
19050 #else
19051         /* Use a recursive mutex if it is available */
19052         pthread_mutexattr_t recursiveAttr;
19053         pthread_mutexattr_init(&recursiveAttr);
19054         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
19055         pthread_mutex_init(&p->mutex, &recursiveAttr);
19056         pthread_mutexattr_destroy(&recursiveAttr);
19057 #endif
19058 #if SQLITE_MUTEX_NREF
19059         p->id = iType;
19060 #endif
19061       }
19062       break;
19063     }
19064     case SQLITE_MUTEX_FAST: {
19065       p = sqlite3MallocZero( sizeof(*p) );
19066       if( p ){
19067 #if SQLITE_MUTEX_NREF
19068         p->id = iType;
19069 #endif
19070         pthread_mutex_init(&p->mutex, 0);
19071       }
19072       break;
19073     }
19074     default: {
19075       assert( iType-2 >= 0 );
19076       assert( iType-2 < ArraySize(staticMutexes) );
19077       p = &staticMutexes[iType-2];
19078 #if SQLITE_MUTEX_NREF
19079       p->id = iType;
19080 #endif
19081       break;
19082     }
19083   }
19084   return p;
19085 }
19086 
19087 
19088 /*
19089 ** This routine deallocates a previously
19090 ** allocated mutex.  SQLite is careful to deallocate every
19091 ** mutex that it allocates.
19092 */
19093 static void pthreadMutexFree(sqlite3_mutex *p){
19094   assert( p->nRef==0 );
19095   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
19096   pthread_mutex_destroy(&p->mutex);
19097   sqlite3_free(p);
19098 }
19099 
19100 /*
19101 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
19102 ** to enter a mutex.  If another thread is already within the mutex,
19103 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
19104 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
19105 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
19106 ** be entered multiple times by the same thread.  In such cases the,
19107 ** mutex must be exited an equal number of times before another thread
19108 ** can enter.  If the same thread tries to enter any other kind of mutex
19109 ** more than once, the behavior is undefined.
19110 */
19111 static void pthreadMutexEnter(sqlite3_mutex *p){
19112   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
19113 
19114 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
19115   /* If recursive mutexes are not available, then we have to grow
19116   ** our own.  This implementation assumes that pthread_equal()
19117   ** is atomic - that it cannot be deceived into thinking self
19118   ** and p->owner are equal if p->owner changes between two values
19119   ** that are not equal to self while the comparison is taking place.
19120   ** This implementation also assumes a coherent cache - that
19121   ** separate processes cannot read different values from the same
19122   ** address at the same time.  If either of these two conditions
19123   ** are not met, then the mutexes will fail and problems will result.
19124   */
19125   {
19126     pthread_t self = pthread_self();
19127     if( p->nRef>0 && pthread_equal(p->owner, self) ){
19128       p->nRef++;
19129     }else{
19130       pthread_mutex_lock(&p->mutex);
19131       assert( p->nRef==0 );
19132       p->owner = self;
19133       p->nRef = 1;
19134     }
19135   }
19136 #else
19137   /* Use the built-in recursive mutexes if they are available.
19138   */
19139   pthread_mutex_lock(&p->mutex);
19140 #if SQLITE_MUTEX_NREF
19141   assert( p->nRef>0 || p->owner==0 );
19142   p->owner = pthread_self();
19143   p->nRef++;
19144 #endif
19145 #endif
19146 
19147 #ifdef SQLITE_DEBUG
19148   if( p->trace ){
19149     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19150   }
19151 #endif
19152 }
19153 static int pthreadMutexTry(sqlite3_mutex *p){
19154   int rc;
19155   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
19156 
19157 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
19158   /* If recursive mutexes are not available, then we have to grow
19159   ** our own.  This implementation assumes that pthread_equal()
19160   ** is atomic - that it cannot be deceived into thinking self
19161   ** and p->owner are equal if p->owner changes between two values
19162   ** that are not equal to self while the comparison is taking place.
19163   ** This implementation also assumes a coherent cache - that
19164   ** separate processes cannot read different values from the same
19165   ** address at the same time.  If either of these two conditions
19166   ** are not met, then the mutexes will fail and problems will result.
19167   */
19168   {
19169     pthread_t self = pthread_self();
19170     if( p->nRef>0 && pthread_equal(p->owner, self) ){
19171       p->nRef++;
19172       rc = SQLITE_OK;
19173     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
19174       assert( p->nRef==0 );
19175       p->owner = self;
19176       p->nRef = 1;
19177       rc = SQLITE_OK;
19178     }else{
19179       rc = SQLITE_BUSY;
19180     }
19181   }
19182 #else
19183   /* Use the built-in recursive mutexes if they are available.
19184   */
19185   if( pthread_mutex_trylock(&p->mutex)==0 ){
19186 #if SQLITE_MUTEX_NREF
19187     p->owner = pthread_self();
19188     p->nRef++;
19189 #endif
19190     rc = SQLITE_OK;
19191   }else{
19192     rc = SQLITE_BUSY;
19193   }
19194 #endif
19195 
19196 #ifdef SQLITE_DEBUG
19197   if( rc==SQLITE_OK && p->trace ){
19198     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19199   }
19200 #endif
19201   return rc;
19202 }
19203 
19204 /*
19205 ** The sqlite3_mutex_leave() routine exits a mutex that was
19206 ** previously entered by the same thread.  The behavior
19207 ** is undefined if the mutex is not currently entered or
19208 ** is not currently allocated.  SQLite will never do either.
19209 */
19210 static void pthreadMutexLeave(sqlite3_mutex *p){
19211   assert( pthreadMutexHeld(p) );
19212 #if SQLITE_MUTEX_NREF
19213   p->nRef--;
19214   if( p->nRef==0 ) p->owner = 0;
19215 #endif
19216   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
19217 
19218 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
19219   if( p->nRef==0 ){
19220     pthread_mutex_unlock(&p->mutex);
19221   }
19222 #else
19223   pthread_mutex_unlock(&p->mutex);
19224 #endif
19225 
19226 #ifdef SQLITE_DEBUG
19227   if( p->trace ){
19228     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19229   }
19230 #endif
19231 }
19232 
19233 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
19234   static const sqlite3_mutex_methods sMutex = {
19235     pthreadMutexInit,
19236     pthreadMutexEnd,
19237     pthreadMutexAlloc,
19238     pthreadMutexFree,
19239     pthreadMutexEnter,
19240     pthreadMutexTry,
19241     pthreadMutexLeave,
19242 #ifdef SQLITE_DEBUG
19243     pthreadMutexHeld,
19244     pthreadMutexNotheld
19245 #else
19246     0,
19247     0
19248 #endif
19249   };
19250 
19251   return &sMutex;
19252 }
19253 
19254 #endif /* SQLITE_MUTEX_PTHREADS */
19255 
19256 /************** End of mutex_unix.c ******************************************/
19257 /************** Begin file mutex_w32.c ***************************************/
19258 /*
19259 ** 2007 August 14
19260 **
19261 ** The author disclaims copyright to this source code.  In place of
19262 ** a legal notice, here is a blessing:
19263 **
19264 **    May you do good and not evil.
19265 **    May you find forgiveness for yourself and forgive others.
19266 **    May you share freely, never taking more than you give.
19267 **
19268 *************************************************************************
19269 ** This file contains the C functions that implement mutexes for Win32.
19270 */
19271 
19272 #if SQLITE_OS_WIN
19273 /*
19274 ** Include code that is common to all os_*.c files
19275 */
19276 /************** Include os_common.h in the middle of mutex_w32.c *************/
19277 /************** Begin file os_common.h ***************************************/
19278 /*
19279 ** 2004 May 22
19280 **
19281 ** The author disclaims copyright to this source code.  In place of
19282 ** a legal notice, here is a blessing:
19283 **
19284 **    May you do good and not evil.
19285 **    May you find forgiveness for yourself and forgive others.
19286 **    May you share freely, never taking more than you give.
19287 **
19288 ******************************************************************************
19289 **
19290 ** This file contains macros and a little bit of code that is common to
19291 ** all of the platform-specific files (os_*.c) and is #included into those
19292 ** files.
19293 **
19294 ** This file should be #included by the os_*.c files only.  It is not a
19295 ** general purpose header file.
19296 */
19297 #ifndef _OS_COMMON_H_
19298 #define _OS_COMMON_H_
19299 
19300 /*
19301 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
19302 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
19303 ** switch.  The following code should catch this problem at compile-time.
19304 */
19305 #ifdef MEMORY_DEBUG
19306 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
19307 #endif
19308 
19309 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
19310 # ifndef SQLITE_DEBUG_OS_TRACE
19311 #   define SQLITE_DEBUG_OS_TRACE 0
19312 # endif
19313   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
19314 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
19315 #else
19316 # define OSTRACE(X)
19317 #endif
19318 
19319 /*
19320 ** Macros for performance tracing.  Normally turned off.  Only works
19321 ** on i486 hardware.
19322 */
19323 #ifdef SQLITE_PERFORMANCE_TRACE
19324 
19325 /*
19326 ** hwtime.h contains inline assembler code for implementing
19327 ** high-performance timing routines.
19328 */
19329 /************** Include hwtime.h in the middle of os_common.h ****************/
19330 /************** Begin file hwtime.h ******************************************/
19331 /*
19332 ** 2008 May 27
19333 **
19334 ** The author disclaims copyright to this source code.  In place of
19335 ** a legal notice, here is a blessing:
19336 **
19337 **    May you do good and not evil.
19338 **    May you find forgiveness for yourself and forgive others.
19339 **    May you share freely, never taking more than you give.
19340 **
19341 ******************************************************************************
19342 **
19343 ** This file contains inline asm code for retrieving "high-performance"
19344 ** counters for x86 class CPUs.
19345 */
19346 #ifndef _HWTIME_H_
19347 #define _HWTIME_H_
19348 
19349 /*
19350 ** The following routine only works on pentium-class (or newer) processors.
19351 ** It uses the RDTSC opcode to read the cycle count value out of the
19352 ** processor and returns that value.  This can be used for high-res
19353 ** profiling.
19354 */
19355 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
19356       (defined(i386) || defined(__i386__) || defined(_M_IX86))
19357 
19358   #if defined(__GNUC__)
19359 
19360   __inline__ sqlite_uint64 sqlite3Hwtime(void){
19361      unsigned int lo, hi;
19362      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
19363      return (sqlite_uint64)hi << 32 | lo;
19364   }
19365 
19366   #elif defined(_MSC_VER)
19367 
19368   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
19369      __asm {
19370         rdtsc
19371         ret       ; return value at EDX:EAX
19372      }
19373   }
19374 
19375   #endif
19376 
19377 #elif (defined(__GNUC__) && defined(__x86_64__))
19378 
19379   __inline__ sqlite_uint64 sqlite3Hwtime(void){
19380       unsigned long val;
19381       __asm__ __volatile__ ("rdtsc" : "=A" (val));
19382       return val;
19383   }
19384 
19385 #elif (defined(__GNUC__) && defined(__ppc__))
19386 
19387   __inline__ sqlite_uint64 sqlite3Hwtime(void){
19388       unsigned long long retval;
19389       unsigned long junk;
19390       __asm__ __volatile__ ("\n\
19391           1:      mftbu   %1\n\
19392                   mftb    %L0\n\
19393                   mftbu   %0\n\
19394                   cmpw    %0,%1\n\
19395                   bne     1b"
19396                   : "=r" (retval), "=r" (junk));
19397       return retval;
19398   }
19399 
19400 #else
19401 
19402   #error Need implementation of sqlite3Hwtime() for your platform.
19403 
19404   /*
19405   ** To compile without implementing sqlite3Hwtime() for your platform,
19406   ** you can remove the above #error and use the following
19407   ** stub function.  You will lose timing support for many
19408   ** of the debugging and testing utilities, but it should at
19409   ** least compile and run.
19410   */
19411 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
19412 
19413 #endif
19414 
19415 #endif /* !defined(_HWTIME_H_) */
19416 
19417 /************** End of hwtime.h **********************************************/
19418 /************** Continuing where we left off in os_common.h ******************/
19419 
19420 static sqlite_uint64 g_start;
19421 static sqlite_uint64 g_elapsed;
19422 #define TIMER_START       g_start=sqlite3Hwtime()
19423 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
19424 #define TIMER_ELAPSED     g_elapsed
19425 #else
19426 #define TIMER_START
19427 #define TIMER_END
19428 #define TIMER_ELAPSED     ((sqlite_uint64)0)
19429 #endif
19430 
19431 /*
19432 ** If we compile with the SQLITE_TEST macro set, then the following block
19433 ** of code will give us the ability to simulate a disk I/O error.  This
19434 ** is used for testing the I/O recovery logic.
19435 */
19436 #ifdef SQLITE_TEST
19437 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
19438 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
19439 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
19440 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
19441 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
19442 SQLITE_API int sqlite3_diskfull_pending = 0;
19443 SQLITE_API int sqlite3_diskfull = 0;
19444 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
19445 #define SimulateIOError(CODE)  \
19446   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
19447        || sqlite3_io_error_pending-- == 1 )  \
19448               { local_ioerr(); CODE; }
19449 static void local_ioerr(){
19450   IOTRACE(("IOERR\n"));
19451   sqlite3_io_error_hit++;
19452   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
19453 }
19454 #define SimulateDiskfullError(CODE) \
19455    if( sqlite3_diskfull_pending ){ \
19456      if( sqlite3_diskfull_pending == 1 ){ \
19457        local_ioerr(); \
19458        sqlite3_diskfull = 1; \
19459        sqlite3_io_error_hit = 1; \
19460        CODE; \
19461      }else{ \
19462        sqlite3_diskfull_pending--; \
19463      } \
19464    }
19465 #else
19466 #define SimulateIOErrorBenign(X)
19467 #define SimulateIOError(A)
19468 #define SimulateDiskfullError(A)
19469 #endif
19470 
19471 /*
19472 ** When testing, keep a count of the number of open files.
19473 */
19474 #ifdef SQLITE_TEST
19475 SQLITE_API int sqlite3_open_file_count = 0;
19476 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
19477 #else
19478 #define OpenCounter(X)
19479 #endif
19480 
19481 #endif /* !defined(_OS_COMMON_H_) */
19482 
19483 /************** End of os_common.h *******************************************/
19484 /************** Continuing where we left off in mutex_w32.c ******************/
19485 
19486 /*
19487 ** Include the header file for the Windows VFS.
19488 */
19489 /************** Include os_win.h in the middle of mutex_w32.c ****************/
19490 /************** Begin file os_win.h ******************************************/
19491 /*
19492 ** 2013 November 25
19493 **
19494 ** The author disclaims copyright to this source code.  In place of
19495 ** a legal notice, here is a blessing:
19496 **
19497 **    May you do good and not evil.
19498 **    May you find forgiveness for yourself and forgive others.
19499 **    May you share freely, never taking more than you give.
19500 **
19501 ******************************************************************************
19502 **
19503 ** This file contains code that is specific to Windows.
19504 */
19505 #ifndef _OS_WIN_H_
19506 #define _OS_WIN_H_
19507 
19508 /*
19509 ** Include the primary Windows SDK header file.
19510 */
19511 #include "windows.h"
19512 
19513 #ifdef __CYGWIN__
19514 # include <sys/cygwin.h>
19515 # include <errno.h> /* amalgamator: dontcache */
19516 #endif
19517 
19518 /*
19519 ** Determine if we are dealing with Windows NT.
19520 **
19521 ** We ought to be able to determine if we are compiling for Windows 9x or
19522 ** Windows NT using the _WIN32_WINNT macro as follows:
19523 **
19524 ** #if defined(_WIN32_WINNT)
19525 ** # define SQLITE_OS_WINNT 1
19526 ** #else
19527 ** # define SQLITE_OS_WINNT 0
19528 ** #endif
19529 **
19530 ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
19531 ** it ought to, so the above test does not work.  We'll just assume that
19532 ** everything is Windows NT unless the programmer explicitly says otherwise
19533 ** by setting SQLITE_OS_WINNT to 0.
19534 */
19535 #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
19536 # define SQLITE_OS_WINNT 1
19537 #endif
19538 
19539 /*
19540 ** Determine if we are dealing with Windows CE - which has a much reduced
19541 ** API.
19542 */
19543 #if defined(_WIN32_WCE)
19544 # define SQLITE_OS_WINCE 1
19545 #else
19546 # define SQLITE_OS_WINCE 0
19547 #endif
19548 
19549 /*
19550 ** Determine if we are dealing with WinRT, which provides only a subset of
19551 ** the full Win32 API.
19552 */
19553 #if !defined(SQLITE_OS_WINRT)
19554 # define SQLITE_OS_WINRT 0
19555 #endif
19556 
19557 /*
19558 ** For WinCE, some API function parameters do not appear to be declared as
19559 ** volatile.
19560 */
19561 #if SQLITE_OS_WINCE
19562 # define SQLITE_WIN32_VOLATILE
19563 #else
19564 # define SQLITE_WIN32_VOLATILE volatile
19565 #endif
19566 
19567 #endif /* _OS_WIN_H_ */
19568 
19569 /************** End of os_win.h **********************************************/
19570 /************** Continuing where we left off in mutex_w32.c ******************/
19571 #endif
19572 
19573 /*
19574 ** The code in this file is only used if we are compiling multithreaded
19575 ** on a Win32 system.
19576 */
19577 #ifdef SQLITE_MUTEX_W32
19578 
19579 /*
19580 ** Each recursive mutex is an instance of the following structure.
19581 */
19582 struct sqlite3_mutex {
19583   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
19584   int id;                    /* Mutex type */
19585 #ifdef SQLITE_DEBUG
19586   volatile int nRef;         /* Number of enterances */
19587   volatile DWORD owner;      /* Thread holding this mutex */
19588   volatile int trace;        /* True to trace changes */
19589 #endif
19590 };
19591 
19592 /*
19593 ** These are the initializer values used when declaring a "static" mutex
19594 ** on Win32.  It should be noted that all mutexes require initialization
19595 ** on the Win32 platform.
19596 */
19597 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
19598 
19599 #ifdef SQLITE_DEBUG
19600 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
19601                                     0L, (DWORD)0, 0 }
19602 #else
19603 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
19604 #endif
19605 
19606 #ifdef SQLITE_DEBUG
19607 /*
19608 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
19609 ** intended for use only inside assert() statements.
19610 */
19611 static int winMutexHeld(sqlite3_mutex *p){
19612   return p->nRef!=0 && p->owner==GetCurrentThreadId();
19613 }
19614 
19615 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
19616   return p->nRef==0 || p->owner!=tid;
19617 }
19618 
19619 static int winMutexNotheld(sqlite3_mutex *p){
19620   DWORD tid = GetCurrentThreadId();
19621   return winMutexNotheld2(p, tid);
19622 }
19623 #endif
19624 
19625 /*
19626 ** Initialize and deinitialize the mutex subsystem.
19627 */
19628 static sqlite3_mutex winMutex_staticMutexes[] = {
19629   SQLITE3_MUTEX_INITIALIZER,
19630   SQLITE3_MUTEX_INITIALIZER,
19631   SQLITE3_MUTEX_INITIALIZER,
19632   SQLITE3_MUTEX_INITIALIZER,
19633   SQLITE3_MUTEX_INITIALIZER,
19634   SQLITE3_MUTEX_INITIALIZER,
19635   SQLITE3_MUTEX_INITIALIZER,
19636   SQLITE3_MUTEX_INITIALIZER,
19637   SQLITE3_MUTEX_INITIALIZER
19638 };
19639 
19640 static int winMutex_isInit = 0;
19641 static int winMutex_isNt = -1; /* <0 means "need to query" */
19642 
19643 /* As the winMutexInit() and winMutexEnd() functions are called as part
19644 ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
19645 ** "interlocked" magic used here is probably not strictly necessary.
19646 */
19647 static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
19648 
19649 SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
19650 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
19651 
19652 static int winMutexInit(void){
19653   /* The first to increment to 1 does actual initialization */
19654   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
19655     int i;
19656     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
19657 #if SQLITE_OS_WINRT
19658       InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
19659 #else
19660       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
19661 #endif
19662     }
19663     winMutex_isInit = 1;
19664   }else{
19665     /* Another thread is (in the process of) initializing the static
19666     ** mutexes */
19667     while( !winMutex_isInit ){
19668       sqlite3_win32_sleep(1);
19669     }
19670   }
19671   return SQLITE_OK;
19672 }
19673 
19674 static int winMutexEnd(void){
19675   /* The first to decrement to 0 does actual shutdown
19676   ** (which should be the last to shutdown.) */
19677   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
19678     if( winMutex_isInit==1 ){
19679       int i;
19680       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
19681         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
19682       }
19683       winMutex_isInit = 0;
19684     }
19685   }
19686   return SQLITE_OK;
19687 }
19688 
19689 /*
19690 ** The sqlite3_mutex_alloc() routine allocates a new
19691 ** mutex and returns a pointer to it.  If it returns NULL
19692 ** that means that a mutex could not be allocated.  SQLite
19693 ** will unwind its stack and return an error.  The argument
19694 ** to sqlite3_mutex_alloc() is one of these integer constants:
19695 **
19696 ** <ul>
19697 ** <li>  SQLITE_MUTEX_FAST
19698 ** <li>  SQLITE_MUTEX_RECURSIVE
19699 ** <li>  SQLITE_MUTEX_STATIC_MASTER
19700 ** <li>  SQLITE_MUTEX_STATIC_MEM
19701 ** <li>  SQLITE_MUTEX_STATIC_OPEN
19702 ** <li>  SQLITE_MUTEX_STATIC_PRNG
19703 ** <li>  SQLITE_MUTEX_STATIC_LRU
19704 ** <li>  SQLITE_MUTEX_STATIC_PMEM
19705 ** <li>  SQLITE_MUTEX_STATIC_APP1
19706 ** <li>  SQLITE_MUTEX_STATIC_APP2
19707 ** <li>  SQLITE_MUTEX_STATIC_APP3
19708 ** </ul>
19709 **
19710 ** The first two constants cause sqlite3_mutex_alloc() to create
19711 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
19712 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
19713 ** The mutex implementation does not need to make a distinction
19714 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
19715 ** not want to.  But SQLite will only request a recursive mutex in
19716 ** cases where it really needs one.  If a faster non-recursive mutex
19717 ** implementation is available on the host platform, the mutex subsystem
19718 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
19719 **
19720 ** The other allowed parameters to sqlite3_mutex_alloc() each return
19721 ** a pointer to a static preexisting mutex.  Six static mutexes are
19722 ** used by the current version of SQLite.  Future versions of SQLite
19723 ** may add additional static mutexes.  Static mutexes are for internal
19724 ** use by SQLite only.  Applications that use SQLite mutexes should
19725 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
19726 ** SQLITE_MUTEX_RECURSIVE.
19727 **
19728 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
19729 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
19730 ** returns a different mutex on every call.  But for the static
19731 ** mutex types, the same mutex is returned on every call that has
19732 ** the same type number.
19733 */
19734 static sqlite3_mutex *winMutexAlloc(int iType){
19735   sqlite3_mutex *p;
19736 
19737   switch( iType ){
19738     case SQLITE_MUTEX_FAST:
19739     case SQLITE_MUTEX_RECURSIVE: {
19740       p = sqlite3MallocZero( sizeof(*p) );
19741       if( p ){
19742 #ifdef SQLITE_DEBUG
19743         p->id = iType;
19744 #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
19745         p->trace = 1;
19746 #endif
19747 #endif
19748 #if SQLITE_OS_WINRT
19749         InitializeCriticalSectionEx(&p->mutex, 0, 0);
19750 #else
19751         InitializeCriticalSection(&p->mutex);
19752 #endif
19753       }
19754       break;
19755     }
19756     default: {
19757       assert( iType-2 >= 0 );
19758       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
19759       assert( winMutex_isInit==1 );
19760       p = &winMutex_staticMutexes[iType-2];
19761 #ifdef SQLITE_DEBUG
19762       p->id = iType;
19763 #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
19764       p->trace = 1;
19765 #endif
19766 #endif
19767       break;
19768     }
19769   }
19770   return p;
19771 }
19772 
19773 
19774 /*
19775 ** This routine deallocates a previously
19776 ** allocated mutex.  SQLite is careful to deallocate every
19777 ** mutex that it allocates.
19778 */
19779 static void winMutexFree(sqlite3_mutex *p){
19780   assert( p );
19781 #ifdef SQLITE_DEBUG
19782   assert( p->nRef==0 && p->owner==0 );
19783   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
19784 #endif
19785   assert( winMutex_isInit==1 );
19786   DeleteCriticalSection(&p->mutex);
19787   sqlite3_free(p);
19788 }
19789 
19790 /*
19791 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
19792 ** to enter a mutex.  If another thread is already within the mutex,
19793 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
19794 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
19795 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
19796 ** be entered multiple times by the same thread.  In such cases the,
19797 ** mutex must be exited an equal number of times before another thread
19798 ** can enter.  If the same thread tries to enter any other kind of mutex
19799 ** more than once, the behavior is undefined.
19800 */
19801 static void winMutexEnter(sqlite3_mutex *p){
19802 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
19803   DWORD tid = GetCurrentThreadId();
19804 #endif
19805 #ifdef SQLITE_DEBUG
19806   assert( p );
19807   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
19808 #else
19809   assert( p );
19810 #endif
19811   assert( winMutex_isInit==1 );
19812   EnterCriticalSection(&p->mutex);
19813 #ifdef SQLITE_DEBUG
19814   assert( p->nRef>0 || p->owner==0 );
19815   p->owner = tid;
19816   p->nRef++;
19817   if( p->trace ){
19818     OSTRACE(("ENTER-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
19819              tid, p, p->trace, p->nRef));
19820   }
19821 #endif
19822 }
19823 
19824 static int winMutexTry(sqlite3_mutex *p){
19825 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
19826   DWORD tid = GetCurrentThreadId();
19827 #endif
19828   int rc = SQLITE_BUSY;
19829   assert( p );
19830   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
19831   /*
19832   ** The sqlite3_mutex_try() routine is very rarely used, and when it
19833   ** is used it is merely an optimization.  So it is OK for it to always
19834   ** fail.
19835   **
19836   ** The TryEnterCriticalSection() interface is only available on WinNT.
19837   ** And some windows compilers complain if you try to use it without
19838   ** first doing some #defines that prevent SQLite from building on Win98.
19839   ** For that reason, we will omit this optimization for now.  See
19840   ** ticket #2685.
19841   */
19842 #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
19843   assert( winMutex_isInit==1 );
19844   assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
19845   if( winMutex_isNt<0 ){
19846     winMutex_isNt = sqlite3_win32_is_nt();
19847   }
19848   assert( winMutex_isNt==0 || winMutex_isNt==1 );
19849   if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
19850 #ifdef SQLITE_DEBUG
19851     p->owner = tid;
19852     p->nRef++;
19853 #endif
19854     rc = SQLITE_OK;
19855   }
19856 #else
19857   UNUSED_PARAMETER(p);
19858 #endif
19859 #ifdef SQLITE_DEBUG
19860   if( p->trace ){
19861     OSTRACE(("TRY-MUTEX tid=%lu, mutex=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
19862              tid, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
19863   }
19864 #endif
19865   return rc;
19866 }
19867 
19868 /*
19869 ** The sqlite3_mutex_leave() routine exits a mutex that was
19870 ** previously entered by the same thread.  The behavior
19871 ** is undefined if the mutex is not currently entered or
19872 ** is not currently allocated.  SQLite will never do either.
19873 */
19874 static void winMutexLeave(sqlite3_mutex *p){
19875 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
19876   DWORD tid = GetCurrentThreadId();
19877 #endif
19878   assert( p );
19879 #ifdef SQLITE_DEBUG
19880   assert( p->nRef>0 );
19881   assert( p->owner==tid );
19882   p->nRef--;
19883   if( p->nRef==0 ) p->owner = 0;
19884   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
19885 #endif
19886   assert( winMutex_isInit==1 );
19887   LeaveCriticalSection(&p->mutex);
19888 #ifdef SQLITE_DEBUG
19889   if( p->trace ){
19890     OSTRACE(("LEAVE-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
19891              tid, p, p->trace, p->nRef));
19892   }
19893 #endif
19894 }
19895 
19896 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
19897   static const sqlite3_mutex_methods sMutex = {
19898     winMutexInit,
19899     winMutexEnd,
19900     winMutexAlloc,
19901     winMutexFree,
19902     winMutexEnter,
19903     winMutexTry,
19904     winMutexLeave,
19905 #ifdef SQLITE_DEBUG
19906     winMutexHeld,
19907     winMutexNotheld
19908 #else
19909     0,
19910     0
19911 #endif
19912   };
19913   return &sMutex;
19914 }
19915 
19916 #endif /* SQLITE_MUTEX_W32 */
19917 
19918 /************** End of mutex_w32.c *******************************************/
19919 /************** Begin file malloc.c ******************************************/
19920 /*
19921 ** 2001 September 15
19922 **
19923 ** The author disclaims copyright to this source code.  In place of
19924 ** a legal notice, here is a blessing:
19925 **
19926 **    May you do good and not evil.
19927 **    May you find forgiveness for yourself and forgive others.
19928 **    May you share freely, never taking more than you give.
19929 **
19930 *************************************************************************
19931 **
19932 ** Memory allocation functions used throughout sqlite.
19933 */
19934 /* #include <stdarg.h> */
19935 
19936 /*
19937 ** Attempt to release up to n bytes of non-essential memory currently
19938 ** held by SQLite. An example of non-essential memory is memory used to
19939 ** cache database pages that are not currently in use.
19940 */
19941 SQLITE_API int sqlite3_release_memory(int n){
19942 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
19943   return sqlite3PcacheReleaseMemory(n);
19944 #else
19945   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
19946   ** is a no-op returning zero if SQLite is not compiled with
19947   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
19948   UNUSED_PARAMETER(n);
19949   return 0;
19950 #endif
19951 }
19952 
19953 /*
19954 ** An instance of the following object records the location of
19955 ** each unused scratch buffer.
19956 */
19957 typedef struct ScratchFreeslot {
19958   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
19959 } ScratchFreeslot;
19960 
19961 /*
19962 ** State information local to the memory allocation subsystem.
19963 */
19964 static SQLITE_WSD struct Mem0Global {
19965   sqlite3_mutex *mutex;         /* Mutex to serialize access */
19966 
19967   /*
19968   ** The alarm callback and its arguments.  The mem0.mutex lock will
19969   ** be held while the callback is running.  Recursive calls into
19970   ** the memory subsystem are allowed, but no new callbacks will be
19971   ** issued.
19972   */
19973   sqlite3_int64 alarmThreshold;
19974   void (*alarmCallback)(void*, sqlite3_int64,int);
19975   void *alarmArg;
19976 
19977   /*
19978   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
19979   ** (so that a range test can be used to determine if an allocation
19980   ** being freed came from pScratch) and a pointer to the list of
19981   ** unused scratch allocations.
19982   */
19983   void *pScratchEnd;
19984   ScratchFreeslot *pScratchFree;
19985   u32 nScratchFree;
19986 
19987   /*
19988   ** True if heap is nearly "full" where "full" is defined by the
19989   ** sqlite3_soft_heap_limit() setting.
19990   */
19991   int nearlyFull;
19992 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
19993 
19994 #define mem0 GLOBAL(struct Mem0Global, mem0)
19995 
19996 /*
19997 ** This routine runs when the memory allocator sees that the
19998 ** total memory allocation is about to exceed the soft heap
19999 ** limit.
20000 */
20001 static void softHeapLimitEnforcer(
20002   void *NotUsed,
20003   sqlite3_int64 NotUsed2,
20004   int allocSize
20005 ){
20006   UNUSED_PARAMETER2(NotUsed, NotUsed2);
20007   sqlite3_release_memory(allocSize);
20008 }
20009 
20010 /*
20011 ** Change the alarm callback
20012 */
20013 static int sqlite3MemoryAlarm(
20014   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
20015   void *pArg,
20016   sqlite3_int64 iThreshold
20017 ){
20018   int nUsed;
20019   sqlite3_mutex_enter(mem0.mutex);
20020   mem0.alarmCallback = xCallback;
20021   mem0.alarmArg = pArg;
20022   mem0.alarmThreshold = iThreshold;
20023   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
20024   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
20025   sqlite3_mutex_leave(mem0.mutex);
20026   return SQLITE_OK;
20027 }
20028 
20029 #ifndef SQLITE_OMIT_DEPRECATED
20030 /*
20031 ** Deprecated external interface.  Internal/core SQLite code
20032 ** should call sqlite3MemoryAlarm.
20033 */
20034 SQLITE_API int sqlite3_memory_alarm(
20035   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
20036   void *pArg,
20037   sqlite3_int64 iThreshold
20038 ){
20039   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
20040 }
20041 #endif
20042 
20043 /*
20044 ** Set the soft heap-size limit for the library. Passing a zero or
20045 ** negative value indicates no limit.
20046 */
20047 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
20048   sqlite3_int64 priorLimit;
20049   sqlite3_int64 excess;
20050 #ifndef SQLITE_OMIT_AUTOINIT
20051   int rc = sqlite3_initialize();
20052   if( rc ) return -1;
20053 #endif
20054   sqlite3_mutex_enter(mem0.mutex);
20055   priorLimit = mem0.alarmThreshold;
20056   sqlite3_mutex_leave(mem0.mutex);
20057   if( n<0 ) return priorLimit;
20058   if( n>0 ){
20059     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
20060   }else{
20061     sqlite3MemoryAlarm(0, 0, 0);
20062   }
20063   excess = sqlite3_memory_used() - n;
20064   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
20065   return priorLimit;
20066 }
20067 SQLITE_API void sqlite3_soft_heap_limit(int n){
20068   if( n<0 ) n = 0;
20069   sqlite3_soft_heap_limit64(n);
20070 }
20071 
20072 /*
20073 ** Initialize the memory allocation subsystem.
20074 */
20075 SQLITE_PRIVATE int sqlite3MallocInit(void){
20076   if( sqlite3GlobalConfig.m.xMalloc==0 ){
20077     sqlite3MemSetDefault();
20078   }
20079   memset(&mem0, 0, sizeof(mem0));
20080   if( sqlite3GlobalConfig.bCoreMutex ){
20081     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
20082   }
20083   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
20084       && sqlite3GlobalConfig.nScratch>0 ){
20085     int i, n, sz;
20086     ScratchFreeslot *pSlot;
20087     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
20088     sqlite3GlobalConfig.szScratch = sz;
20089     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
20090     n = sqlite3GlobalConfig.nScratch;
20091     mem0.pScratchFree = pSlot;
20092     mem0.nScratchFree = n;
20093     for(i=0; i<n-1; i++){
20094       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
20095       pSlot = pSlot->pNext;
20096     }
20097     pSlot->pNext = 0;
20098     mem0.pScratchEnd = (void*)&pSlot[1];
20099   }else{
20100     mem0.pScratchEnd = 0;
20101     sqlite3GlobalConfig.pScratch = 0;
20102     sqlite3GlobalConfig.szScratch = 0;
20103     sqlite3GlobalConfig.nScratch = 0;
20104   }
20105   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
20106       || sqlite3GlobalConfig.nPage<1 ){
20107     sqlite3GlobalConfig.pPage = 0;
20108     sqlite3GlobalConfig.szPage = 0;
20109     sqlite3GlobalConfig.nPage = 0;
20110   }
20111   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
20112 }
20113 
20114 /*
20115 ** Return true if the heap is currently under memory pressure - in other
20116 ** words if the amount of heap used is close to the limit set by
20117 ** sqlite3_soft_heap_limit().
20118 */
20119 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
20120   return mem0.nearlyFull;
20121 }
20122 
20123 /*
20124 ** Deinitialize the memory allocation subsystem.
20125 */
20126 SQLITE_PRIVATE void sqlite3MallocEnd(void){
20127   if( sqlite3GlobalConfig.m.xShutdown ){
20128     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
20129   }
20130   memset(&mem0, 0, sizeof(mem0));
20131 }
20132 
20133 /*
20134 ** Return the amount of memory currently checked out.
20135 */
20136 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
20137   int n, mx;
20138   sqlite3_int64 res;
20139   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
20140   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
20141   return res;
20142 }
20143 
20144 /*
20145 ** Return the maximum amount of memory that has ever been
20146 ** checked out since either the beginning of this process
20147 ** or since the most recent reset.
20148 */
20149 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
20150   int n, mx;
20151   sqlite3_int64 res;
20152   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
20153   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
20154   return res;
20155 }
20156 
20157 /*
20158 ** Trigger the alarm
20159 */
20160 static void sqlite3MallocAlarm(int nByte){
20161   void (*xCallback)(void*,sqlite3_int64,int);
20162   sqlite3_int64 nowUsed;
20163   void *pArg;
20164   if( mem0.alarmCallback==0 ) return;
20165   xCallback = mem0.alarmCallback;
20166   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
20167   pArg = mem0.alarmArg;
20168   mem0.alarmCallback = 0;
20169   sqlite3_mutex_leave(mem0.mutex);
20170   xCallback(pArg, nowUsed, nByte);
20171   sqlite3_mutex_enter(mem0.mutex);
20172   mem0.alarmCallback = xCallback;
20173   mem0.alarmArg = pArg;
20174 }
20175 
20176 /*
20177 ** Do a memory allocation with statistics and alarms.  Assume the
20178 ** lock is already held.
20179 */
20180 static int mallocWithAlarm(int n, void **pp){
20181   int nFull;
20182   void *p;
20183   assert( sqlite3_mutex_held(mem0.mutex) );
20184   nFull = sqlite3GlobalConfig.m.xRoundup(n);
20185   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
20186   if( mem0.alarmCallback!=0 ){
20187     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
20188     if( nUsed >= mem0.alarmThreshold - nFull ){
20189       mem0.nearlyFull = 1;
20190       sqlite3MallocAlarm(nFull);
20191     }else{
20192       mem0.nearlyFull = 0;
20193     }
20194   }
20195   p = sqlite3GlobalConfig.m.xMalloc(nFull);
20196 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
20197   if( p==0 && mem0.alarmCallback ){
20198     sqlite3MallocAlarm(nFull);
20199     p = sqlite3GlobalConfig.m.xMalloc(nFull);
20200   }
20201 #endif
20202   if( p ){
20203     nFull = sqlite3MallocSize(p);
20204     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
20205     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
20206   }
20207   *pp = p;
20208   return nFull;
20209 }
20210 
20211 /*
20212 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
20213 ** assumes the memory subsystem has already been initialized.
20214 */
20215 SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
20216   void *p;
20217   if( n==0 || n>=0x7fffff00 ){
20218     /* A memory allocation of a number of bytes which is near the maximum
20219     ** signed integer value might cause an integer overflow inside of the
20220     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
20221     ** 255 bytes of overhead.  SQLite itself will never use anything near
20222     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
20223     p = 0;
20224   }else if( sqlite3GlobalConfig.bMemstat ){
20225     sqlite3_mutex_enter(mem0.mutex);
20226     mallocWithAlarm((int)n, &p);
20227     sqlite3_mutex_leave(mem0.mutex);
20228   }else{
20229     p = sqlite3GlobalConfig.m.xMalloc((int)n);
20230   }
20231   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-11148-40995 */
20232   return p;
20233 }
20234 
20235 /*
20236 ** This version of the memory allocation is for use by the application.
20237 ** First make sure the memory subsystem is initialized, then do the
20238 ** allocation.
20239 */
20240 SQLITE_API void *sqlite3_malloc(int n){
20241 #ifndef SQLITE_OMIT_AUTOINIT
20242   if( sqlite3_initialize() ) return 0;
20243 #endif
20244   return n<=0 ? 0 : sqlite3Malloc(n);
20245 }
20246 SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
20247 #ifndef SQLITE_OMIT_AUTOINIT
20248   if( sqlite3_initialize() ) return 0;
20249 #endif
20250   return sqlite3Malloc(n);
20251 }
20252 
20253 /*
20254 ** Each thread may only have a single outstanding allocation from
20255 ** xScratchMalloc().  We verify this constraint in the single-threaded
20256 ** case by setting scratchAllocOut to 1 when an allocation
20257 ** is outstanding clearing it when the allocation is freed.
20258 */
20259 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
20260 static int scratchAllocOut = 0;
20261 #endif
20262 
20263 
20264 /*
20265 ** Allocate memory that is to be used and released right away.
20266 ** This routine is similar to alloca() in that it is not intended
20267 ** for situations where the memory might be held long-term.  This
20268 ** routine is intended to get memory to old large transient data
20269 ** structures that would not normally fit on the stack of an
20270 ** embedded processor.
20271 */
20272 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
20273   void *p;
20274   assert( n>0 );
20275 
20276   sqlite3_mutex_enter(mem0.mutex);
20277   sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
20278   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
20279     p = mem0.pScratchFree;
20280     mem0.pScratchFree = mem0.pScratchFree->pNext;
20281     mem0.nScratchFree--;
20282     sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
20283     sqlite3_mutex_leave(mem0.mutex);
20284   }else{
20285     sqlite3_mutex_leave(mem0.mutex);
20286     p = sqlite3Malloc(n);
20287     if( sqlite3GlobalConfig.bMemstat && p ){
20288       sqlite3_mutex_enter(mem0.mutex);
20289       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
20290       sqlite3_mutex_leave(mem0.mutex);
20291     }
20292     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
20293   }
20294   assert( sqlite3_mutex_notheld(mem0.mutex) );
20295 
20296 
20297 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
20298   /* Verify that no more than two scratch allocations per thread
20299   ** are outstanding at one time.  (This is only checked in the
20300   ** single-threaded case since checking in the multi-threaded case
20301   ** would be much more complicated.) */
20302   assert( scratchAllocOut<=1 );
20303   if( p ) scratchAllocOut++;
20304 #endif
20305 
20306   return p;
20307 }
20308 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
20309   if( p ){
20310 
20311 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
20312     /* Verify that no more than two scratch allocation per thread
20313     ** is outstanding at one time.  (This is only checked in the
20314     ** single-threaded case since checking in the multi-threaded case
20315     ** would be much more complicated.) */
20316     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
20317     scratchAllocOut--;
20318 #endif
20319 
20320     if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
20321       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
20322       ScratchFreeslot *pSlot;
20323       pSlot = (ScratchFreeslot*)p;
20324       sqlite3_mutex_enter(mem0.mutex);
20325       pSlot->pNext = mem0.pScratchFree;
20326       mem0.pScratchFree = pSlot;
20327       mem0.nScratchFree++;
20328       assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
20329       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
20330       sqlite3_mutex_leave(mem0.mutex);
20331     }else{
20332       /* Release memory back to the heap */
20333       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
20334       assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
20335       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
20336       if( sqlite3GlobalConfig.bMemstat ){
20337         int iSize = sqlite3MallocSize(p);
20338         sqlite3_mutex_enter(mem0.mutex);
20339         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
20340         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
20341         sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
20342         sqlite3GlobalConfig.m.xFree(p);
20343         sqlite3_mutex_leave(mem0.mutex);
20344       }else{
20345         sqlite3GlobalConfig.m.xFree(p);
20346       }
20347     }
20348   }
20349 }
20350 
20351 /*
20352 ** TRUE if p is a lookaside memory allocation from db
20353 */
20354 #ifndef SQLITE_OMIT_LOOKASIDE
20355 static int isLookaside(sqlite3 *db, void *p){
20356   return p>=db->lookaside.pStart && p<db->lookaside.pEnd;
20357 }
20358 #else
20359 #define isLookaside(A,B) 0
20360 #endif
20361 
20362 /*
20363 ** Return the size of a memory allocation previously obtained from
20364 ** sqlite3Malloc() or sqlite3_malloc().
20365 */
20366 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
20367   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
20368   return sqlite3GlobalConfig.m.xSize(p);
20369 }
20370 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
20371   if( db==0 ){
20372     assert( sqlite3MemdebugNoType(p, ~MEMTYPE_HEAP) );
20373     assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
20374     return sqlite3MallocSize(p);
20375   }else{
20376     assert( sqlite3_mutex_held(db->mutex) );
20377     if( isLookaside(db, p) ){
20378       return db->lookaside.sz;
20379     }else{
20380       assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20381       assert( sqlite3MemdebugNoType(p, ~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20382       return sqlite3GlobalConfig.m.xSize(p);
20383     }
20384   }
20385 }
20386 SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
20387   assert( sqlite3MemdebugNoType(p, ~MEMTYPE_HEAP) );
20388   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
20389   return (sqlite3_uint64)sqlite3GlobalConfig.m.xSize(p);
20390 }
20391 
20392 /*
20393 ** Free memory previously obtained from sqlite3Malloc().
20394 */
20395 SQLITE_API void sqlite3_free(void *p){
20396   if( p==0 ) return;  /* IMP: R-49053-54554 */
20397   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
20398   assert( sqlite3MemdebugNoType(p, ~MEMTYPE_HEAP) );
20399   if( sqlite3GlobalConfig.bMemstat ){
20400     sqlite3_mutex_enter(mem0.mutex);
20401     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
20402     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
20403     sqlite3GlobalConfig.m.xFree(p);
20404     sqlite3_mutex_leave(mem0.mutex);
20405   }else{
20406     sqlite3GlobalConfig.m.xFree(p);
20407   }
20408 }
20409 
20410 /*
20411 ** Add the size of memory allocation "p" to the count in
20412 ** *db->pnBytesFreed.
20413 */
20414 static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
20415   *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
20416 }
20417 
20418 /*
20419 ** Free memory that might be associated with a particular database
20420 ** connection.
20421 */
20422 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
20423   assert( db==0 || sqlite3_mutex_held(db->mutex) );
20424   if( p==0 ) return;
20425   if( db ){
20426     if( db->pnBytesFreed ){
20427       measureAllocationSize(db, p);
20428       return;
20429     }
20430     if( isLookaside(db, p) ){
20431       LookasideSlot *pBuf = (LookasideSlot*)p;
20432 #if SQLITE_DEBUG
20433       /* Trash all content in the buffer being freed */
20434       memset(p, 0xaa, db->lookaside.sz);
20435 #endif
20436       pBuf->pNext = db->lookaside.pFree;
20437       db->lookaside.pFree = pBuf;
20438       db->lookaside.nOut--;
20439       return;
20440     }
20441   }
20442   assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20443   assert( sqlite3MemdebugNoType(p, ~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20444   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
20445   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
20446   sqlite3_free(p);
20447 }
20448 
20449 /*
20450 ** Change the size of an existing memory allocation
20451 */
20452 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
20453   int nOld, nNew, nDiff;
20454   void *pNew;
20455   assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
20456   assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
20457   if( pOld==0 ){
20458     return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
20459   }
20460   if( nBytes==0 ){
20461     sqlite3_free(pOld); /* IMP: R-26507-47431 */
20462     return 0;
20463   }
20464   if( nBytes>=0x7fffff00 ){
20465     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
20466     return 0;
20467   }
20468   nOld = sqlite3MallocSize(pOld);
20469   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
20470   ** argument to xRealloc is always a value returned by a prior call to
20471   ** xRoundup. */
20472   nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
20473   if( nOld==nNew ){
20474     pNew = pOld;
20475   }else if( sqlite3GlobalConfig.bMemstat ){
20476     sqlite3_mutex_enter(mem0.mutex);
20477     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
20478     nDiff = nNew - nOld;
20479     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
20480           mem0.alarmThreshold-nDiff ){
20481       sqlite3MallocAlarm(nDiff);
20482     }
20483     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
20484     if( pNew==0 && mem0.alarmCallback ){
20485       sqlite3MallocAlarm((int)nBytes);
20486       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
20487     }
20488     if( pNew ){
20489       nNew = sqlite3MallocSize(pNew);
20490       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
20491     }
20492     sqlite3_mutex_leave(mem0.mutex);
20493   }else{
20494     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
20495   }
20496   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
20497   return pNew;
20498 }
20499 
20500 /*
20501 ** The public interface to sqlite3Realloc.  Make sure that the memory
20502 ** subsystem is initialized prior to invoking sqliteRealloc.
20503 */
20504 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
20505 #ifndef SQLITE_OMIT_AUTOINIT
20506   if( sqlite3_initialize() ) return 0;
20507 #endif
20508   if( n<0 ) n = 0;  /* IMP: R-26507-47431 */
20509   return sqlite3Realloc(pOld, n);
20510 }
20511 SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
20512 #ifndef SQLITE_OMIT_AUTOINIT
20513   if( sqlite3_initialize() ) return 0;
20514 #endif
20515   return sqlite3Realloc(pOld, n);
20516 }
20517 
20518 
20519 /*
20520 ** Allocate and zero memory.
20521 */
20522 SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
20523   void *p = sqlite3Malloc(n);
20524   if( p ){
20525     memset(p, 0, (size_t)n);
20526   }
20527   return p;
20528 }
20529 
20530 /*
20531 ** Allocate and zero memory.  If the allocation fails, make
20532 ** the mallocFailed flag in the connection pointer.
20533 */
20534 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
20535   void *p = sqlite3DbMallocRaw(db, n);
20536   if( p ){
20537     memset(p, 0, (size_t)n);
20538   }
20539   return p;
20540 }
20541 
20542 /*
20543 ** Allocate and zero memory.  If the allocation fails, make
20544 ** the mallocFailed flag in the connection pointer.
20545 **
20546 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
20547 ** failure on the same database connection) then always return 0.
20548 ** Hence for a particular database connection, once malloc starts
20549 ** failing, it fails consistently until mallocFailed is reset.
20550 ** This is an important assumption.  There are many places in the
20551 ** code that do things like this:
20552 **
20553 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
20554 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
20555 **         if( b ) a[10] = 9;
20556 **
20557 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
20558 ** that all prior mallocs (ex: "a") worked too.
20559 */
20560 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
20561   void *p;
20562   assert( db==0 || sqlite3_mutex_held(db->mutex) );
20563   assert( db==0 || db->pnBytesFreed==0 );
20564 #ifndef SQLITE_OMIT_LOOKASIDE
20565   if( db ){
20566     LookasideSlot *pBuf;
20567     if( db->mallocFailed ){
20568       return 0;
20569     }
20570     if( db->lookaside.bEnabled ){
20571       if( n>db->lookaside.sz ){
20572         db->lookaside.anStat[1]++;
20573       }else if( (pBuf = db->lookaside.pFree)==0 ){
20574         db->lookaside.anStat[2]++;
20575       }else{
20576         db->lookaside.pFree = pBuf->pNext;
20577         db->lookaside.nOut++;
20578         db->lookaside.anStat[0]++;
20579         if( db->lookaside.nOut>db->lookaside.mxOut ){
20580           db->lookaside.mxOut = db->lookaside.nOut;
20581         }
20582         return (void*)pBuf;
20583       }
20584     }
20585   }
20586 #else
20587   if( db && db->mallocFailed ){
20588     return 0;
20589   }
20590 #endif
20591   p = sqlite3Malloc(n);
20592   if( !p && db ){
20593     db->mallocFailed = 1;
20594   }
20595   sqlite3MemdebugSetType(p,
20596          (db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
20597   return p;
20598 }
20599 
20600 /*
20601 ** Resize the block of memory pointed to by p to n bytes. If the
20602 ** resize fails, set the mallocFailed flag in the connection object.
20603 */
20604 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
20605   void *pNew = 0;
20606   assert( db!=0 );
20607   assert( sqlite3_mutex_held(db->mutex) );
20608   if( db->mallocFailed==0 ){
20609     if( p==0 ){
20610       return sqlite3DbMallocRaw(db, n);
20611     }
20612     if( isLookaside(db, p) ){
20613       if( n<=db->lookaside.sz ){
20614         return p;
20615       }
20616       pNew = sqlite3DbMallocRaw(db, n);
20617       if( pNew ){
20618         memcpy(pNew, p, db->lookaside.sz);
20619         sqlite3DbFree(db, p);
20620       }
20621     }else{
20622       assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20623       assert( sqlite3MemdebugNoType(p, ~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20624       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
20625       pNew = sqlite3_realloc64(p, n);
20626       if( !pNew ){
20627         db->mallocFailed = 1;
20628       }
20629       sqlite3MemdebugSetType(pNew,
20630             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
20631     }
20632   }
20633   return pNew;
20634 }
20635 
20636 /*
20637 ** Attempt to reallocate p.  If the reallocation fails, then free p
20638 ** and set the mallocFailed flag in the database connection.
20639 */
20640 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
20641   void *pNew;
20642   pNew = sqlite3DbRealloc(db, p, n);
20643   if( !pNew ){
20644     sqlite3DbFree(db, p);
20645   }
20646   return pNew;
20647 }
20648 
20649 /*
20650 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
20651 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
20652 ** is because when memory debugging is turned on, these two functions are
20653 ** called via macros that record the current file and line number in the
20654 ** ThreadData structure.
20655 */
20656 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
20657   char *zNew;
20658   size_t n;
20659   if( z==0 ){
20660     return 0;
20661   }
20662   n = sqlite3Strlen30(z) + 1;
20663   assert( (n&0x7fffffff)==n );
20664   zNew = sqlite3DbMallocRaw(db, (int)n);
20665   if( zNew ){
20666     memcpy(zNew, z, n);
20667   }
20668   return zNew;
20669 }
20670 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
20671   char *zNew;
20672   if( z==0 ){
20673     return 0;
20674   }
20675   assert( (n&0x7fffffff)==n );
20676   zNew = sqlite3DbMallocRaw(db, n+1);
20677   if( zNew ){
20678     memcpy(zNew, z, (size_t)n);
20679     zNew[n] = 0;
20680   }
20681   return zNew;
20682 }
20683 
20684 /*
20685 ** Create a string from the zFromat argument and the va_list that follows.
20686 ** Store the string in memory obtained from sqliteMalloc() and make *pz
20687 ** point to that string.
20688 */
20689 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
20690   va_list ap;
20691   char *z;
20692 
20693   va_start(ap, zFormat);
20694   z = sqlite3VMPrintf(db, zFormat, ap);
20695   va_end(ap);
20696   sqlite3DbFree(db, *pz);
20697   *pz = z;
20698 }
20699 
20700 /*
20701 ** Take actions at the end of an API call to indicate an OOM error
20702 */
20703 static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
20704   db->mallocFailed = 0;
20705   sqlite3Error(db, SQLITE_NOMEM);
20706   return SQLITE_NOMEM;
20707 }
20708 
20709 /*
20710 ** This function must be called before exiting any API function (i.e.
20711 ** returning control to the user) that has called sqlite3_malloc or
20712 ** sqlite3_realloc.
20713 **
20714 ** The returned value is normally a copy of the second argument to this
20715 ** function. However, if a malloc() failure has occurred since the previous
20716 ** invocation SQLITE_NOMEM is returned instead.
20717 **
20718 ** If the first argument, db, is not NULL and a malloc() error has occurred,
20719 ** then the connection error-code (the value returned by sqlite3_errcode())
20720 ** is set to SQLITE_NOMEM.
20721 */
20722 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
20723   /* If the db handle is not NULL, then we must hold the connection handle
20724   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
20725   ** is unsafe, as is the call to sqlite3Error().
20726   */
20727   assert( !db || sqlite3_mutex_held(db->mutex) );
20728   if( db==0 ) return rc & 0xff;
20729   if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
20730     return apiOomError(db);
20731   }
20732   return rc & db->errMask;
20733 }
20734 
20735 /************** End of malloc.c **********************************************/
20736 /************** Begin file printf.c ******************************************/
20737 /*
20738 ** The "printf" code that follows dates from the 1980's.  It is in
20739 ** the public domain.  The original comments are included here for
20740 ** completeness.  They are very out-of-date but might be useful as
20741 ** an historical reference.  Most of the "enhancements" have been backed
20742 ** out so that the functionality is now the same as standard printf().
20743 **
20744 **************************************************************************
20745 **
20746 ** This file contains code for a set of "printf"-like routines.  These
20747 ** routines format strings much like the printf() from the standard C
20748 ** library, though the implementation here has enhancements to support
20749 ** SQLlite.
20750 */
20751 
20752 /*
20753 ** If the strchrnul() library function is available, then set
20754 ** HAVE_STRCHRNUL.  If that routine is not available, this module
20755 ** will supply its own.  The built-in version is slower than
20756 ** the glibc version so the glibc version is definitely preferred.
20757 */
20758 #if !defined(HAVE_STRCHRNUL)
20759 # define HAVE_STRCHRNUL 0
20760 #endif
20761 
20762 
20763 /*
20764 ** Conversion types fall into various categories as defined by the
20765 ** following enumeration.
20766 */
20767 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
20768 #define etFLOAT       2 /* Floating point.  %f */
20769 #define etEXP         3 /* Exponentional notation. %e and %E */
20770 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
20771 #define etSIZE        5 /* Return number of characters processed so far. %n */
20772 #define etSTRING      6 /* Strings. %s */
20773 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
20774 #define etPERCENT     8 /* Percent symbol. %% */
20775 #define etCHARX       9 /* Characters. %c */
20776 /* The rest are extensions, not normally found in printf() */
20777 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
20778 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
20779                           NULL pointers replaced by SQL NULL.  %Q */
20780 #define etTOKEN      12 /* a pointer to a Token structure */
20781 #define etSRCLIST    13 /* a pointer to a SrcList */
20782 #define etPOINTER    14 /* The %p conversion */
20783 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
20784 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
20785 
20786 #define etINVALID     0 /* Any unrecognized conversion type */
20787 
20788 
20789 /*
20790 ** An "etByte" is an 8-bit unsigned value.
20791 */
20792 typedef unsigned char etByte;
20793 
20794 /*
20795 ** Each builtin conversion character (ex: the 'd' in "%d") is described
20796 ** by an instance of the following structure
20797 */
20798 typedef struct et_info {   /* Information about each format field */
20799   char fmttype;            /* The format field code letter */
20800   etByte base;             /* The base for radix conversion */
20801   etByte flags;            /* One or more of FLAG_ constants below */
20802   etByte type;             /* Conversion paradigm */
20803   etByte charset;          /* Offset into aDigits[] of the digits string */
20804   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
20805 } et_info;
20806 
20807 /*
20808 ** Allowed values for et_info.flags
20809 */
20810 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
20811 #define FLAG_INTERN  2     /* True if for internal use only */
20812 #define FLAG_STRING  4     /* Allow infinity precision */
20813 
20814 
20815 /*
20816 ** The following table is searched linearly, so it is good to put the
20817 ** most frequently used conversion types first.
20818 */
20819 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
20820 static const char aPrefix[] = "-x0\000X0";
20821 static const et_info fmtinfo[] = {
20822   {  'd', 10, 1, etRADIX,      0,  0 },
20823   {  's',  0, 4, etSTRING,     0,  0 },
20824   {  'g',  0, 1, etGENERIC,    30, 0 },
20825   {  'z',  0, 4, etDYNSTRING,  0,  0 },
20826   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
20827   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
20828   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
20829   {  'c',  0, 0, etCHARX,      0,  0 },
20830   {  'o',  8, 0, etRADIX,      0,  2 },
20831   {  'u', 10, 0, etRADIX,      0,  0 },
20832   {  'x', 16, 0, etRADIX,      16, 1 },
20833   {  'X', 16, 0, etRADIX,      0,  4 },
20834 #ifndef SQLITE_OMIT_FLOATING_POINT
20835   {  'f',  0, 1, etFLOAT,      0,  0 },
20836   {  'e',  0, 1, etEXP,        30, 0 },
20837   {  'E',  0, 1, etEXP,        14, 0 },
20838   {  'G',  0, 1, etGENERIC,    14, 0 },
20839 #endif
20840   {  'i', 10, 1, etRADIX,      0,  0 },
20841   {  'n',  0, 0, etSIZE,       0,  0 },
20842   {  '%',  0, 0, etPERCENT,    0,  0 },
20843   {  'p', 16, 0, etPOINTER,    0,  1 },
20844 
20845 /* All the rest have the FLAG_INTERN bit set and are thus for internal
20846 ** use only */
20847   {  'T',  0, 2, etTOKEN,      0,  0 },
20848   {  'S',  0, 2, etSRCLIST,    0,  0 },
20849   {  'r', 10, 3, etORDINAL,    0,  0 },
20850 };
20851 
20852 /*
20853 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
20854 ** conversions will work.
20855 */
20856 #ifndef SQLITE_OMIT_FLOATING_POINT
20857 /*
20858 ** "*val" is a double such that 0.1 <= *val < 10.0
20859 ** Return the ascii code for the leading digit of *val, then
20860 ** multiply "*val" by 10.0 to renormalize.
20861 **
20862 ** Example:
20863 **     input:     *val = 3.14159
20864 **     output:    *val = 1.4159    function return = '3'
20865 **
20866 ** The counter *cnt is incremented each time.  After counter exceeds
20867 ** 16 (the number of significant digits in a 64-bit float) '0' is
20868 ** always returned.
20869 */
20870 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
20871   int digit;
20872   LONGDOUBLE_TYPE d;
20873   if( (*cnt)<=0 ) return '0';
20874   (*cnt)--;
20875   digit = (int)*val;
20876   d = digit;
20877   digit += '0';
20878   *val = (*val - d)*10.0;
20879   return (char)digit;
20880 }
20881 #endif /* SQLITE_OMIT_FLOATING_POINT */
20882 
20883 /*
20884 ** Set the StrAccum object to an error mode.
20885 */
20886 static void setStrAccumError(StrAccum *p, u8 eError){
20887   p->accError = eError;
20888   p->nAlloc = 0;
20889 }
20890 
20891 /*
20892 ** Extra argument values from a PrintfArguments object
20893 */
20894 static sqlite3_int64 getIntArg(PrintfArguments *p){
20895   if( p->nArg<=p->nUsed ) return 0;
20896   return sqlite3_value_int64(p->apArg[p->nUsed++]);
20897 }
20898 static double getDoubleArg(PrintfArguments *p){
20899   if( p->nArg<=p->nUsed ) return 0.0;
20900   return sqlite3_value_double(p->apArg[p->nUsed++]);
20901 }
20902 static char *getTextArg(PrintfArguments *p){
20903   if( p->nArg<=p->nUsed ) return 0;
20904   return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
20905 }
20906 
20907 
20908 /*
20909 ** On machines with a small stack size, you can redefine the
20910 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
20911 */
20912 #ifndef SQLITE_PRINT_BUF_SIZE
20913 # define SQLITE_PRINT_BUF_SIZE 70
20914 #endif
20915 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
20916 
20917 /*
20918 ** Render a string given by "fmt" into the StrAccum object.
20919 */
20920 SQLITE_PRIVATE void sqlite3VXPrintf(
20921   StrAccum *pAccum,          /* Accumulate results here */
20922   u32 bFlags,                /* SQLITE_PRINTF_* flags */
20923   const char *fmt,           /* Format string */
20924   va_list ap                 /* arguments */
20925 ){
20926   int c;                     /* Next character in the format string */
20927   char *bufpt;               /* Pointer to the conversion buffer */
20928   int precision;             /* Precision of the current field */
20929   int length;                /* Length of the field */
20930   int idx;                   /* A general purpose loop counter */
20931   int width;                 /* Width of the current field */
20932   etByte flag_leftjustify;   /* True if "-" flag is present */
20933   etByte flag_plussign;      /* True if "+" flag is present */
20934   etByte flag_blanksign;     /* True if " " flag is present */
20935   etByte flag_alternateform; /* True if "#" flag is present */
20936   etByte flag_altform2;      /* True if "!" flag is present */
20937   etByte flag_zeropad;       /* True if field width constant starts with zero */
20938   etByte flag_long;          /* True if "l" flag is present */
20939   etByte flag_longlong;      /* True if the "ll" flag is present */
20940   etByte done;               /* Loop termination flag */
20941   etByte xtype = 0;          /* Conversion paradigm */
20942   u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
20943   u8 useIntern;              /* Ok to use internal conversions (ex: %T) */
20944   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
20945   sqlite_uint64 longvalue;   /* Value for integer types */
20946   LONGDOUBLE_TYPE realvalue; /* Value for real types */
20947   const et_info *infop;      /* Pointer to the appropriate info structure */
20948   char *zOut;                /* Rendering buffer */
20949   int nOut;                  /* Size of the rendering buffer */
20950   char *zExtra = 0;          /* Malloced memory used by some conversion */
20951 #ifndef SQLITE_OMIT_FLOATING_POINT
20952   int  exp, e2;              /* exponent of real numbers */
20953   int nsd;                   /* Number of significant digits returned */
20954   double rounder;            /* Used for rounding floating point values */
20955   etByte flag_dp;            /* True if decimal point should be shown */
20956   etByte flag_rtz;           /* True if trailing zeros should be removed */
20957 #endif
20958   PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
20959   char buf[etBUFSIZE];       /* Conversion buffer */
20960 
20961   bufpt = 0;
20962   if( bFlags ){
20963     if( (bArgList = (bFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
20964       pArgList = va_arg(ap, PrintfArguments*);
20965     }
20966     useIntern = bFlags & SQLITE_PRINTF_INTERNAL;
20967   }else{
20968     bArgList = useIntern = 0;
20969   }
20970   for(; (c=(*fmt))!=0; ++fmt){
20971     if( c!='%' ){
20972       bufpt = (char *)fmt;
20973 #if HAVE_STRCHRNUL
20974       fmt = strchrnul(fmt, '%');
20975 #else
20976       do{ fmt++; }while( *fmt && *fmt != '%' );
20977 #endif
20978       sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
20979       if( *fmt==0 ) break;
20980     }
20981     if( (c=(*++fmt))==0 ){
20982       sqlite3StrAccumAppend(pAccum, "%", 1);
20983       break;
20984     }
20985     /* Find out what flags are present */
20986     flag_leftjustify = flag_plussign = flag_blanksign =
20987      flag_alternateform = flag_altform2 = flag_zeropad = 0;
20988     done = 0;
20989     do{
20990       switch( c ){
20991         case '-':   flag_leftjustify = 1;     break;
20992         case '+':   flag_plussign = 1;        break;
20993         case ' ':   flag_blanksign = 1;       break;
20994         case '#':   flag_alternateform = 1;   break;
20995         case '!':   flag_altform2 = 1;        break;
20996         case '0':   flag_zeropad = 1;         break;
20997         default:    done = 1;                 break;
20998       }
20999     }while( !done && (c=(*++fmt))!=0 );
21000     /* Get the field width */
21001     width = 0;
21002     if( c=='*' ){
21003       if( bArgList ){
21004         width = (int)getIntArg(pArgList);
21005       }else{
21006         width = va_arg(ap,int);
21007       }
21008       if( width<0 ){
21009         flag_leftjustify = 1;
21010         width = -width;
21011       }
21012       c = *++fmt;
21013     }else{
21014       while( c>='0' && c<='9' ){
21015         width = width*10 + c - '0';
21016         c = *++fmt;
21017       }
21018     }
21019     /* Get the precision */
21020     if( c=='.' ){
21021       precision = 0;
21022       c = *++fmt;
21023       if( c=='*' ){
21024         if( bArgList ){
21025           precision = (int)getIntArg(pArgList);
21026         }else{
21027           precision = va_arg(ap,int);
21028         }
21029         if( precision<0 ) precision = -precision;
21030         c = *++fmt;
21031       }else{
21032         while( c>='0' && c<='9' ){
21033           precision = precision*10 + c - '0';
21034           c = *++fmt;
21035         }
21036       }
21037     }else{
21038       precision = -1;
21039     }
21040     /* Get the conversion type modifier */
21041     if( c=='l' ){
21042       flag_long = 1;
21043       c = *++fmt;
21044       if( c=='l' ){
21045         flag_longlong = 1;
21046         c = *++fmt;
21047       }else{
21048         flag_longlong = 0;
21049       }
21050     }else{
21051       flag_long = flag_longlong = 0;
21052     }
21053     /* Fetch the info entry for the field */
21054     infop = &fmtinfo[0];
21055     xtype = etINVALID;
21056     for(idx=0; idx<ArraySize(fmtinfo); idx++){
21057       if( c==fmtinfo[idx].fmttype ){
21058         infop = &fmtinfo[idx];
21059         if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
21060           xtype = infop->type;
21061         }else{
21062           return;
21063         }
21064         break;
21065       }
21066     }
21067 
21068     /*
21069     ** At this point, variables are initialized as follows:
21070     **
21071     **   flag_alternateform          TRUE if a '#' is present.
21072     **   flag_altform2               TRUE if a '!' is present.
21073     **   flag_plussign               TRUE if a '+' is present.
21074     **   flag_leftjustify            TRUE if a '-' is present or if the
21075     **                               field width was negative.
21076     **   flag_zeropad                TRUE if the width began with 0.
21077     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
21078     **                               the conversion character.
21079     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
21080     **                               the conversion character.
21081     **   flag_blanksign              TRUE if a ' ' is present.
21082     **   width                       The specified field width.  This is
21083     **                               always non-negative.  Zero is the default.
21084     **   precision                   The specified precision.  The default
21085     **                               is -1.
21086     **   xtype                       The class of the conversion.
21087     **   infop                       Pointer to the appropriate info struct.
21088     */
21089     switch( xtype ){
21090       case etPOINTER:
21091         flag_longlong = sizeof(char*)==sizeof(i64);
21092         flag_long = sizeof(char*)==sizeof(long int);
21093         /* Fall through into the next case */
21094       case etORDINAL:
21095       case etRADIX:
21096         if( infop->flags & FLAG_SIGNED ){
21097           i64 v;
21098           if( bArgList ){
21099             v = getIntArg(pArgList);
21100           }else if( flag_longlong ){
21101             v = va_arg(ap,i64);
21102           }else if( flag_long ){
21103             v = va_arg(ap,long int);
21104           }else{
21105             v = va_arg(ap,int);
21106           }
21107           if( v<0 ){
21108             if( v==SMALLEST_INT64 ){
21109               longvalue = ((u64)1)<<63;
21110             }else{
21111               longvalue = -v;
21112             }
21113             prefix = '-';
21114           }else{
21115             longvalue = v;
21116             if( flag_plussign )        prefix = '+';
21117             else if( flag_blanksign )  prefix = ' ';
21118             else                       prefix = 0;
21119           }
21120         }else{
21121           if( bArgList ){
21122             longvalue = (u64)getIntArg(pArgList);
21123           }else if( flag_longlong ){
21124             longvalue = va_arg(ap,u64);
21125           }else if( flag_long ){
21126             longvalue = va_arg(ap,unsigned long int);
21127           }else{
21128             longvalue = va_arg(ap,unsigned int);
21129           }
21130           prefix = 0;
21131         }
21132         if( longvalue==0 ) flag_alternateform = 0;
21133         if( flag_zeropad && precision<width-(prefix!=0) ){
21134           precision = width-(prefix!=0);
21135         }
21136         if( precision<etBUFSIZE-10 ){
21137           nOut = etBUFSIZE;
21138           zOut = buf;
21139         }else{
21140           nOut = precision + 10;
21141           zOut = zExtra = sqlite3Malloc( nOut );
21142           if( zOut==0 ){
21143             setStrAccumError(pAccum, STRACCUM_NOMEM);
21144             return;
21145           }
21146         }
21147         bufpt = &zOut[nOut-1];
21148         if( xtype==etORDINAL ){
21149           static const char zOrd[] = "thstndrd";
21150           int x = (int)(longvalue % 10);
21151           if( x>=4 || (longvalue/10)%10==1 ){
21152             x = 0;
21153           }
21154           *(--bufpt) = zOrd[x*2+1];
21155           *(--bufpt) = zOrd[x*2];
21156         }
21157         {
21158           const char *cset = &aDigits[infop->charset];
21159           u8 base = infop->base;
21160           do{                                           /* Convert to ascii */
21161             *(--bufpt) = cset[longvalue%base];
21162             longvalue = longvalue/base;
21163           }while( longvalue>0 );
21164         }
21165         length = (int)(&zOut[nOut-1]-bufpt);
21166         for(idx=precision-length; idx>0; idx--){
21167           *(--bufpt) = '0';                             /* Zero pad */
21168         }
21169         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
21170         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
21171           const char *pre;
21172           char x;
21173           pre = &aPrefix[infop->prefix];
21174           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
21175         }
21176         length = (int)(&zOut[nOut-1]-bufpt);
21177         break;
21178       case etFLOAT:
21179       case etEXP:
21180       case etGENERIC:
21181         if( bArgList ){
21182           realvalue = getDoubleArg(pArgList);
21183         }else{
21184           realvalue = va_arg(ap,double);
21185         }
21186 #ifdef SQLITE_OMIT_FLOATING_POINT
21187         length = 0;
21188 #else
21189         if( precision<0 ) precision = 6;         /* Set default precision */
21190         if( realvalue<0.0 ){
21191           realvalue = -realvalue;
21192           prefix = '-';
21193         }else{
21194           if( flag_plussign )          prefix = '+';
21195           else if( flag_blanksign )    prefix = ' ';
21196           else                         prefix = 0;
21197         }
21198         if( xtype==etGENERIC && precision>0 ) precision--;
21199         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
21200         if( xtype==etFLOAT ) realvalue += rounder;
21201         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
21202         exp = 0;
21203         if( sqlite3IsNaN((double)realvalue) ){
21204           bufpt = "NaN";
21205           length = 3;
21206           break;
21207         }
21208         if( realvalue>0.0 ){
21209           LONGDOUBLE_TYPE scale = 1.0;
21210           while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
21211           while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
21212           while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
21213           while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
21214           realvalue /= scale;
21215           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
21216           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
21217           if( exp>350 ){
21218             if( prefix=='-' ){
21219               bufpt = "-Inf";
21220             }else if( prefix=='+' ){
21221               bufpt = "+Inf";
21222             }else{
21223               bufpt = "Inf";
21224             }
21225             length = sqlite3Strlen30(bufpt);
21226             break;
21227           }
21228         }
21229         bufpt = buf;
21230         /*
21231         ** If the field type is etGENERIC, then convert to either etEXP
21232         ** or etFLOAT, as appropriate.
21233         */
21234         if( xtype!=etFLOAT ){
21235           realvalue += rounder;
21236           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
21237         }
21238         if( xtype==etGENERIC ){
21239           flag_rtz = !flag_alternateform;
21240           if( exp<-4 || exp>precision ){
21241             xtype = etEXP;
21242           }else{
21243             precision = precision - exp;
21244             xtype = etFLOAT;
21245           }
21246         }else{
21247           flag_rtz = flag_altform2;
21248         }
21249         if( xtype==etEXP ){
21250           e2 = 0;
21251         }else{
21252           e2 = exp;
21253         }
21254         if( MAX(e2,0)+precision+width > etBUFSIZE - 15 ){
21255           bufpt = zExtra = sqlite3Malloc( MAX(e2,0)+precision+width+15 );
21256           if( bufpt==0 ){
21257             setStrAccumError(pAccum, STRACCUM_NOMEM);
21258             return;
21259           }
21260         }
21261         zOut = bufpt;
21262         nsd = 16 + flag_altform2*10;
21263         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
21264         /* The sign in front of the number */
21265         if( prefix ){
21266           *(bufpt++) = prefix;
21267         }
21268         /* Digits prior to the decimal point */
21269         if( e2<0 ){
21270           *(bufpt++) = '0';
21271         }else{
21272           for(; e2>=0; e2--){
21273             *(bufpt++) = et_getdigit(&realvalue,&nsd);
21274           }
21275         }
21276         /* The decimal point */
21277         if( flag_dp ){
21278           *(bufpt++) = '.';
21279         }
21280         /* "0" digits after the decimal point but before the first
21281         ** significant digit of the number */
21282         for(e2++; e2<0; precision--, e2++){
21283           assert( precision>0 );
21284           *(bufpt++) = '0';
21285         }
21286         /* Significant digits after the decimal point */
21287         while( (precision--)>0 ){
21288           *(bufpt++) = et_getdigit(&realvalue,&nsd);
21289         }
21290         /* Remove trailing zeros and the "." if no digits follow the "." */
21291         if( flag_rtz && flag_dp ){
21292           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
21293           assert( bufpt>zOut );
21294           if( bufpt[-1]=='.' ){
21295             if( flag_altform2 ){
21296               *(bufpt++) = '0';
21297             }else{
21298               *(--bufpt) = 0;
21299             }
21300           }
21301         }
21302         /* Add the "eNNN" suffix */
21303         if( xtype==etEXP ){
21304           *(bufpt++) = aDigits[infop->charset];
21305           if( exp<0 ){
21306             *(bufpt++) = '-'; exp = -exp;
21307           }else{
21308             *(bufpt++) = '+';
21309           }
21310           if( exp>=100 ){
21311             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
21312             exp %= 100;
21313           }
21314           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
21315           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
21316         }
21317         *bufpt = 0;
21318 
21319         /* The converted number is in buf[] and zero terminated. Output it.
21320         ** Note that the number is in the usual order, not reversed as with
21321         ** integer conversions. */
21322         length = (int)(bufpt-zOut);
21323         bufpt = zOut;
21324 
21325         /* Special case:  Add leading zeros if the flag_zeropad flag is
21326         ** set and we are not left justified */
21327         if( flag_zeropad && !flag_leftjustify && length < width){
21328           int i;
21329           int nPad = width - length;
21330           for(i=width; i>=nPad; i--){
21331             bufpt[i] = bufpt[i-nPad];
21332           }
21333           i = prefix!=0;
21334           while( nPad-- ) bufpt[i++] = '0';
21335           length = width;
21336         }
21337 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
21338         break;
21339       case etSIZE:
21340         if( !bArgList ){
21341           *(va_arg(ap,int*)) = pAccum->nChar;
21342         }
21343         length = width = 0;
21344         break;
21345       case etPERCENT:
21346         buf[0] = '%';
21347         bufpt = buf;
21348         length = 1;
21349         break;
21350       case etCHARX:
21351         if( bArgList ){
21352           bufpt = getTextArg(pArgList);
21353           c = bufpt ? bufpt[0] : 0;
21354         }else{
21355           c = va_arg(ap,int);
21356         }
21357         if( precision>1 ){
21358           width -= precision-1;
21359           if( width>1 && !flag_leftjustify ){
21360             sqlite3AppendChar(pAccum, width-1, ' ');
21361             width = 0;
21362           }
21363           sqlite3AppendChar(pAccum, precision-1, c);
21364         }
21365         length = 1;
21366         buf[0] = c;
21367         bufpt = buf;
21368         break;
21369       case etSTRING:
21370       case etDYNSTRING:
21371         if( bArgList ){
21372           bufpt = getTextArg(pArgList);
21373         }else{
21374           bufpt = va_arg(ap,char*);
21375         }
21376         if( bufpt==0 ){
21377           bufpt = "";
21378         }else if( xtype==etDYNSTRING && !bArgList ){
21379           zExtra = bufpt;
21380         }
21381         if( precision>=0 ){
21382           for(length=0; length<precision && bufpt[length]; length++){}
21383         }else{
21384           length = sqlite3Strlen30(bufpt);
21385         }
21386         break;
21387       case etSQLESCAPE:
21388       case etSQLESCAPE2:
21389       case etSQLESCAPE3: {
21390         int i, j, k, n, isnull;
21391         int needQuote;
21392         char ch;
21393         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
21394         char *escarg;
21395 
21396         if( bArgList ){
21397           escarg = getTextArg(pArgList);
21398         }else{
21399           escarg = va_arg(ap,char*);
21400         }
21401         isnull = escarg==0;
21402         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
21403         k = precision;
21404         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
21405           if( ch==q )  n++;
21406         }
21407         needQuote = !isnull && xtype==etSQLESCAPE2;
21408         n += i + 1 + needQuote*2;
21409         if( n>etBUFSIZE ){
21410           bufpt = zExtra = sqlite3Malloc( n );
21411           if( bufpt==0 ){
21412             setStrAccumError(pAccum, STRACCUM_NOMEM);
21413             return;
21414           }
21415         }else{
21416           bufpt = buf;
21417         }
21418         j = 0;
21419         if( needQuote ) bufpt[j++] = q;
21420         k = i;
21421         for(i=0; i<k; i++){
21422           bufpt[j++] = ch = escarg[i];
21423           if( ch==q ) bufpt[j++] = ch;
21424         }
21425         if( needQuote ) bufpt[j++] = q;
21426         bufpt[j] = 0;
21427         length = j;
21428         /* The precision in %q and %Q means how many input characters to
21429         ** consume, not the length of the output...
21430         ** if( precision>=0 && precision<length ) length = precision; */
21431         break;
21432       }
21433       case etTOKEN: {
21434         Token *pToken = va_arg(ap, Token*);
21435         assert( bArgList==0 );
21436         if( pToken && pToken->n ){
21437           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
21438         }
21439         length = width = 0;
21440         break;
21441       }
21442       case etSRCLIST: {
21443         SrcList *pSrc = va_arg(ap, SrcList*);
21444         int k = va_arg(ap, int);
21445         struct SrcList_item *pItem = &pSrc->a[k];
21446         assert( bArgList==0 );
21447         assert( k>=0 && k<pSrc->nSrc );
21448         if( pItem->zDatabase ){
21449           sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
21450           sqlite3StrAccumAppend(pAccum, ".", 1);
21451         }
21452         sqlite3StrAccumAppendAll(pAccum, pItem->zName);
21453         length = width = 0;
21454         break;
21455       }
21456       default: {
21457         assert( xtype==etINVALID );
21458         return;
21459       }
21460     }/* End switch over the format type */
21461     /*
21462     ** The text of the conversion is pointed to by "bufpt" and is
21463     ** "length" characters long.  The field width is "width".  Do
21464     ** the output.
21465     */
21466     width -= length;
21467     if( width>0 && !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
21468     sqlite3StrAccumAppend(pAccum, bufpt, length);
21469     if( width>0 && flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
21470 
21471     if( zExtra ){
21472       sqlite3_free(zExtra);
21473       zExtra = 0;
21474     }
21475   }/* End for loop over the format string */
21476 } /* End of function */
21477 
21478 /*
21479 ** Enlarge the memory allocation on a StrAccum object so that it is
21480 ** able to accept at least N more bytes of text.
21481 **
21482 ** Return the number of bytes of text that StrAccum is able to accept
21483 ** after the attempted enlargement.  The value returned might be zero.
21484 */
21485 static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
21486   char *zNew;
21487   assert( p->nChar+N >= p->nAlloc ); /* Only called if really needed */
21488   if( p->accError ){
21489     testcase(p->accError==STRACCUM_TOOBIG);
21490     testcase(p->accError==STRACCUM_NOMEM);
21491     return 0;
21492   }
21493   if( !p->useMalloc ){
21494     N = p->nAlloc - p->nChar - 1;
21495     setStrAccumError(p, STRACCUM_TOOBIG);
21496     return N;
21497   }else{
21498     char *zOld = (p->zText==p->zBase ? 0 : p->zText);
21499     i64 szNew = p->nChar;
21500     szNew += N + 1;
21501     if( szNew > p->mxAlloc ){
21502       sqlite3StrAccumReset(p);
21503       setStrAccumError(p, STRACCUM_TOOBIG);
21504       return 0;
21505     }else{
21506       p->nAlloc = (int)szNew;
21507     }
21508     if( p->useMalloc==1 ){
21509       zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
21510     }else{
21511       zNew = sqlite3_realloc(zOld, p->nAlloc);
21512     }
21513     if( zNew ){
21514       assert( p->zText!=0 || p->nChar==0 );
21515       if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
21516       p->zText = zNew;
21517     }else{
21518       sqlite3StrAccumReset(p);
21519       setStrAccumError(p, STRACCUM_NOMEM);
21520       return 0;
21521     }
21522   }
21523   return N;
21524 }
21525 
21526 /*
21527 ** Append N copies of character c to the given string buffer.
21528 */
21529 SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
21530   if( p->nChar+N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ) return;
21531   while( (N--)>0 ) p->zText[p->nChar++] = c;
21532 }
21533 
21534 /*
21535 ** The StrAccum "p" is not large enough to accept N new bytes of z[].
21536 ** So enlarge if first, then do the append.
21537 **
21538 ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
21539 ** work (enlarging the buffer) using tail recursion, so that the
21540 ** sqlite3StrAccumAppend() routine can use fast calling semantics.
21541 */
21542 static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
21543   N = sqlite3StrAccumEnlarge(p, N);
21544   if( N>0 ){
21545     memcpy(&p->zText[p->nChar], z, N);
21546     p->nChar += N;
21547   }
21548 }
21549 
21550 /*
21551 ** Append N bytes of text from z to the StrAccum object.  Increase the
21552 ** size of the memory allocation for StrAccum if necessary.
21553 */
21554 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
21555   assert( z!=0 );
21556   assert( p->zText!=0 || p->nChar==0 || p->accError );
21557   assert( N>=0 );
21558   assert( p->accError==0 || p->nAlloc==0 );
21559   if( p->nChar+N >= p->nAlloc ){
21560     enlargeAndAppend(p,z,N);
21561   }else{
21562     assert( p->zText );
21563     p->nChar += N;
21564     memcpy(&p->zText[p->nChar-N], z, N);
21565   }
21566 }
21567 
21568 /*
21569 ** Append the complete text of zero-terminated string z[] to the p string.
21570 */
21571 SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
21572   sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
21573 }
21574 
21575 
21576 /*
21577 ** Finish off a string by making sure it is zero-terminated.
21578 ** Return a pointer to the resulting string.  Return a NULL
21579 ** pointer if any kind of error was encountered.
21580 */
21581 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
21582   if( p->zText ){
21583     p->zText[p->nChar] = 0;
21584     if( p->useMalloc && p->zText==p->zBase ){
21585       if( p->useMalloc==1 ){
21586         p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
21587       }else{
21588         p->zText = sqlite3_malloc(p->nChar+1);
21589       }
21590       if( p->zText ){
21591         memcpy(p->zText, p->zBase, p->nChar+1);
21592       }else{
21593         setStrAccumError(p, STRACCUM_NOMEM);
21594       }
21595     }
21596   }
21597   return p->zText;
21598 }
21599 
21600 /*
21601 ** Reset an StrAccum string.  Reclaim all malloced memory.
21602 */
21603 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
21604   if( p->zText!=p->zBase ){
21605     if( p->useMalloc==1 ){
21606       sqlite3DbFree(p->db, p->zText);
21607     }else{
21608       sqlite3_free(p->zText);
21609     }
21610   }
21611   p->zText = 0;
21612 }
21613 
21614 /*
21615 ** Initialize a string accumulator
21616 */
21617 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
21618   p->zText = p->zBase = zBase;
21619   p->db = 0;
21620   p->nChar = 0;
21621   p->nAlloc = n;
21622   p->mxAlloc = mx;
21623   p->useMalloc = 1;
21624   p->accError = 0;
21625 }
21626 
21627 /*
21628 ** Print into memory obtained from sqliteMalloc().  Use the internal
21629 ** %-conversion extensions.
21630 */
21631 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
21632   char *z;
21633   char zBase[SQLITE_PRINT_BUF_SIZE];
21634   StrAccum acc;
21635   assert( db!=0 );
21636   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
21637                       db->aLimit[SQLITE_LIMIT_LENGTH]);
21638   acc.db = db;
21639   sqlite3VXPrintf(&acc, SQLITE_PRINTF_INTERNAL, zFormat, ap);
21640   z = sqlite3StrAccumFinish(&acc);
21641   if( acc.accError==STRACCUM_NOMEM ){
21642     db->mallocFailed = 1;
21643   }
21644   return z;
21645 }
21646 
21647 /*
21648 ** Print into memory obtained from sqliteMalloc().  Use the internal
21649 ** %-conversion extensions.
21650 */
21651 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
21652   va_list ap;
21653   char *z;
21654   va_start(ap, zFormat);
21655   z = sqlite3VMPrintf(db, zFormat, ap);
21656   va_end(ap);
21657   return z;
21658 }
21659 
21660 /*
21661 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
21662 ** the string and before returning.  This routine is intended to be used
21663 ** to modify an existing string.  For example:
21664 **
21665 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
21666 **
21667 */
21668 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
21669   va_list ap;
21670   char *z;
21671   va_start(ap, zFormat);
21672   z = sqlite3VMPrintf(db, zFormat, ap);
21673   va_end(ap);
21674   sqlite3DbFree(db, zStr);
21675   return z;
21676 }
21677 
21678 /*
21679 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
21680 ** %-conversion extensions.
21681 */
21682 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
21683   char *z;
21684   char zBase[SQLITE_PRINT_BUF_SIZE];
21685   StrAccum acc;
21686 #ifndef SQLITE_OMIT_AUTOINIT
21687   if( sqlite3_initialize() ) return 0;
21688 #endif
21689   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
21690   acc.useMalloc = 2;
21691   sqlite3VXPrintf(&acc, 0, zFormat, ap);
21692   z = sqlite3StrAccumFinish(&acc);
21693   return z;
21694 }
21695 
21696 /*
21697 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
21698 ** %-conversion extensions.
21699 */
21700 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
21701   va_list ap;
21702   char *z;
21703 #ifndef SQLITE_OMIT_AUTOINIT
21704   if( sqlite3_initialize() ) return 0;
21705 #endif
21706   va_start(ap, zFormat);
21707   z = sqlite3_vmprintf(zFormat, ap);
21708   va_end(ap);
21709   return z;
21710 }
21711 
21712 /*
21713 ** sqlite3_snprintf() works like snprintf() except that it ignores the
21714 ** current locale settings.  This is important for SQLite because we
21715 ** are not able to use a "," as the decimal point in place of "." as
21716 ** specified by some locales.
21717 **
21718 ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
21719 ** from the snprintf() standard.  Unfortunately, it is too late to change
21720 ** this without breaking compatibility, so we just have to live with the
21721 ** mistake.
21722 **
21723 ** sqlite3_vsnprintf() is the varargs version.
21724 */
21725 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
21726   StrAccum acc;
21727   if( n<=0 ) return zBuf;
21728   sqlite3StrAccumInit(&acc, zBuf, n, 0);
21729   acc.useMalloc = 0;
21730   sqlite3VXPrintf(&acc, 0, zFormat, ap);
21731   return sqlite3StrAccumFinish(&acc);
21732 }
21733 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
21734   char *z;
21735   va_list ap;
21736   va_start(ap,zFormat);
21737   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
21738   va_end(ap);
21739   return z;
21740 }
21741 
21742 /*
21743 ** This is the routine that actually formats the sqlite3_log() message.
21744 ** We house it in a separate routine from sqlite3_log() to avoid using
21745 ** stack space on small-stack systems when logging is disabled.
21746 **
21747 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
21748 ** allocate memory because it might be called while the memory allocator
21749 ** mutex is held.
21750 */
21751 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
21752   StrAccum acc;                          /* String accumulator */
21753   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
21754 
21755   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
21756   acc.useMalloc = 0;
21757   sqlite3VXPrintf(&acc, 0, zFormat, ap);
21758   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
21759                            sqlite3StrAccumFinish(&acc));
21760 }
21761 
21762 /*
21763 ** Format and write a message to the log if logging is enabled.
21764 */
21765 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
21766   va_list ap;                             /* Vararg list */
21767   if( sqlite3GlobalConfig.xLog ){
21768     va_start(ap, zFormat);
21769     renderLogMsg(iErrCode, zFormat, ap);
21770     va_end(ap);
21771   }
21772 }
21773 
21774 #if defined(SQLITE_DEBUG)
21775 /*
21776 ** A version of printf() that understands %lld.  Used for debugging.
21777 ** The printf() built into some versions of windows does not understand %lld
21778 ** and segfaults if you give it a long long int.
21779 */
21780 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
21781   va_list ap;
21782   StrAccum acc;
21783   char zBuf[500];
21784   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
21785   acc.useMalloc = 0;
21786   va_start(ap,zFormat);
21787   sqlite3VXPrintf(&acc, 0, zFormat, ap);
21788   va_end(ap);
21789   sqlite3StrAccumFinish(&acc);
21790   fprintf(stdout,"%s", zBuf);
21791   fflush(stdout);
21792 }
21793 #endif
21794 
21795 #ifdef SQLITE_DEBUG
21796 /*************************************************************************
21797 ** Routines for implementing the "TreeView" display of hierarchical
21798 ** data structures for debugging.
21799 **
21800 ** The main entry points (coded elsewhere) are:
21801 **     sqlite3TreeViewExpr(0, pExpr, 0);
21802 **     sqlite3TreeViewExprList(0, pList, 0, 0);
21803 **     sqlite3TreeViewSelect(0, pSelect, 0);
21804 ** Insert calls to those routines while debugging in order to display
21805 ** a diagram of Expr, ExprList, and Select objects.
21806 **
21807 */
21808 /* Add a new subitem to the tree.  The moreToFollow flag indicates that this
21809 ** is not the last item in the tree. */
21810 SQLITE_PRIVATE TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
21811   if( p==0 ){
21812     p = sqlite3_malloc( sizeof(*p) );
21813     if( p==0 ) return 0;
21814     memset(p, 0, sizeof(*p));
21815   }else{
21816     p->iLevel++;
21817   }
21818   assert( moreToFollow==0 || moreToFollow==1 );
21819   if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
21820   return p;
21821 }
21822 /* Finished with one layer of the tree */
21823 SQLITE_PRIVATE void sqlite3TreeViewPop(TreeView *p){
21824   if( p==0 ) return;
21825   p->iLevel--;
21826   if( p->iLevel<0 ) sqlite3_free(p);
21827 }
21828 /* Generate a single line of output for the tree, with a prefix that contains
21829 ** all the appropriate tree lines */
21830 SQLITE_PRIVATE void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
21831   va_list ap;
21832   int i;
21833   StrAccum acc;
21834   char zBuf[500];
21835   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
21836   acc.useMalloc = 0;
21837   if( p ){
21838     for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
21839       sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|   " : "    ", 4);
21840     }
21841     sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
21842   }
21843   va_start(ap, zFormat);
21844   sqlite3VXPrintf(&acc, 0, zFormat, ap);
21845   va_end(ap);
21846   if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
21847   sqlite3StrAccumFinish(&acc);
21848   fprintf(stdout,"%s", zBuf);
21849   fflush(stdout);
21850 }
21851 /* Shorthand for starting a new tree item that consists of a single label */
21852 SQLITE_PRIVATE void sqlite3TreeViewItem(TreeView *p, const char *zLabel, u8 moreToFollow){
21853   p = sqlite3TreeViewPush(p, moreToFollow);
21854   sqlite3TreeViewLine(p, "%s", zLabel);
21855 }
21856 #endif /* SQLITE_DEBUG */
21857 
21858 /*
21859 ** variable-argument wrapper around sqlite3VXPrintf().
21860 */
21861 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, u32 bFlags, const char *zFormat, ...){
21862   va_list ap;
21863   va_start(ap,zFormat);
21864   sqlite3VXPrintf(p, bFlags, zFormat, ap);
21865   va_end(ap);
21866 }
21867 
21868 /************** End of printf.c **********************************************/
21869 /************** Begin file random.c ******************************************/
21870 /*
21871 ** 2001 September 15
21872 **
21873 ** The author disclaims copyright to this source code.  In place of
21874 ** a legal notice, here is a blessing:
21875 **
21876 **    May you do good and not evil.
21877 **    May you find forgiveness for yourself and forgive others.
21878 **    May you share freely, never taking more than you give.
21879 **
21880 *************************************************************************
21881 ** This file contains code to implement a pseudo-random number
21882 ** generator (PRNG) for SQLite.
21883 **
21884 ** Random numbers are used by some of the database backends in order
21885 ** to generate random integer keys for tables or random filenames.
21886 */
21887 
21888 
21889 /* All threads share a single random number generator.
21890 ** This structure is the current state of the generator.
21891 */
21892 static SQLITE_WSD struct sqlite3PrngType {
21893   unsigned char isInit;          /* True if initialized */
21894   unsigned char i, j;            /* State variables */
21895   unsigned char s[256];          /* State variables */
21896 } sqlite3Prng;
21897 
21898 /*
21899 ** Return N random bytes.
21900 */
21901 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
21902   unsigned char t;
21903   unsigned char *zBuf = pBuf;
21904 
21905   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
21906   ** state vector.  If writable static data is unsupported on the target,
21907   ** we have to locate the state vector at run-time.  In the more common
21908   ** case where writable static data is supported, wsdPrng can refer directly
21909   ** to the "sqlite3Prng" state vector declared above.
21910   */
21911 #ifdef SQLITE_OMIT_WSD
21912   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
21913 # define wsdPrng p[0]
21914 #else
21915 # define wsdPrng sqlite3Prng
21916 #endif
21917 
21918 #if SQLITE_THREADSAFE
21919   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
21920   sqlite3_mutex_enter(mutex);
21921 #endif
21922 
21923   if( N<=0 ){
21924     wsdPrng.isInit = 0;
21925     sqlite3_mutex_leave(mutex);
21926     return;
21927   }
21928 
21929   /* Initialize the state of the random number generator once,
21930   ** the first time this routine is called.  The seed value does
21931   ** not need to contain a lot of randomness since we are not
21932   ** trying to do secure encryption or anything like that...
21933   **
21934   ** Nothing in this file or anywhere else in SQLite does any kind of
21935   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
21936   ** number generator) not as an encryption device.
21937   */
21938   if( !wsdPrng.isInit ){
21939     int i;
21940     char k[256];
21941     wsdPrng.j = 0;
21942     wsdPrng.i = 0;
21943     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
21944     for(i=0; i<256; i++){
21945       wsdPrng.s[i] = (u8)i;
21946     }
21947     for(i=0; i<256; i++){
21948       wsdPrng.j += wsdPrng.s[i] + k[i];
21949       t = wsdPrng.s[wsdPrng.j];
21950       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
21951       wsdPrng.s[i] = t;
21952     }
21953     wsdPrng.isInit = 1;
21954   }
21955 
21956   assert( N>0 );
21957   do{
21958     wsdPrng.i++;
21959     t = wsdPrng.s[wsdPrng.i];
21960     wsdPrng.j += t;
21961     wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
21962     wsdPrng.s[wsdPrng.j] = t;
21963     t += wsdPrng.s[wsdPrng.i];
21964     *(zBuf++) = wsdPrng.s[t];
21965   }while( --N );
21966   sqlite3_mutex_leave(mutex);
21967 }
21968 
21969 #ifndef SQLITE_OMIT_BUILTIN_TEST
21970 /*
21971 ** For testing purposes, we sometimes want to preserve the state of
21972 ** PRNG and restore the PRNG to its saved state at a later time, or
21973 ** to reset the PRNG to its initial state.  These routines accomplish
21974 ** those tasks.
21975 **
21976 ** The sqlite3_test_control() interface calls these routines to
21977 ** control the PRNG.
21978 */
21979 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
21980 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
21981   memcpy(
21982     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
21983     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
21984     sizeof(sqlite3Prng)
21985   );
21986 }
21987 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
21988   memcpy(
21989     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
21990     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
21991     sizeof(sqlite3Prng)
21992   );
21993 }
21994 #endif /* SQLITE_OMIT_BUILTIN_TEST */
21995 
21996 /************** End of random.c **********************************************/
21997 /************** Begin file threads.c *****************************************/
21998 /*
21999 ** 2012 July 21
22000 **
22001 ** The author disclaims copyright to this source code.  In place of
22002 ** a legal notice, here is a blessing:
22003 **
22004 **    May you do good and not evil.
22005 **    May you find forgiveness for yourself and forgive others.
22006 **    May you share freely, never taking more than you give.
22007 **
22008 ******************************************************************************
22009 **
22010 ** This file presents a simple cross-platform threading interface for
22011 ** use internally by SQLite.
22012 **
22013 ** A "thread" can be created using sqlite3ThreadCreate().  This thread
22014 ** runs independently of its creator until it is joined using
22015 ** sqlite3ThreadJoin(), at which point it terminates.
22016 **
22017 ** Threads do not have to be real.  It could be that the work of the
22018 ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
22019 ** or sqlite3ThreadJoin() call.  This is, in fact, what happens in
22020 ** single threaded systems.  Nothing in SQLite requires multiple threads.
22021 ** This interface exists so that applications that want to take advantage
22022 ** of multiple cores can do so, while also allowing applications to stay
22023 ** single-threaded if desired.
22024 */
22025 
22026 #if SQLITE_MAX_WORKER_THREADS>0
22027 
22028 /********************************* Unix Pthreads ****************************/
22029 #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
22030 
22031 #define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
22032 /* #include <pthread.h> */
22033 
22034 /* A running thread */
22035 struct SQLiteThread {
22036   pthread_t tid;                 /* Thread ID */
22037   int done;                      /* Set to true when thread finishes */
22038   void *pOut;                    /* Result returned by the thread */
22039   void *(*xTask)(void*);         /* The thread routine */
22040   void *pIn;                     /* Argument to the thread */
22041 };
22042 
22043 /* Create a new thread */
22044 SQLITE_PRIVATE int sqlite3ThreadCreate(
22045   SQLiteThread **ppThread,  /* OUT: Write the thread object here */
22046   void *(*xTask)(void*),    /* Routine to run in a separate thread */
22047   void *pIn                 /* Argument passed into xTask() */
22048 ){
22049   SQLiteThread *p;
22050   int rc;
22051 
22052   assert( ppThread!=0 );
22053   assert( xTask!=0 );
22054   /* This routine is never used in single-threaded mode */
22055   assert( sqlite3GlobalConfig.bCoreMutex!=0 );
22056 
22057   *ppThread = 0;
22058   p = sqlite3Malloc(sizeof(*p));
22059   if( p==0 ) return SQLITE_NOMEM;
22060   memset(p, 0, sizeof(*p));
22061   p->xTask = xTask;
22062   p->pIn = pIn;
22063   if( sqlite3FaultSim(200) ){
22064     rc = 1;
22065   }else{
22066     rc = pthread_create(&p->tid, 0, xTask, pIn);
22067   }
22068   if( rc ){
22069     p->done = 1;
22070     p->pOut = xTask(pIn);
22071   }
22072   *ppThread = p;
22073   return SQLITE_OK;
22074 }
22075 
22076 /* Get the results of the thread */
22077 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
22078   int rc;
22079 
22080   assert( ppOut!=0 );
22081   if( NEVER(p==0) ) return SQLITE_NOMEM;
22082   if( p->done ){
22083     *ppOut = p->pOut;
22084     rc = SQLITE_OK;
22085   }else{
22086     rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
22087   }
22088   sqlite3_free(p);
22089   return rc;
22090 }
22091 
22092 #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
22093 /******************************** End Unix Pthreads *************************/
22094 
22095 
22096 /********************************* Win32 Threads ****************************/
22097 #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_THREADSAFE>0
22098 
22099 #define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
22100 #include <process.h>
22101 
22102 /* A running thread */
22103 struct SQLiteThread {
22104   void *tid;               /* The thread handle */
22105   unsigned id;             /* The thread identifier */
22106   void *(*xTask)(void*);   /* The routine to run as a thread */
22107   void *pIn;               /* Argument to xTask */
22108   void *pResult;           /* Result of xTask */
22109 };
22110 
22111 /* Thread procedure Win32 compatibility shim */
22112 static unsigned __stdcall sqlite3ThreadProc(
22113   void *pArg  /* IN: Pointer to the SQLiteThread structure */
22114 ){
22115   SQLiteThread *p = (SQLiteThread *)pArg;
22116 
22117   assert( p!=0 );
22118 #if 0
22119   /*
22120   ** This assert appears to trigger spuriously on certain
22121   ** versions of Windows, possibly due to _beginthreadex()
22122   ** and/or CreateThread() not fully setting their thread
22123   ** ID parameter before starting the thread.
22124   */
22125   assert( p->id==GetCurrentThreadId() );
22126 #endif
22127   assert( p->xTask!=0 );
22128   p->pResult = p->xTask(p->pIn);
22129 
22130   _endthreadex(0);
22131   return 0; /* NOT REACHED */
22132 }
22133 
22134 /* Create a new thread */
22135 SQLITE_PRIVATE int sqlite3ThreadCreate(
22136   SQLiteThread **ppThread,  /* OUT: Write the thread object here */
22137   void *(*xTask)(void*),    /* Routine to run in a separate thread */
22138   void *pIn                 /* Argument passed into xTask() */
22139 ){
22140   SQLiteThread *p;
22141 
22142   assert( ppThread!=0 );
22143   assert( xTask!=0 );
22144   *ppThread = 0;
22145   p = sqlite3Malloc(sizeof(*p));
22146   if( p==0 ) return SQLITE_NOMEM;
22147   if( sqlite3GlobalConfig.bCoreMutex==0 ){
22148     memset(p, 0, sizeof(*p));
22149   }else{
22150     p->xTask = xTask;
22151     p->pIn = pIn;
22152     p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
22153     if( p->tid==0 ){
22154       memset(p, 0, sizeof(*p));
22155     }
22156   }
22157   if( p->xTask==0 ){
22158     p->id = GetCurrentThreadId();
22159     p->pResult = xTask(pIn);
22160   }
22161   *ppThread = p;
22162   return SQLITE_OK;
22163 }
22164 
22165 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
22166 
22167 /* Get the results of the thread */
22168 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
22169   DWORD rc;
22170   BOOL bRc;
22171 
22172   assert( ppOut!=0 );
22173   if( NEVER(p==0) ) return SQLITE_NOMEM;
22174   if( p->xTask==0 ){
22175     assert( p->id==GetCurrentThreadId() );
22176     rc = WAIT_OBJECT_0;
22177     assert( p->tid==0 );
22178   }else{
22179     assert( p->id!=0 && p->id!=GetCurrentThreadId() );
22180     rc = sqlite3Win32Wait((HANDLE)p->tid);
22181     assert( rc!=WAIT_IO_COMPLETION );
22182     bRc = CloseHandle((HANDLE)p->tid);
22183     assert( bRc );
22184   }
22185   if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
22186   sqlite3_free(p);
22187   return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
22188 }
22189 
22190 #endif /* SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT */
22191 /******************************** End Win32 Threads *************************/
22192 
22193 
22194 /********************************* Single-Threaded **************************/
22195 #ifndef SQLITE_THREADS_IMPLEMENTED
22196 /*
22197 ** This implementation does not actually create a new thread.  It does the
22198 ** work of the thread in the main thread, when either the thread is created
22199 ** or when it is joined
22200 */
22201 
22202 /* A running thread */
22203 struct SQLiteThread {
22204   void *(*xTask)(void*);   /* The routine to run as a thread */
22205   void *pIn;               /* Argument to xTask */
22206   void *pResult;           /* Result of xTask */
22207 };
22208 
22209 /* Create a new thread */
22210 SQLITE_PRIVATE int sqlite3ThreadCreate(
22211   SQLiteThread **ppThread,  /* OUT: Write the thread object here */
22212   void *(*xTask)(void*),    /* Routine to run in a separate thread */
22213   void *pIn                 /* Argument passed into xTask() */
22214 ){
22215   SQLiteThread *p;
22216 
22217   assert( ppThread!=0 );
22218   assert( xTask!=0 );
22219   *ppThread = 0;
22220   p = sqlite3Malloc(sizeof(*p));
22221   if( p==0 ) return SQLITE_NOMEM;
22222   if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
22223     p->xTask = xTask;
22224     p->pIn = pIn;
22225   }else{
22226     p->xTask = 0;
22227     p->pResult = xTask(pIn);
22228   }
22229   *ppThread = p;
22230   return SQLITE_OK;
22231 }
22232 
22233 /* Get the results of the thread */
22234 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
22235 
22236   assert( ppOut!=0 );
22237   if( NEVER(p==0) ) return SQLITE_NOMEM;
22238   if( p->xTask ){
22239     *ppOut = p->xTask(p->pIn);
22240   }else{
22241     *ppOut = p->pResult;
22242   }
22243   sqlite3_free(p);
22244 
22245 #if defined(SQLITE_TEST)
22246   {
22247     void *pTstAlloc = sqlite3Malloc(10);
22248     if (!pTstAlloc) return SQLITE_NOMEM;
22249     sqlite3_free(pTstAlloc);
22250   }
22251 #endif
22252 
22253   return SQLITE_OK;
22254 }
22255 
22256 #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
22257 /****************************** End Single-Threaded *************************/
22258 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
22259 
22260 /************** End of threads.c *********************************************/
22261 /************** Begin file utf.c *********************************************/
22262 /*
22263 ** 2004 April 13
22264 **
22265 ** The author disclaims copyright to this source code.  In place of
22266 ** a legal notice, here is a blessing:
22267 **
22268 **    May you do good and not evil.
22269 **    May you find forgiveness for yourself and forgive others.
22270 **    May you share freely, never taking more than you give.
22271 **
22272 *************************************************************************
22273 ** This file contains routines used to translate between UTF-8,
22274 ** UTF-16, UTF-16BE, and UTF-16LE.
22275 **
22276 ** Notes on UTF-8:
22277 **
22278 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
22279 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
22280 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
22281 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
22282 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
22283 **
22284 **
22285 ** Notes on UTF-16:  (with wwww+1==uuuuu)
22286 **
22287 **      Word-0               Word-1          Value
22288 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
22289 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
22290 **
22291 **
22292 ** BOM or Byte Order Mark:
22293 **     0xff 0xfe   little-endian utf-16 follows
22294 **     0xfe 0xff   big-endian utf-16 follows
22295 **
22296 */
22297 /* #include <assert.h> */
22298 
22299 #ifndef SQLITE_AMALGAMATION
22300 /*
22301 ** The following constant value is used by the SQLITE_BIGENDIAN and
22302 ** SQLITE_LITTLEENDIAN macros.
22303 */
22304 SQLITE_PRIVATE const int sqlite3one = 1;
22305 #endif /* SQLITE_AMALGAMATION */
22306 
22307 /*
22308 ** This lookup table is used to help decode the first byte of
22309 ** a multi-byte UTF8 character.
22310 */
22311 static const unsigned char sqlite3Utf8Trans1[] = {
22312   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22313   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
22314   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
22315   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
22316   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22317   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
22318   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22319   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
22320 };
22321 
22322 
22323 #define WRITE_UTF8(zOut, c) {                          \
22324   if( c<0x00080 ){                                     \
22325     *zOut++ = (u8)(c&0xFF);                            \
22326   }                                                    \
22327   else if( c<0x00800 ){                                \
22328     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
22329     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
22330   }                                                    \
22331   else if( c<0x10000 ){                                \
22332     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
22333     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
22334     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
22335   }else{                                               \
22336     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
22337     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
22338     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
22339     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
22340   }                                                    \
22341 }
22342 
22343 #define WRITE_UTF16LE(zOut, c) {                                    \
22344   if( c<=0xFFFF ){                                                  \
22345     *zOut++ = (u8)(c&0x00FF);                                       \
22346     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
22347   }else{                                                            \
22348     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
22349     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
22350     *zOut++ = (u8)(c&0x00FF);                                       \
22351     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
22352   }                                                                 \
22353 }
22354 
22355 #define WRITE_UTF16BE(zOut, c) {                                    \
22356   if( c<=0xFFFF ){                                                  \
22357     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
22358     *zOut++ = (u8)(c&0x00FF);                                       \
22359   }else{                                                            \
22360     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
22361     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
22362     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
22363     *zOut++ = (u8)(c&0x00FF);                                       \
22364   }                                                                 \
22365 }
22366 
22367 #define READ_UTF16LE(zIn, TERM, c){                                   \
22368   c = (*zIn++);                                                       \
22369   c += ((*zIn++)<<8);                                                 \
22370   if( c>=0xD800 && c<0xE000 && TERM ){                                \
22371     int c2 = (*zIn++);                                                \
22372     c2 += ((*zIn++)<<8);                                              \
22373     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
22374   }                                                                   \
22375 }
22376 
22377 #define READ_UTF16BE(zIn, TERM, c){                                   \
22378   c = ((*zIn++)<<8);                                                  \
22379   c += (*zIn++);                                                      \
22380   if( c>=0xD800 && c<0xE000 && TERM ){                                \
22381     int c2 = ((*zIn++)<<8);                                           \
22382     c2 += (*zIn++);                                                   \
22383     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
22384   }                                                                   \
22385 }
22386 
22387 /*
22388 ** Translate a single UTF-8 character.  Return the unicode value.
22389 **
22390 ** During translation, assume that the byte that zTerm points
22391 ** is a 0x00.
22392 **
22393 ** Write a pointer to the next unread byte back into *pzNext.
22394 **
22395 ** Notes On Invalid UTF-8:
22396 **
22397 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
22398 **     be encoded as a multi-byte character.  Any multi-byte character that
22399 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
22400 **
22401 **  *  This routine never allows a UTF16 surrogate value to be encoded.
22402 **     If a multi-byte character attempts to encode a value between
22403 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
22404 **
22405 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
22406 **     byte of a character are interpreted as single-byte characters
22407 **     and rendered as themselves even though they are technically
22408 **     invalid characters.
22409 **
22410 **  *  This routine accepts over-length UTF8 encodings
22411 **     for unicode values 0x80 and greater.  It does not change over-length
22412 **     encodings to 0xfffd as some systems recommend.
22413 */
22414 #define READ_UTF8(zIn, zTerm, c)                           \
22415   c = *(zIn++);                                            \
22416   if( c>=0xc0 ){                                           \
22417     c = sqlite3Utf8Trans1[c-0xc0];                         \
22418     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
22419       c = (c<<6) + (0x3f & *(zIn++));                      \
22420     }                                                      \
22421     if( c<0x80                                             \
22422         || (c&0xFFFFF800)==0xD800                          \
22423         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
22424   }
22425 SQLITE_PRIVATE u32 sqlite3Utf8Read(
22426   const unsigned char **pz    /* Pointer to string from which to read char */
22427 ){
22428   unsigned int c;
22429 
22430   /* Same as READ_UTF8() above but without the zTerm parameter.
22431   ** For this routine, we assume the UTF8 string is always zero-terminated.
22432   */
22433   c = *((*pz)++);
22434   if( c>=0xc0 ){
22435     c = sqlite3Utf8Trans1[c-0xc0];
22436     while( (*(*pz) & 0xc0)==0x80 ){
22437       c = (c<<6) + (0x3f & *((*pz)++));
22438     }
22439     if( c<0x80
22440         || (c&0xFFFFF800)==0xD800
22441         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
22442   }
22443   return c;
22444 }
22445 
22446 
22447 
22448 
22449 /*
22450 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
22451 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
22452 */
22453 /* #define TRANSLATE_TRACE 1 */
22454 
22455 #ifndef SQLITE_OMIT_UTF16
22456 /*
22457 ** This routine transforms the internal text encoding used by pMem to
22458 ** desiredEnc. It is an error if the string is already of the desired
22459 ** encoding, or if *pMem does not contain a string value.
22460 */
22461 SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
22462   int len;                    /* Maximum length of output string in bytes */
22463   unsigned char *zOut;                  /* Output buffer */
22464   unsigned char *zIn;                   /* Input iterator */
22465   unsigned char *zTerm;                 /* End of input */
22466   unsigned char *z;                     /* Output iterator */
22467   unsigned int c;
22468 
22469   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
22470   assert( pMem->flags&MEM_Str );
22471   assert( pMem->enc!=desiredEnc );
22472   assert( pMem->enc!=0 );
22473   assert( pMem->n>=0 );
22474 
22475 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
22476   {
22477     char zBuf[100];
22478     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
22479     fprintf(stderr, "INPUT:  %s\n", zBuf);
22480   }
22481 #endif
22482 
22483   /* If the translation is between UTF-16 little and big endian, then
22484   ** all that is required is to swap the byte order. This case is handled
22485   ** differently from the others.
22486   */
22487   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
22488     u8 temp;
22489     int rc;
22490     rc = sqlite3VdbeMemMakeWriteable(pMem);
22491     if( rc!=SQLITE_OK ){
22492       assert( rc==SQLITE_NOMEM );
22493       return SQLITE_NOMEM;
22494     }
22495     zIn = (u8*)pMem->z;
22496     zTerm = &zIn[pMem->n&~1];
22497     while( zIn<zTerm ){
22498       temp = *zIn;
22499       *zIn = *(zIn+1);
22500       zIn++;
22501       *zIn++ = temp;
22502     }
22503     pMem->enc = desiredEnc;
22504     goto translate_out;
22505   }
22506 
22507   /* Set len to the maximum number of bytes required in the output buffer. */
22508   if( desiredEnc==SQLITE_UTF8 ){
22509     /* When converting from UTF-16, the maximum growth results from
22510     ** translating a 2-byte character to a 4-byte UTF-8 character.
22511     ** A single byte is required for the output string
22512     ** nul-terminator.
22513     */
22514     pMem->n &= ~1;
22515     len = pMem->n * 2 + 1;
22516   }else{
22517     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
22518     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
22519     ** character. Two bytes are required in the output buffer for the
22520     ** nul-terminator.
22521     */
22522     len = pMem->n * 2 + 2;
22523   }
22524 
22525   /* Set zIn to point at the start of the input buffer and zTerm to point 1
22526   ** byte past the end.
22527   **
22528   ** Variable zOut is set to point at the output buffer, space obtained
22529   ** from sqlite3_malloc().
22530   */
22531   zIn = (u8*)pMem->z;
22532   zTerm = &zIn[pMem->n];
22533   zOut = sqlite3DbMallocRaw(pMem->db, len);
22534   if( !zOut ){
22535     return SQLITE_NOMEM;
22536   }
22537   z = zOut;
22538 
22539   if( pMem->enc==SQLITE_UTF8 ){
22540     if( desiredEnc==SQLITE_UTF16LE ){
22541       /* UTF-8 -> UTF-16 Little-endian */
22542       while( zIn<zTerm ){
22543         READ_UTF8(zIn, zTerm, c);
22544         WRITE_UTF16LE(z, c);
22545       }
22546     }else{
22547       assert( desiredEnc==SQLITE_UTF16BE );
22548       /* UTF-8 -> UTF-16 Big-endian */
22549       while( zIn<zTerm ){
22550         READ_UTF8(zIn, zTerm, c);
22551         WRITE_UTF16BE(z, c);
22552       }
22553     }
22554     pMem->n = (int)(z - zOut);
22555     *z++ = 0;
22556   }else{
22557     assert( desiredEnc==SQLITE_UTF8 );
22558     if( pMem->enc==SQLITE_UTF16LE ){
22559       /* UTF-16 Little-endian -> UTF-8 */
22560       while( zIn<zTerm ){
22561         READ_UTF16LE(zIn, zIn<zTerm, c);
22562         WRITE_UTF8(z, c);
22563       }
22564     }else{
22565       /* UTF-16 Big-endian -> UTF-8 */
22566       while( zIn<zTerm ){
22567         READ_UTF16BE(zIn, zIn<zTerm, c);
22568         WRITE_UTF8(z, c);
22569       }
22570     }
22571     pMem->n = (int)(z - zOut);
22572   }
22573   *z = 0;
22574   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
22575 
22576   c = pMem->flags;
22577   sqlite3VdbeMemRelease(pMem);
22578   pMem->flags = MEM_Str|MEM_Term|(c&MEM_AffMask);
22579   pMem->enc = desiredEnc;
22580   pMem->z = (char*)zOut;
22581   pMem->zMalloc = pMem->z;
22582   pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
22583 
22584 translate_out:
22585 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
22586   {
22587     char zBuf[100];
22588     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
22589     fprintf(stderr, "OUTPUT: %s\n", zBuf);
22590   }
22591 #endif
22592   return SQLITE_OK;
22593 }
22594 
22595 /*
22596 ** This routine checks for a byte-order mark at the beginning of the
22597 ** UTF-16 string stored in *pMem. If one is present, it is removed and
22598 ** the encoding of the Mem adjusted. This routine does not do any
22599 ** byte-swapping, it just sets Mem.enc appropriately.
22600 **
22601 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
22602 ** changed by this function.
22603 */
22604 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
22605   int rc = SQLITE_OK;
22606   u8 bom = 0;
22607 
22608   assert( pMem->n>=0 );
22609   if( pMem->n>1 ){
22610     u8 b1 = *(u8 *)pMem->z;
22611     u8 b2 = *(((u8 *)pMem->z) + 1);
22612     if( b1==0xFE && b2==0xFF ){
22613       bom = SQLITE_UTF16BE;
22614     }
22615     if( b1==0xFF && b2==0xFE ){
22616       bom = SQLITE_UTF16LE;
22617     }
22618   }
22619 
22620   if( bom ){
22621     rc = sqlite3VdbeMemMakeWriteable(pMem);
22622     if( rc==SQLITE_OK ){
22623       pMem->n -= 2;
22624       memmove(pMem->z, &pMem->z[2], pMem->n);
22625       pMem->z[pMem->n] = '\0';
22626       pMem->z[pMem->n+1] = '\0';
22627       pMem->flags |= MEM_Term;
22628       pMem->enc = bom;
22629     }
22630   }
22631   return rc;
22632 }
22633 #endif /* SQLITE_OMIT_UTF16 */
22634 
22635 /*
22636 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
22637 ** return the number of unicode characters in pZ up to (but not including)
22638 ** the first 0x00 byte. If nByte is not less than zero, return the
22639 ** number of unicode characters in the first nByte of pZ (or up to
22640 ** the first 0x00, whichever comes first).
22641 */
22642 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
22643   int r = 0;
22644   const u8 *z = (const u8*)zIn;
22645   const u8 *zTerm;
22646   if( nByte>=0 ){
22647     zTerm = &z[nByte];
22648   }else{
22649     zTerm = (const u8*)(-1);
22650   }
22651   assert( z<=zTerm );
22652   while( *z!=0 && z<zTerm ){
22653     SQLITE_SKIP_UTF8(z);
22654     r++;
22655   }
22656   return r;
22657 }
22658 
22659 /* This test function is not currently used by the automated test-suite.
22660 ** Hence it is only available in debug builds.
22661 */
22662 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
22663 /*
22664 ** Translate UTF-8 to UTF-8.
22665 **
22666 ** This has the effect of making sure that the string is well-formed
22667 ** UTF-8.  Miscoded characters are removed.
22668 **
22669 ** The translation is done in-place and aborted if the output
22670 ** overruns the input.
22671 */
22672 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
22673   unsigned char *zOut = zIn;
22674   unsigned char *zStart = zIn;
22675   u32 c;
22676 
22677   while( zIn[0] && zOut<=zIn ){
22678     c = sqlite3Utf8Read((const u8**)&zIn);
22679     if( c!=0xfffd ){
22680       WRITE_UTF8(zOut, c);
22681     }
22682   }
22683   *zOut = 0;
22684   return (int)(zOut - zStart);
22685 }
22686 #endif
22687 
22688 #ifndef SQLITE_OMIT_UTF16
22689 /*
22690 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
22691 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
22692 ** be freed by the calling function.
22693 **
22694 ** NULL is returned if there is an allocation error.
22695 */
22696 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
22697   Mem m;
22698   memset(&m, 0, sizeof(m));
22699   m.db = db;
22700   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
22701   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
22702   if( db->mallocFailed ){
22703     sqlite3VdbeMemRelease(&m);
22704     m.z = 0;
22705   }
22706   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
22707   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
22708   assert( m.z || db->mallocFailed );
22709   return m.z;
22710 }
22711 
22712 /*
22713 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
22714 ** Return the number of bytes in the first nChar unicode characters
22715 ** in pZ.  nChar must be non-negative.
22716 */
22717 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
22718   int c;
22719   unsigned char const *z = zIn;
22720   int n = 0;
22721 
22722   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
22723     while( n<nChar ){
22724       READ_UTF16BE(z, 1, c);
22725       n++;
22726     }
22727   }else{
22728     while( n<nChar ){
22729       READ_UTF16LE(z, 1, c);
22730       n++;
22731     }
22732   }
22733   return (int)(z-(unsigned char const *)zIn);
22734 }
22735 
22736 #if defined(SQLITE_TEST)
22737 /*
22738 ** This routine is called from the TCL test function "translate_selftest".
22739 ** It checks that the primitives for serializing and deserializing
22740 ** characters in each encoding are inverses of each other.
22741 */
22742 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
22743   unsigned int i, t;
22744   unsigned char zBuf[20];
22745   unsigned char *z;
22746   int n;
22747   unsigned int c;
22748 
22749   for(i=0; i<0x00110000; i++){
22750     z = zBuf;
22751     WRITE_UTF8(z, i);
22752     n = (int)(z-zBuf);
22753     assert( n>0 && n<=4 );
22754     z[0] = 0;
22755     z = zBuf;
22756     c = sqlite3Utf8Read((const u8**)&z);
22757     t = i;
22758     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
22759     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
22760     assert( c==t );
22761     assert( (z-zBuf)==n );
22762   }
22763   for(i=0; i<0x00110000; i++){
22764     if( i>=0xD800 && i<0xE000 ) continue;
22765     z = zBuf;
22766     WRITE_UTF16LE(z, i);
22767     n = (int)(z-zBuf);
22768     assert( n>0 && n<=4 );
22769     z[0] = 0;
22770     z = zBuf;
22771     READ_UTF16LE(z, 1, c);
22772     assert( c==i );
22773     assert( (z-zBuf)==n );
22774   }
22775   for(i=0; i<0x00110000; i++){
22776     if( i>=0xD800 && i<0xE000 ) continue;
22777     z = zBuf;
22778     WRITE_UTF16BE(z, i);
22779     n = (int)(z-zBuf);
22780     assert( n>0 && n<=4 );
22781     z[0] = 0;
22782     z = zBuf;
22783     READ_UTF16BE(z, 1, c);
22784     assert( c==i );
22785     assert( (z-zBuf)==n );
22786   }
22787 }
22788 #endif /* SQLITE_TEST */
22789 #endif /* SQLITE_OMIT_UTF16 */
22790 
22791 /************** End of utf.c *************************************************/
22792 /************** Begin file util.c ********************************************/
22793 /*
22794 ** 2001 September 15
22795 **
22796 ** The author disclaims copyright to this source code.  In place of
22797 ** a legal notice, here is a blessing:
22798 **
22799 **    May you do good and not evil.
22800 **    May you find forgiveness for yourself and forgive others.
22801 **    May you share freely, never taking more than you give.
22802 **
22803 *************************************************************************
22804 ** Utility functions used throughout sqlite.
22805 **
22806 ** This file contains functions for allocating memory, comparing
22807 ** strings, and stuff like that.
22808 **
22809 */
22810 /* #include <stdarg.h> */
22811 #ifdef SQLITE_HAVE_ISNAN
22812 # include <math.h>
22813 #endif
22814 
22815 /*
22816 ** Routine needed to support the testcase() macro.
22817 */
22818 #ifdef SQLITE_COVERAGE_TEST
22819 SQLITE_PRIVATE void sqlite3Coverage(int x){
22820   static unsigned dummy = 0;
22821   dummy += (unsigned)x;
22822 }
22823 #endif
22824 
22825 /*
22826 ** Give a callback to the test harness that can be used to simulate faults
22827 ** in places where it is difficult or expensive to do so purely by means
22828 ** of inputs.
22829 **
22830 ** The intent of the integer argument is to let the fault simulator know
22831 ** which of multiple sqlite3FaultSim() calls has been hit.
22832 **
22833 ** Return whatever integer value the test callback returns, or return
22834 ** SQLITE_OK if no test callback is installed.
22835 */
22836 #ifndef SQLITE_OMIT_BUILTIN_TEST
22837 SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
22838   int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
22839   return xCallback ? xCallback(iTest) : SQLITE_OK;
22840 }
22841 #endif
22842 
22843 #ifndef SQLITE_OMIT_FLOATING_POINT
22844 /*
22845 ** Return true if the floating point value is Not a Number (NaN).
22846 **
22847 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
22848 ** Otherwise, we have our own implementation that works on most systems.
22849 */
22850 SQLITE_PRIVATE int sqlite3IsNaN(double x){
22851   int rc;   /* The value return */
22852 #if !defined(SQLITE_HAVE_ISNAN)
22853   /*
22854   ** Systems that support the isnan() library function should probably
22855   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
22856   ** found that many systems do not have a working isnan() function so
22857   ** this implementation is provided as an alternative.
22858   **
22859   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
22860   ** On the other hand, the use of -ffast-math comes with the following
22861   ** warning:
22862   **
22863   **      This option [-ffast-math] should never be turned on by any
22864   **      -O option since it can result in incorrect output for programs
22865   **      which depend on an exact implementation of IEEE or ISO
22866   **      rules/specifications for math functions.
22867   **
22868   ** Under MSVC, this NaN test may fail if compiled with a floating-
22869   ** point precision mode other than /fp:precise.  From the MSDN
22870   ** documentation:
22871   **
22872   **      The compiler [with /fp:precise] will properly handle comparisons
22873   **      involving NaN. For example, x != x evaluates to true if x is NaN
22874   **      ...
22875   */
22876 #ifdef __FAST_MATH__
22877 # error SQLite will not work correctly with the -ffast-math option of GCC.
22878 #endif
22879   volatile double y = x;
22880   volatile double z = y;
22881   rc = (y!=z);
22882 #else  /* if defined(SQLITE_HAVE_ISNAN) */
22883   rc = isnan(x);
22884 #endif /* SQLITE_HAVE_ISNAN */
22885   testcase( rc );
22886   return rc;
22887 }
22888 #endif /* SQLITE_OMIT_FLOATING_POINT */
22889 
22890 /*
22891 ** Compute a string length that is limited to what can be stored in
22892 ** lower 30 bits of a 32-bit signed integer.
22893 **
22894 ** The value returned will never be negative.  Nor will it ever be greater
22895 ** than the actual length of the string.  For very long strings (greater
22896 ** than 1GiB) the value returned might be less than the true string length.
22897 */
22898 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
22899   const char *z2 = z;
22900   if( z==0 ) return 0;
22901   while( *z2 ){ z2++; }
22902   return 0x3fffffff & (int)(z2 - z);
22903 }
22904 
22905 /*
22906 ** Set the current error code to err_code and clear any prior error message.
22907 */
22908 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
22909   assert( db!=0 );
22910   db->errCode = err_code;
22911   if( db->pErr ) sqlite3ValueSetNull(db->pErr);
22912 }
22913 
22914 /*
22915 ** Set the most recent error code and error string for the sqlite
22916 ** handle "db". The error code is set to "err_code".
22917 **
22918 ** If it is not NULL, string zFormat specifies the format of the
22919 ** error string in the style of the printf functions: The following
22920 ** format characters are allowed:
22921 **
22922 **      %s      Insert a string
22923 **      %z      A string that should be freed after use
22924 **      %d      Insert an integer
22925 **      %T      Insert a token
22926 **      %S      Insert the first element of a SrcList
22927 **
22928 ** zFormat and any string tokens that follow it are assumed to be
22929 ** encoded in UTF-8.
22930 **
22931 ** To clear the most recent error for sqlite handle "db", sqlite3Error
22932 ** should be called with err_code set to SQLITE_OK and zFormat set
22933 ** to NULL.
22934 */
22935 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
22936   assert( db!=0 );
22937   db->errCode = err_code;
22938   if( zFormat==0 ){
22939     sqlite3Error(db, err_code);
22940   }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
22941     char *z;
22942     va_list ap;
22943     va_start(ap, zFormat);
22944     z = sqlite3VMPrintf(db, zFormat, ap);
22945     va_end(ap);
22946     sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
22947   }
22948 }
22949 
22950 /*
22951 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
22952 ** The following formatting characters are allowed:
22953 **
22954 **      %s      Insert a string
22955 **      %z      A string that should be freed after use
22956 **      %d      Insert an integer
22957 **      %T      Insert a token
22958 **      %S      Insert the first element of a SrcList
22959 **
22960 ** This function should be used to report any error that occurs while
22961 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
22962 ** last thing the sqlite3_prepare() function does is copy the error
22963 ** stored by this function into the database handle using sqlite3Error().
22964 ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
22965 ** during statement execution (sqlite3_step() etc.).
22966 */
22967 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
22968   char *zMsg;
22969   va_list ap;
22970   sqlite3 *db = pParse->db;
22971   va_start(ap, zFormat);
22972   zMsg = sqlite3VMPrintf(db, zFormat, ap);
22973   va_end(ap);
22974   if( db->suppressErr ){
22975     sqlite3DbFree(db, zMsg);
22976   }else{
22977     pParse->nErr++;
22978     sqlite3DbFree(db, pParse->zErrMsg);
22979     pParse->zErrMsg = zMsg;
22980     pParse->rc = SQLITE_ERROR;
22981   }
22982 }
22983 
22984 /*
22985 ** Convert an SQL-style quoted string into a normal string by removing
22986 ** the quote characters.  The conversion is done in-place.  If the
22987 ** input does not begin with a quote character, then this routine
22988 ** is a no-op.
22989 **
22990 ** The input string must be zero-terminated.  A new zero-terminator
22991 ** is added to the dequoted string.
22992 **
22993 ** The return value is -1 if no dequoting occurs or the length of the
22994 ** dequoted string, exclusive of the zero terminator, if dequoting does
22995 ** occur.
22996 **
22997 ** 2002-Feb-14: This routine is extended to remove MS-Access style
22998 ** brackets from around identifiers.  For example:  "[a-b-c]" becomes
22999 ** "a-b-c".
23000 */
23001 SQLITE_PRIVATE int sqlite3Dequote(char *z){
23002   char quote;
23003   int i, j;
23004   if( z==0 ) return -1;
23005   quote = z[0];
23006   switch( quote ){
23007     case '\'':  break;
23008     case '"':   break;
23009     case '`':   break;                /* For MySQL compatibility */
23010     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
23011     default:    return -1;
23012   }
23013   for(i=1, j=0;; i++){
23014     assert( z[i] );
23015     if( z[i]==quote ){
23016       if( z[i+1]==quote ){
23017         z[j++] = quote;
23018         i++;
23019       }else{
23020         break;
23021       }
23022     }else{
23023       z[j++] = z[i];
23024     }
23025   }
23026   z[j] = 0;
23027   return j;
23028 }
23029 
23030 /* Convenient short-hand */
23031 #define UpperToLower sqlite3UpperToLower
23032 
23033 /*
23034 ** Some systems have stricmp().  Others have strcasecmp().  Because
23035 ** there is no consistency, we will define our own.
23036 **
23037 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
23038 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
23039 ** the contents of two buffers containing UTF-8 strings in a
23040 ** case-independent fashion, using the same definition of "case
23041 ** independence" that SQLite uses internally when comparing identifiers.
23042 */
23043 SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
23044   register unsigned char *a, *b;
23045   a = (unsigned char *)zLeft;
23046   b = (unsigned char *)zRight;
23047   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
23048   return UpperToLower[*a] - UpperToLower[*b];
23049 }
23050 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
23051   register unsigned char *a, *b;
23052   a = (unsigned char *)zLeft;
23053   b = (unsigned char *)zRight;
23054   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
23055   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
23056 }
23057 
23058 /*
23059 ** The string z[] is an text representation of a real number.
23060 ** Convert this string to a double and write it into *pResult.
23061 **
23062 ** The string z[] is length bytes in length (bytes, not characters) and
23063 ** uses the encoding enc.  The string is not necessarily zero-terminated.
23064 **
23065 ** Return TRUE if the result is a valid real number (or integer) and FALSE
23066 ** if the string is empty or contains extraneous text.  Valid numbers
23067 ** are in one of these formats:
23068 **
23069 **    [+-]digits[E[+-]digits]
23070 **    [+-]digits.[digits][E[+-]digits]
23071 **    [+-].digits[E[+-]digits]
23072 **
23073 ** Leading and trailing whitespace is ignored for the purpose of determining
23074 ** validity.
23075 **
23076 ** If some prefix of the input string is a valid number, this routine
23077 ** returns FALSE but it still converts the prefix and writes the result
23078 ** into *pResult.
23079 */
23080 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
23081 #ifndef SQLITE_OMIT_FLOATING_POINT
23082   int incr;
23083   const char *zEnd = z + length;
23084   /* sign * significand * (10 ^ (esign * exponent)) */
23085   int sign = 1;    /* sign of significand */
23086   i64 s = 0;       /* significand */
23087   int d = 0;       /* adjust exponent for shifting decimal point */
23088   int esign = 1;   /* sign of exponent */
23089   int e = 0;       /* exponent */
23090   int eValid = 1;  /* True exponent is either not used or is well-formed */
23091   double result;
23092   int nDigits = 0;
23093   int nonNum = 0;
23094 
23095   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
23096   *pResult = 0.0;   /* Default return value, in case of an error */
23097 
23098   if( enc==SQLITE_UTF8 ){
23099     incr = 1;
23100   }else{
23101     int i;
23102     incr = 2;
23103     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
23104     for(i=3-enc; i<length && z[i]==0; i+=2){}
23105     nonNum = i<length;
23106     zEnd = z+i+enc-3;
23107     z += (enc&1);
23108   }
23109 
23110   /* skip leading spaces */
23111   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
23112   if( z>=zEnd ) return 0;
23113 
23114   /* get sign of significand */
23115   if( *z=='-' ){
23116     sign = -1;
23117     z+=incr;
23118   }else if( *z=='+' ){
23119     z+=incr;
23120   }
23121 
23122   /* skip leading zeroes */
23123   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
23124 
23125   /* copy max significant digits to significand */
23126   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
23127     s = s*10 + (*z - '0');
23128     z+=incr, nDigits++;
23129   }
23130 
23131   /* skip non-significant significand digits
23132   ** (increase exponent by d to shift decimal left) */
23133   while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
23134   if( z>=zEnd ) goto do_atof_calc;
23135 
23136   /* if decimal point is present */
23137   if( *z=='.' ){
23138     z+=incr;
23139     /* copy digits from after decimal to significand
23140     ** (decrease exponent by d to shift decimal right) */
23141     while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
23142       s = s*10 + (*z - '0');
23143       z+=incr, nDigits++, d--;
23144     }
23145     /* skip non-significant digits */
23146     while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
23147   }
23148   if( z>=zEnd ) goto do_atof_calc;
23149 
23150   /* if exponent is present */
23151   if( *z=='e' || *z=='E' ){
23152     z+=incr;
23153     eValid = 0;
23154     if( z>=zEnd ) goto do_atof_calc;
23155     /* get sign of exponent */
23156     if( *z=='-' ){
23157       esign = -1;
23158       z+=incr;
23159     }else if( *z=='+' ){
23160       z+=incr;
23161     }
23162     /* copy digits to exponent */
23163     while( z<zEnd && sqlite3Isdigit(*z) ){
23164       e = e<10000 ? (e*10 + (*z - '0')) : 10000;
23165       z+=incr;
23166       eValid = 1;
23167     }
23168   }
23169 
23170   /* skip trailing spaces */
23171   if( nDigits && eValid ){
23172     while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
23173   }
23174 
23175 do_atof_calc:
23176   /* adjust exponent by d, and update sign */
23177   e = (e*esign) + d;
23178   if( e<0 ) {
23179     esign = -1;
23180     e *= -1;
23181   } else {
23182     esign = 1;
23183   }
23184 
23185   /* if 0 significand */
23186   if( !s ) {
23187     /* In the IEEE 754 standard, zero is signed.
23188     ** Add the sign if we've seen at least one digit */
23189     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
23190   } else {
23191     /* attempt to reduce exponent */
23192     if( esign>0 ){
23193       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
23194     }else{
23195       while( !(s%10) && e>0 ) e--,s/=10;
23196     }
23197 
23198     /* adjust the sign of significand */
23199     s = sign<0 ? -s : s;
23200 
23201     /* if exponent, scale significand as appropriate
23202     ** and store in result. */
23203     if( e ){
23204       LONGDOUBLE_TYPE scale = 1.0;
23205       /* attempt to handle extremely small/large numbers better */
23206       if( e>307 && e<342 ){
23207         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
23208         if( esign<0 ){
23209           result = s / scale;
23210           result /= 1.0e+308;
23211         }else{
23212           result = s * scale;
23213           result *= 1.0e+308;
23214         }
23215       }else if( e>=342 ){
23216         if( esign<0 ){
23217           result = 0.0*s;
23218         }else{
23219           result = 1e308*1e308*s;  /* Infinity */
23220         }
23221       }else{
23222         /* 1.0e+22 is the largest power of 10 than can be
23223         ** represented exactly. */
23224         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
23225         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
23226         if( esign<0 ){
23227           result = s / scale;
23228         }else{
23229           result = s * scale;
23230         }
23231       }
23232     } else {
23233       result = (double)s;
23234     }
23235   }
23236 
23237   /* store the result */
23238   *pResult = result;
23239 
23240   /* return true if number and no extra non-whitespace chracters after */
23241   return z>=zEnd && nDigits>0 && eValid && nonNum==0;
23242 #else
23243   return !sqlite3Atoi64(z, pResult, length, enc);
23244 #endif /* SQLITE_OMIT_FLOATING_POINT */
23245 }
23246 
23247 /*
23248 ** Compare the 19-character string zNum against the text representation
23249 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
23250 ** if zNum is less than, equal to, or greater than the string.
23251 ** Note that zNum must contain exactly 19 characters.
23252 **
23253 ** Unlike memcmp() this routine is guaranteed to return the difference
23254 ** in the values of the last digit if the only difference is in the
23255 ** last digit.  So, for example,
23256 **
23257 **      compare2pow63("9223372036854775800", 1)
23258 **
23259 ** will return -8.
23260 */
23261 static int compare2pow63(const char *zNum, int incr){
23262   int c = 0;
23263   int i;
23264                     /* 012345678901234567 */
23265   const char *pow63 = "922337203685477580";
23266   for(i=0; c==0 && i<18; i++){
23267     c = (zNum[i*incr]-pow63[i])*10;
23268   }
23269   if( c==0 ){
23270     c = zNum[18*incr] - '8';
23271     testcase( c==(-1) );
23272     testcase( c==0 );
23273     testcase( c==(+1) );
23274   }
23275   return c;
23276 }
23277 
23278 /*
23279 ** Convert zNum to a 64-bit signed integer.  zNum must be decimal. This
23280 ** routine does *not* accept hexadecimal notation.
23281 **
23282 ** If the zNum value is representable as a 64-bit twos-complement
23283 ** integer, then write that value into *pNum and return 0.
23284 **
23285 ** If zNum is exactly 9223372036854775808, return 2.  This special
23286 ** case is broken out because while 9223372036854775808 cannot be a
23287 ** signed 64-bit integer, its negative -9223372036854775808 can be.
23288 **
23289 ** If zNum is too big for a 64-bit integer and is not
23290 ** 9223372036854775808  or if zNum contains any non-numeric text,
23291 ** then return 1.
23292 **
23293 ** length is the number of bytes in the string (bytes, not characters).
23294 ** The string is not necessarily zero-terminated.  The encoding is
23295 ** given by enc.
23296 */
23297 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
23298   int incr;
23299   u64 u = 0;
23300   int neg = 0; /* assume positive */
23301   int i;
23302   int c = 0;
23303   int nonNum = 0;
23304   const char *zStart;
23305   const char *zEnd = zNum + length;
23306   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
23307   if( enc==SQLITE_UTF8 ){
23308     incr = 1;
23309   }else{
23310     incr = 2;
23311     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
23312     for(i=3-enc; i<length && zNum[i]==0; i+=2){}
23313     nonNum = i<length;
23314     zEnd = zNum+i+enc-3;
23315     zNum += (enc&1);
23316   }
23317   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
23318   if( zNum<zEnd ){
23319     if( *zNum=='-' ){
23320       neg = 1;
23321       zNum+=incr;
23322     }else if( *zNum=='+' ){
23323       zNum+=incr;
23324     }
23325   }
23326   zStart = zNum;
23327   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
23328   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
23329     u = u*10 + c - '0';
23330   }
23331   if( u>LARGEST_INT64 ){
23332     *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
23333   }else if( neg ){
23334     *pNum = -(i64)u;
23335   }else{
23336     *pNum = (i64)u;
23337   }
23338   testcase( i==18 );
23339   testcase( i==19 );
23340   testcase( i==20 );
23341   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
23342     /* zNum is empty or contains non-numeric text or is longer
23343     ** than 19 digits (thus guaranteeing that it is too large) */
23344     return 1;
23345   }else if( i<19*incr ){
23346     /* Less than 19 digits, so we know that it fits in 64 bits */
23347     assert( u<=LARGEST_INT64 );
23348     return 0;
23349   }else{
23350     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
23351     c = compare2pow63(zNum, incr);
23352     if( c<0 ){
23353       /* zNum is less than 9223372036854775808 so it fits */
23354       assert( u<=LARGEST_INT64 );
23355       return 0;
23356     }else if( c>0 ){
23357       /* zNum is greater than 9223372036854775808 so it overflows */
23358       return 1;
23359     }else{
23360       /* zNum is exactly 9223372036854775808.  Fits if negative.  The
23361       ** special case 2 overflow if positive */
23362       assert( u-1==LARGEST_INT64 );
23363       return neg ? 0 : 2;
23364     }
23365   }
23366 }
23367 
23368 /*
23369 ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
23370 ** into a 64-bit signed integer.  This routine accepts hexadecimal literals,
23371 ** whereas sqlite3Atoi64() does not.
23372 **
23373 ** Returns:
23374 **
23375 **     0    Successful transformation.  Fits in a 64-bit signed integer.
23376 **     1    Integer too large for a 64-bit signed integer or is malformed
23377 **     2    Special case of 9223372036854775808
23378 */
23379 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
23380 #ifndef SQLITE_OMIT_HEX_INTEGER
23381   if( z[0]=='0'
23382    && (z[1]=='x' || z[1]=='X')
23383    && sqlite3Isxdigit(z[2])
23384   ){
23385     u64 u = 0;
23386     int i, k;
23387     for(i=2; z[i]=='0'; i++){}
23388     for(k=i; sqlite3Isxdigit(z[k]); k++){
23389       u = u*16 + sqlite3HexToInt(z[k]);
23390     }
23391     memcpy(pOut, &u, 8);
23392     return (z[k]==0 && k-i<=16) ? 0 : 1;
23393   }else
23394 #endif /* SQLITE_OMIT_HEX_INTEGER */
23395   {
23396     return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
23397   }
23398 }
23399 
23400 /*
23401 ** If zNum represents an integer that will fit in 32-bits, then set
23402 ** *pValue to that integer and return true.  Otherwise return false.
23403 **
23404 ** This routine accepts both decimal and hexadecimal notation for integers.
23405 **
23406 ** Any non-numeric characters that following zNum are ignored.
23407 ** This is different from sqlite3Atoi64() which requires the
23408 ** input number to be zero-terminated.
23409 */
23410 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
23411   sqlite_int64 v = 0;
23412   int i, c;
23413   int neg = 0;
23414   if( zNum[0]=='-' ){
23415     neg = 1;
23416     zNum++;
23417   }else if( zNum[0]=='+' ){
23418     zNum++;
23419   }
23420 #ifndef SQLITE_OMIT_HEX_INTEGER
23421   else if( zNum[0]=='0'
23422         && (zNum[1]=='x' || zNum[1]=='X')
23423         && sqlite3Isxdigit(zNum[2])
23424   ){
23425     u32 u = 0;
23426     zNum += 2;
23427     while( zNum[0]=='0' ) zNum++;
23428     for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
23429       u = u*16 + sqlite3HexToInt(zNum[i]);
23430     }
23431     if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
23432       memcpy(pValue, &u, 4);
23433       return 1;
23434     }else{
23435       return 0;
23436     }
23437   }
23438 #endif
23439   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
23440     v = v*10 + c;
23441   }
23442 
23443   /* The longest decimal representation of a 32 bit integer is 10 digits:
23444   **
23445   **             1234567890
23446   **     2^31 -> 2147483648
23447   */
23448   testcase( i==10 );
23449   if( i>10 ){
23450     return 0;
23451   }
23452   testcase( v-neg==2147483647 );
23453   if( v-neg>2147483647 ){
23454     return 0;
23455   }
23456   if( neg ){
23457     v = -v;
23458   }
23459   *pValue = (int)v;
23460   return 1;
23461 }
23462 
23463 /*
23464 ** Return a 32-bit integer value extracted from a string.  If the
23465 ** string is not an integer, just return 0.
23466 */
23467 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
23468   int x = 0;
23469   if( z ) sqlite3GetInt32(z, &x);
23470   return x;
23471 }
23472 
23473 /*
23474 ** The variable-length integer encoding is as follows:
23475 **
23476 ** KEY:
23477 **         A = 0xxxxxxx    7 bits of data and one flag bit
23478 **         B = 1xxxxxxx    7 bits of data and one flag bit
23479 **         C = xxxxxxxx    8 bits of data
23480 **
23481 **  7 bits - A
23482 ** 14 bits - BA
23483 ** 21 bits - BBA
23484 ** 28 bits - BBBA
23485 ** 35 bits - BBBBA
23486 ** 42 bits - BBBBBA
23487 ** 49 bits - BBBBBBA
23488 ** 56 bits - BBBBBBBA
23489 ** 64 bits - BBBBBBBBC
23490 */
23491 
23492 /*
23493 ** Write a 64-bit variable-length integer to memory starting at p[0].
23494 ** The length of data write will be between 1 and 9 bytes.  The number
23495 ** of bytes written is returned.
23496 **
23497 ** A variable-length integer consists of the lower 7 bits of each byte
23498 ** for all bytes that have the 8th bit set and one byte with the 8th
23499 ** bit clear.  Except, if we get to the 9th byte, it stores the full
23500 ** 8 bits and is the last byte.
23501 */
23502 static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
23503   int i, j, n;
23504   u8 buf[10];
23505   if( v & (((u64)0xff000000)<<32) ){
23506     p[8] = (u8)v;
23507     v >>= 8;
23508     for(i=7; i>=0; i--){
23509       p[i] = (u8)((v & 0x7f) | 0x80);
23510       v >>= 7;
23511     }
23512     return 9;
23513   }
23514   n = 0;
23515   do{
23516     buf[n++] = (u8)((v & 0x7f) | 0x80);
23517     v >>= 7;
23518   }while( v!=0 );
23519   buf[0] &= 0x7f;
23520   assert( n<=9 );
23521   for(i=0, j=n-1; j>=0; j--, i++){
23522     p[i] = buf[j];
23523   }
23524   return n;
23525 }
23526 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
23527   if( v<=0x7f ){
23528     p[0] = v&0x7f;
23529     return 1;
23530   }
23531   if( v<=0x3fff ){
23532     p[0] = ((v>>7)&0x7f)|0x80;
23533     p[1] = v&0x7f;
23534     return 2;
23535   }
23536   return putVarint64(p,v);
23537 }
23538 
23539 /*
23540 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
23541 ** are defined here rather than simply putting the constant expressions
23542 ** inline in order to work around bugs in the RVT compiler.
23543 **
23544 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
23545 **
23546 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
23547 */
23548 #define SLOT_2_0     0x001fc07f
23549 #define SLOT_4_2_0   0xf01fc07f
23550 
23551 
23552 /*
23553 ** Read a 64-bit variable-length integer from memory starting at p[0].
23554 ** Return the number of bytes read.  The value is stored in *v.
23555 */
23556 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
23557   u32 a,b,s;
23558 
23559   a = *p;
23560   /* a: p0 (unmasked) */
23561   if (!(a&0x80))
23562   {
23563     *v = a;
23564     return 1;
23565   }
23566 
23567   p++;
23568   b = *p;
23569   /* b: p1 (unmasked) */
23570   if (!(b&0x80))
23571   {
23572     a &= 0x7f;
23573     a = a<<7;
23574     a |= b;
23575     *v = a;
23576     return 2;
23577   }
23578 
23579   /* Verify that constants are precomputed correctly */
23580   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
23581   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
23582 
23583   p++;
23584   a = a<<14;
23585   a |= *p;
23586   /* a: p0<<14 | p2 (unmasked) */
23587   if (!(a&0x80))
23588   {
23589     a &= SLOT_2_0;
23590     b &= 0x7f;
23591     b = b<<7;
23592     a |= b;
23593     *v = a;
23594     return 3;
23595   }
23596 
23597   /* CSE1 from below */
23598   a &= SLOT_2_0;
23599   p++;
23600   b = b<<14;
23601   b |= *p;
23602   /* b: p1<<14 | p3 (unmasked) */
23603   if (!(b&0x80))
23604   {
23605     b &= SLOT_2_0;
23606     /* moved CSE1 up */
23607     /* a &= (0x7f<<14)|(0x7f); */
23608     a = a<<7;
23609     a |= b;
23610     *v = a;
23611     return 4;
23612   }
23613 
23614   /* a: p0<<14 | p2 (masked) */
23615   /* b: p1<<14 | p3 (unmasked) */
23616   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
23617   /* moved CSE1 up */
23618   /* a &= (0x7f<<14)|(0x7f); */
23619   b &= SLOT_2_0;
23620   s = a;
23621   /* s: p0<<14 | p2 (masked) */
23622 
23623   p++;
23624   a = a<<14;
23625   a |= *p;
23626   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
23627   if (!(a&0x80))
23628   {
23629     /* we can skip these cause they were (effectively) done above in calc'ing s */
23630     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
23631     /* b &= (0x7f<<14)|(0x7f); */
23632     b = b<<7;
23633     a |= b;
23634     s = s>>18;
23635     *v = ((u64)s)<<32 | a;
23636     return 5;
23637   }
23638 
23639   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
23640   s = s<<7;
23641   s |= b;
23642   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
23643 
23644   p++;
23645   b = b<<14;
23646   b |= *p;
23647   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
23648   if (!(b&0x80))
23649   {
23650     /* we can skip this cause it was (effectively) done above in calc'ing s */
23651     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
23652     a &= SLOT_2_0;
23653     a = a<<7;
23654     a |= b;
23655     s = s>>18;
23656     *v = ((u64)s)<<32 | a;
23657     return 6;
23658   }
23659 
23660   p++;
23661   a = a<<14;
23662   a |= *p;
23663   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
23664   if (!(a&0x80))
23665   {
23666     a &= SLOT_4_2_0;
23667     b &= SLOT_2_0;
23668     b = b<<7;
23669     a |= b;
23670     s = s>>11;
23671     *v = ((u64)s)<<32 | a;
23672     return 7;
23673   }
23674 
23675   /* CSE2 from below */
23676   a &= SLOT_2_0;
23677   p++;
23678   b = b<<14;
23679   b |= *p;
23680   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
23681   if (!(b&0x80))
23682   {
23683     b &= SLOT_4_2_0;
23684     /* moved CSE2 up */
23685     /* a &= (0x7f<<14)|(0x7f); */
23686     a = a<<7;
23687     a |= b;
23688     s = s>>4;
23689     *v = ((u64)s)<<32 | a;
23690     return 8;
23691   }
23692 
23693   p++;
23694   a = a<<15;
23695   a |= *p;
23696   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
23697 
23698   /* moved CSE2 up */
23699   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
23700   b &= SLOT_2_0;
23701   b = b<<8;
23702   a |= b;
23703 
23704   s = s<<4;
23705   b = p[-4];
23706   b &= 0x7f;
23707   b = b>>3;
23708   s |= b;
23709 
23710   *v = ((u64)s)<<32 | a;
23711 
23712   return 9;
23713 }
23714 
23715 /*
23716 ** Read a 32-bit variable-length integer from memory starting at p[0].
23717 ** Return the number of bytes read.  The value is stored in *v.
23718 **
23719 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
23720 ** integer, then set *v to 0xffffffff.
23721 **
23722 ** A MACRO version, getVarint32, is provided which inlines the
23723 ** single-byte case.  All code should use the MACRO version as
23724 ** this function assumes the single-byte case has already been handled.
23725 */
23726 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
23727   u32 a,b;
23728 
23729   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
23730   ** by the getVarin32() macro */
23731   a = *p;
23732   /* a: p0 (unmasked) */
23733 #ifndef getVarint32
23734   if (!(a&0x80))
23735   {
23736     /* Values between 0 and 127 */
23737     *v = a;
23738     return 1;
23739   }
23740 #endif
23741 
23742   /* The 2-byte case */
23743   p++;
23744   b = *p;
23745   /* b: p1 (unmasked) */
23746   if (!(b&0x80))
23747   {
23748     /* Values between 128 and 16383 */
23749     a &= 0x7f;
23750     a = a<<7;
23751     *v = a | b;
23752     return 2;
23753   }
23754 
23755   /* The 3-byte case */
23756   p++;
23757   a = a<<14;
23758   a |= *p;
23759   /* a: p0<<14 | p2 (unmasked) */
23760   if (!(a&0x80))
23761   {
23762     /* Values between 16384 and 2097151 */
23763     a &= (0x7f<<14)|(0x7f);
23764     b &= 0x7f;
23765     b = b<<7;
23766     *v = a | b;
23767     return 3;
23768   }
23769 
23770   /* A 32-bit varint is used to store size information in btrees.
23771   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
23772   ** A 3-byte varint is sufficient, for example, to record the size
23773   ** of a 1048569-byte BLOB or string.
23774   **
23775   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
23776   ** rare larger cases can be handled by the slower 64-bit varint
23777   ** routine.
23778   */
23779 #if 1
23780   {
23781     u64 v64;
23782     u8 n;
23783 
23784     p -= 2;
23785     n = sqlite3GetVarint(p, &v64);
23786     assert( n>3 && n<=9 );
23787     if( (v64 & SQLITE_MAX_U32)!=v64 ){
23788       *v = 0xffffffff;
23789     }else{
23790       *v = (u32)v64;
23791     }
23792     return n;
23793   }
23794 
23795 #else
23796   /* For following code (kept for historical record only) shows an
23797   ** unrolling for the 3- and 4-byte varint cases.  This code is
23798   ** slightly faster, but it is also larger and much harder to test.
23799   */
23800   p++;
23801   b = b<<14;
23802   b |= *p;
23803   /* b: p1<<14 | p3 (unmasked) */
23804   if (!(b&0x80))
23805   {
23806     /* Values between 2097152 and 268435455 */
23807     b &= (0x7f<<14)|(0x7f);
23808     a &= (0x7f<<14)|(0x7f);
23809     a = a<<7;
23810     *v = a | b;
23811     return 4;
23812   }
23813 
23814   p++;
23815   a = a<<14;
23816   a |= *p;
23817   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
23818   if (!(a&0x80))
23819   {
23820     /* Values  between 268435456 and 34359738367 */
23821     a &= SLOT_4_2_0;
23822     b &= SLOT_4_2_0;
23823     b = b<<7;
23824     *v = a | b;
23825     return 5;
23826   }
23827 
23828   /* We can only reach this point when reading a corrupt database
23829   ** file.  In that case we are not in any hurry.  Use the (relatively
23830   ** slow) general-purpose sqlite3GetVarint() routine to extract the
23831   ** value. */
23832   {
23833     u64 v64;
23834     u8 n;
23835 
23836     p -= 4;
23837     n = sqlite3GetVarint(p, &v64);
23838     assert( n>5 && n<=9 );
23839     *v = (u32)v64;
23840     return n;
23841   }
23842 #endif
23843 }
23844 
23845 /*
23846 ** Return the number of bytes that will be needed to store the given
23847 ** 64-bit integer.
23848 */
23849 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
23850   int i = 0;
23851   do{
23852     i++;
23853     v >>= 7;
23854   }while( v!=0 && ALWAYS(i<9) );
23855   return i;
23856 }
23857 
23858 
23859 /*
23860 ** Read or write a four-byte big-endian integer value.
23861 */
23862 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
23863   testcase( p[0]&0x80 );
23864   return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
23865 }
23866 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
23867   p[0] = (u8)(v>>24);
23868   p[1] = (u8)(v>>16);
23869   p[2] = (u8)(v>>8);
23870   p[3] = (u8)v;
23871 }
23872 
23873 
23874 
23875 /*
23876 ** Translate a single byte of Hex into an integer.
23877 ** This routine only works if h really is a valid hexadecimal
23878 ** character:  0..9a..fA..F
23879 */
23880 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
23881   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
23882 #ifdef SQLITE_ASCII
23883   h += 9*(1&(h>>6));
23884 #endif
23885 #ifdef SQLITE_EBCDIC
23886   h += 9*(1&~(h>>4));
23887 #endif
23888   return (u8)(h & 0xf);
23889 }
23890 
23891 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
23892 /*
23893 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
23894 ** value.  Return a pointer to its binary value.  Space to hold the
23895 ** binary value has been obtained from malloc and must be freed by
23896 ** the calling routine.
23897 */
23898 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
23899   char *zBlob;
23900   int i;
23901 
23902   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
23903   n--;
23904   if( zBlob ){
23905     for(i=0; i<n; i+=2){
23906       zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
23907     }
23908     zBlob[i/2] = 0;
23909   }
23910   return zBlob;
23911 }
23912 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
23913 
23914 /*
23915 ** Log an error that is an API call on a connection pointer that should
23916 ** not have been used.  The "type" of connection pointer is given as the
23917 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
23918 */
23919 static void logBadConnection(const char *zType){
23920   sqlite3_log(SQLITE_MISUSE,
23921      "API call with %s database connection pointer",
23922      zType
23923   );
23924 }
23925 
23926 /*
23927 ** Check to make sure we have a valid db pointer.  This test is not
23928 ** foolproof but it does provide some measure of protection against
23929 ** misuse of the interface such as passing in db pointers that are
23930 ** NULL or which have been previously closed.  If this routine returns
23931 ** 1 it means that the db pointer is valid and 0 if it should not be
23932 ** dereferenced for any reason.  The calling function should invoke
23933 ** SQLITE_MISUSE immediately.
23934 **
23935 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
23936 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
23937 ** open properly and is not fit for general use but which can be
23938 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
23939 */
23940 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
23941   u32 magic;
23942   if( db==0 ){
23943     logBadConnection("NULL");
23944     return 0;
23945   }
23946   magic = db->magic;
23947   if( magic!=SQLITE_MAGIC_OPEN ){
23948     if( sqlite3SafetyCheckSickOrOk(db) ){
23949       testcase( sqlite3GlobalConfig.xLog!=0 );
23950       logBadConnection("unopened");
23951     }
23952     return 0;
23953   }else{
23954     return 1;
23955   }
23956 }
23957 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
23958   u32 magic;
23959   magic = db->magic;
23960   if( magic!=SQLITE_MAGIC_SICK &&
23961       magic!=SQLITE_MAGIC_OPEN &&
23962       magic!=SQLITE_MAGIC_BUSY ){
23963     testcase( sqlite3GlobalConfig.xLog!=0 );
23964     logBadConnection("invalid");
23965     return 0;
23966   }else{
23967     return 1;
23968   }
23969 }
23970 
23971 /*
23972 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
23973 ** the other 64-bit signed integer at *pA and store the result in *pA.
23974 ** Return 0 on success.  Or if the operation would have resulted in an
23975 ** overflow, leave *pA unchanged and return 1.
23976 */
23977 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
23978   i64 iA = *pA;
23979   testcase( iA==0 ); testcase( iA==1 );
23980   testcase( iB==-1 ); testcase( iB==0 );
23981   if( iB>=0 ){
23982     testcase( iA>0 && LARGEST_INT64 - iA == iB );
23983     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
23984     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
23985   }else{
23986     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
23987     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
23988     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
23989   }
23990   *pA += iB;
23991   return 0;
23992 }
23993 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
23994   testcase( iB==SMALLEST_INT64+1 );
23995   if( iB==SMALLEST_INT64 ){
23996     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
23997     if( (*pA)>=0 ) return 1;
23998     *pA -= iB;
23999     return 0;
24000   }else{
24001     return sqlite3AddInt64(pA, -iB);
24002   }
24003 }
24004 #define TWOPOWER32 (((i64)1)<<32)
24005 #define TWOPOWER31 (((i64)1)<<31)
24006 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
24007   i64 iA = *pA;
24008   i64 iA1, iA0, iB1, iB0, r;
24009 
24010   iA1 = iA/TWOPOWER32;
24011   iA0 = iA % TWOPOWER32;
24012   iB1 = iB/TWOPOWER32;
24013   iB0 = iB % TWOPOWER32;
24014   if( iA1==0 ){
24015     if( iB1==0 ){
24016       *pA *= iB;
24017       return 0;
24018     }
24019     r = iA0*iB1;
24020   }else if( iB1==0 ){
24021     r = iA1*iB0;
24022   }else{
24023     /* If both iA1 and iB1 are non-zero, overflow will result */
24024     return 1;
24025   }
24026   testcase( r==(-TWOPOWER31)-1 );
24027   testcase( r==(-TWOPOWER31) );
24028   testcase( r==TWOPOWER31 );
24029   testcase( r==TWOPOWER31-1 );
24030   if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
24031   r *= TWOPOWER32;
24032   if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
24033   *pA = r;
24034   return 0;
24035 }
24036 
24037 /*
24038 ** Compute the absolute value of a 32-bit signed integer, of possible.  Or
24039 ** if the integer has a value of -2147483648, return +2147483647
24040 */
24041 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
24042   if( x>=0 ) return x;
24043   if( x==(int)0x80000000 ) return 0x7fffffff;
24044   return -x;
24045 }
24046 
24047 #ifdef SQLITE_ENABLE_8_3_NAMES
24048 /*
24049 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
24050 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
24051 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
24052 ** three characters, then shorten the suffix on z[] to be the last three
24053 ** characters of the original suffix.
24054 **
24055 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
24056 ** do the suffix shortening regardless of URI parameter.
24057 **
24058 ** Examples:
24059 **
24060 **     test.db-journal    =>   test.nal
24061 **     test.db-wal        =>   test.wal
24062 **     test.db-shm        =>   test.shm
24063 **     test.db-mj7f3319fa =>   test.9fa
24064 */
24065 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
24066 #if SQLITE_ENABLE_8_3_NAMES<2
24067   if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
24068 #endif
24069   {
24070     int i, sz;
24071     sz = sqlite3Strlen30(z);
24072     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
24073     if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
24074   }
24075 }
24076 #endif
24077 
24078 /*
24079 ** Find (an approximate) sum of two LogEst values.  This computation is
24080 ** not a simple "+" operator because LogEst is stored as a logarithmic
24081 ** value.
24082 **
24083 */
24084 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
24085   static const unsigned char x[] = {
24086      10, 10,                         /* 0,1 */
24087       9, 9,                          /* 2,3 */
24088       8, 8,                          /* 4,5 */
24089       7, 7, 7,                       /* 6,7,8 */
24090       6, 6, 6,                       /* 9,10,11 */
24091       5, 5, 5,                       /* 12-14 */
24092       4, 4, 4, 4,                    /* 15-18 */
24093       3, 3, 3, 3, 3, 3,              /* 19-24 */
24094       2, 2, 2, 2, 2, 2, 2,           /* 25-31 */
24095   };
24096   if( a>=b ){
24097     if( a>b+49 ) return a;
24098     if( a>b+31 ) return a+1;
24099     return a+x[a-b];
24100   }else{
24101     if( b>a+49 ) return b;
24102     if( b>a+31 ) return b+1;
24103     return b+x[b-a];
24104   }
24105 }
24106 
24107 /*
24108 ** Convert an integer into a LogEst.  In other words, compute an
24109 ** approximation for 10*log2(x).
24110 */
24111 SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
24112   static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
24113   LogEst y = 40;
24114   if( x<8 ){
24115     if( x<2 ) return 0;
24116     while( x<8 ){  y -= 10; x <<= 1; }
24117   }else{
24118     while( x>255 ){ y += 40; x >>= 4; }
24119     while( x>15 ){  y += 10; x >>= 1; }
24120   }
24121   return a[x&7] + y - 10;
24122 }
24123 
24124 #ifndef SQLITE_OMIT_VIRTUALTABLE
24125 /*
24126 ** Convert a double into a LogEst
24127 ** In other words, compute an approximation for 10*log2(x).
24128 */
24129 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
24130   u64 a;
24131   LogEst e;
24132   assert( sizeof(x)==8 && sizeof(a)==8 );
24133   if( x<=1 ) return 0;
24134   if( x<=2000000000 ) return sqlite3LogEst((u64)x);
24135   memcpy(&a, &x, 8);
24136   e = (a>>52) - 1022;
24137   return e*10;
24138 }
24139 #endif /* SQLITE_OMIT_VIRTUALTABLE */
24140 
24141 /*
24142 ** Convert a LogEst into an integer.
24143 */
24144 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
24145   u64 n;
24146   if( x<10 ) return 1;
24147   n = x%10;
24148   x /= 10;
24149   if( n>=5 ) n -= 2;
24150   else if( n>=1 ) n -= 1;
24151   if( x>=3 ){
24152     return x>60 ? (u64)LARGEST_INT64 : (n+8)<<(x-3);
24153   }
24154   return (n+8)>>(3-x);
24155 }
24156 
24157 /************** End of util.c ************************************************/
24158 /************** Begin file hash.c ********************************************/
24159 /*
24160 ** 2001 September 22
24161 **
24162 ** The author disclaims copyright to this source code.  In place of
24163 ** a legal notice, here is a blessing:
24164 **
24165 **    May you do good and not evil.
24166 **    May you find forgiveness for yourself and forgive others.
24167 **    May you share freely, never taking more than you give.
24168 **
24169 *************************************************************************
24170 ** This is the implementation of generic hash-tables
24171 ** used in SQLite.
24172 */
24173 /* #include <assert.h> */
24174 
24175 /* Turn bulk memory into a hash table object by initializing the
24176 ** fields of the Hash structure.
24177 **
24178 ** "pNew" is a pointer to the hash table that is to be initialized.
24179 */
24180 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
24181   assert( pNew!=0 );
24182   pNew->first = 0;
24183   pNew->count = 0;
24184   pNew->htsize = 0;
24185   pNew->ht = 0;
24186 }
24187 
24188 /* Remove all entries from a hash table.  Reclaim all memory.
24189 ** Call this routine to delete a hash table or to reset a hash table
24190 ** to the empty state.
24191 */
24192 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
24193   HashElem *elem;         /* For looping over all elements of the table */
24194 
24195   assert( pH!=0 );
24196   elem = pH->first;
24197   pH->first = 0;
24198   sqlite3_free(pH->ht);
24199   pH->ht = 0;
24200   pH->htsize = 0;
24201   while( elem ){
24202     HashElem *next_elem = elem->next;
24203     sqlite3_free(elem);
24204     elem = next_elem;
24205   }
24206   pH->count = 0;
24207 }
24208 
24209 /*
24210 ** The hashing function.
24211 */
24212 static unsigned int strHash(const char *z){
24213   unsigned int h = 0;
24214   unsigned char c;
24215   while( (c = (unsigned char)*z++)!=0 ){
24216     h = (h<<3) ^ h ^ sqlite3UpperToLower[c];
24217   }
24218   return h;
24219 }
24220 
24221 
24222 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
24223 ** insert pNew into the pEntry hash bucket.
24224 */
24225 static void insertElement(
24226   Hash *pH,              /* The complete hash table */
24227   struct _ht *pEntry,    /* The entry into which pNew is inserted */
24228   HashElem *pNew         /* The element to be inserted */
24229 ){
24230   HashElem *pHead;       /* First element already in pEntry */
24231   if( pEntry ){
24232     pHead = pEntry->count ? pEntry->chain : 0;
24233     pEntry->count++;
24234     pEntry->chain = pNew;
24235   }else{
24236     pHead = 0;
24237   }
24238   if( pHead ){
24239     pNew->next = pHead;
24240     pNew->prev = pHead->prev;
24241     if( pHead->prev ){ pHead->prev->next = pNew; }
24242     else             { pH->first = pNew; }
24243     pHead->prev = pNew;
24244   }else{
24245     pNew->next = pH->first;
24246     if( pH->first ){ pH->first->prev = pNew; }
24247     pNew->prev = 0;
24248     pH->first = pNew;
24249   }
24250 }
24251 
24252 
24253 /* Resize the hash table so that it cantains "new_size" buckets.
24254 **
24255 ** The hash table might fail to resize if sqlite3_malloc() fails or
24256 ** if the new size is the same as the prior size.
24257 ** Return TRUE if the resize occurs and false if not.
24258 */
24259 static int rehash(Hash *pH, unsigned int new_size){
24260   struct _ht *new_ht;            /* The new hash table */
24261   HashElem *elem, *next_elem;    /* For looping over existing elements */
24262 
24263 #if SQLITE_MALLOC_SOFT_LIMIT>0
24264   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
24265     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
24266   }
24267   if( new_size==pH->htsize ) return 0;
24268 #endif
24269 
24270   /* The inability to allocates space for a larger hash table is
24271   ** a performance hit but it is not a fatal error.  So mark the
24272   ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
24273   ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
24274   ** only zeroes the requested number of bytes whereas this module will
24275   ** use the actual amount of space allocated for the hash table (which
24276   ** may be larger than the requested amount).
24277   */
24278   sqlite3BeginBenignMalloc();
24279   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
24280   sqlite3EndBenignMalloc();
24281 
24282   if( new_ht==0 ) return 0;
24283   sqlite3_free(pH->ht);
24284   pH->ht = new_ht;
24285   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
24286   memset(new_ht, 0, new_size*sizeof(struct _ht));
24287   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
24288     unsigned int h = strHash(elem->pKey) % new_size;
24289     next_elem = elem->next;
24290     insertElement(pH, &new_ht[h], elem);
24291   }
24292   return 1;
24293 }
24294 
24295 /* This function (for internal use only) locates an element in an
24296 ** hash table that matches the given key.  The hash for this key is
24297 ** also computed and returned in the *pH parameter.
24298 */
24299 static HashElem *findElementWithHash(
24300   const Hash *pH,     /* The pH to be searched */
24301   const char *pKey,   /* The key we are searching for */
24302   unsigned int *pHash /* Write the hash value here */
24303 ){
24304   HashElem *elem;                /* Used to loop thru the element list */
24305   int count;                     /* Number of elements left to test */
24306   unsigned int h;                /* The computed hash */
24307 
24308   if( pH->ht ){
24309     struct _ht *pEntry;
24310     h = strHash(pKey) % pH->htsize;
24311     pEntry = &pH->ht[h];
24312     elem = pEntry->chain;
24313     count = pEntry->count;
24314   }else{
24315     h = 0;
24316     elem = pH->first;
24317     count = pH->count;
24318   }
24319   *pHash = h;
24320   while( count-- ){
24321     assert( elem!=0 );
24322     if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
24323       return elem;
24324     }
24325     elem = elem->next;
24326   }
24327   return 0;
24328 }
24329 
24330 /* Remove a single entry from the hash table given a pointer to that
24331 ** element and a hash on the element's key.
24332 */
24333 static void removeElementGivenHash(
24334   Hash *pH,         /* The pH containing "elem" */
24335   HashElem* elem,   /* The element to be removed from the pH */
24336   unsigned int h    /* Hash value for the element */
24337 ){
24338   struct _ht *pEntry;
24339   if( elem->prev ){
24340     elem->prev->next = elem->next;
24341   }else{
24342     pH->first = elem->next;
24343   }
24344   if( elem->next ){
24345     elem->next->prev = elem->prev;
24346   }
24347   if( pH->ht ){
24348     pEntry = &pH->ht[h];
24349     if( pEntry->chain==elem ){
24350       pEntry->chain = elem->next;
24351     }
24352     pEntry->count--;
24353     assert( pEntry->count>=0 );
24354   }
24355   sqlite3_free( elem );
24356   pH->count--;
24357   if( pH->count==0 ){
24358     assert( pH->first==0 );
24359     assert( pH->count==0 );
24360     sqlite3HashClear(pH);
24361   }
24362 }
24363 
24364 /* Attempt to locate an element of the hash table pH with a key
24365 ** that matches pKey.  Return the data for this element if it is
24366 ** found, or NULL if there is no match.
24367 */
24368 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
24369   HashElem *elem;    /* The element that matches key */
24370   unsigned int h;    /* A hash on key */
24371 
24372   assert( pH!=0 );
24373   assert( pKey!=0 );
24374   elem = findElementWithHash(pH, pKey, &h);
24375   return elem ? elem->data : 0;
24376 }
24377 
24378 /* Insert an element into the hash table pH.  The key is pKey
24379 ** and the data is "data".
24380 **
24381 ** If no element exists with a matching key, then a new
24382 ** element is created and NULL is returned.
24383 **
24384 ** If another element already exists with the same key, then the
24385 ** new data replaces the old data and the old data is returned.
24386 ** The key is not copied in this instance.  If a malloc fails, then
24387 ** the new data is returned and the hash table is unchanged.
24388 **
24389 ** If the "data" parameter to this function is NULL, then the
24390 ** element corresponding to "key" is removed from the hash table.
24391 */
24392 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
24393   unsigned int h;       /* the hash of the key modulo hash table size */
24394   HashElem *elem;       /* Used to loop thru the element list */
24395   HashElem *new_elem;   /* New element added to the pH */
24396 
24397   assert( pH!=0 );
24398   assert( pKey!=0 );
24399   elem = findElementWithHash(pH,pKey,&h);
24400   if( elem ){
24401     void *old_data = elem->data;
24402     if( data==0 ){
24403       removeElementGivenHash(pH,elem,h);
24404     }else{
24405       elem->data = data;
24406       elem->pKey = pKey;
24407     }
24408     return old_data;
24409   }
24410   if( data==0 ) return 0;
24411   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
24412   if( new_elem==0 ) return data;
24413   new_elem->pKey = pKey;
24414   new_elem->data = data;
24415   pH->count++;
24416   if( pH->count>=10 && pH->count > 2*pH->htsize ){
24417     if( rehash(pH, pH->count*2) ){
24418       assert( pH->htsize>0 );
24419       h = strHash(pKey) % pH->htsize;
24420     }
24421   }
24422   insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
24423   return 0;
24424 }
24425 
24426 /************** End of hash.c ************************************************/
24427 /************** Begin file opcodes.c *****************************************/
24428 /* Automatically generated.  Do not edit */
24429 /* See the mkopcodec.awk script for details. */
24430 #if !defined(SQLITE_OMIT_EXPLAIN) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
24431 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
24432 # define OpHelp(X) "\0" X
24433 #else
24434 # define OpHelp(X)
24435 #endif
24436 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
24437  static const char *const azName[] = { "?",
24438      /*   1 */ "Function"         OpHelp("r[P3]=func(r[P2@P5])"),
24439      /*   2 */ "Savepoint"        OpHelp(""),
24440      /*   3 */ "AutoCommit"       OpHelp(""),
24441      /*   4 */ "Transaction"      OpHelp(""),
24442      /*   5 */ "SorterNext"       OpHelp(""),
24443      /*   6 */ "PrevIfOpen"       OpHelp(""),
24444      /*   7 */ "NextIfOpen"       OpHelp(""),
24445      /*   8 */ "Prev"             OpHelp(""),
24446      /*   9 */ "Next"             OpHelp(""),
24447      /*  10 */ "AggStep"          OpHelp("accum=r[P3] step(r[P2@P5])"),
24448      /*  11 */ "Checkpoint"       OpHelp(""),
24449      /*  12 */ "JournalMode"      OpHelp(""),
24450      /*  13 */ "Vacuum"           OpHelp(""),
24451      /*  14 */ "VFilter"          OpHelp("iplan=r[P3] zplan='P4'"),
24452      /*  15 */ "VUpdate"          OpHelp("data=r[P3@P2]"),
24453      /*  16 */ "Goto"             OpHelp(""),
24454      /*  17 */ "Gosub"            OpHelp(""),
24455      /*  18 */ "Return"           OpHelp(""),
24456      /*  19 */ "Not"              OpHelp("r[P2]= !r[P1]"),
24457      /*  20 */ "InitCoroutine"    OpHelp(""),
24458      /*  21 */ "EndCoroutine"     OpHelp(""),
24459      /*  22 */ "Yield"            OpHelp(""),
24460      /*  23 */ "HaltIfNull"       OpHelp("if r[P3]=null halt"),
24461      /*  24 */ "Halt"             OpHelp(""),
24462      /*  25 */ "Integer"          OpHelp("r[P2]=P1"),
24463      /*  26 */ "Int64"            OpHelp("r[P2]=P4"),
24464      /*  27 */ "String"           OpHelp("r[P2]='P4' (len=P1)"),
24465      /*  28 */ "Null"             OpHelp("r[P2..P3]=NULL"),
24466      /*  29 */ "SoftNull"         OpHelp("r[P1]=NULL"),
24467      /*  30 */ "Blob"             OpHelp("r[P2]=P4 (len=P1)"),
24468      /*  31 */ "Variable"         OpHelp("r[P2]=parameter(P1,P4)"),
24469      /*  32 */ "Move"             OpHelp("r[P2@P3]=r[P1@P3]"),
24470      /*  33 */ "Copy"             OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
24471      /*  34 */ "SCopy"            OpHelp("r[P2]=r[P1]"),
24472      /*  35 */ "ResultRow"        OpHelp("output=r[P1@P2]"),
24473      /*  36 */ "CollSeq"          OpHelp(""),
24474      /*  37 */ "AddImm"           OpHelp("r[P1]=r[P1]+P2"),
24475      /*  38 */ "MustBeInt"        OpHelp(""),
24476      /*  39 */ "RealAffinity"     OpHelp(""),
24477      /*  40 */ "Cast"             OpHelp("affinity(r[P1])"),
24478      /*  41 */ "Permutation"      OpHelp(""),
24479      /*  42 */ "Compare"          OpHelp("r[P1@P3] <-> r[P2@P3]"),
24480      /*  43 */ "Jump"             OpHelp(""),
24481      /*  44 */ "Once"             OpHelp(""),
24482      /*  45 */ "If"               OpHelp(""),
24483      /*  46 */ "IfNot"            OpHelp(""),
24484      /*  47 */ "Column"           OpHelp("r[P3]=PX"),
24485      /*  48 */ "Affinity"         OpHelp("affinity(r[P1@P2])"),
24486      /*  49 */ "MakeRecord"       OpHelp("r[P3]=mkrec(r[P1@P2])"),
24487      /*  50 */ "Count"            OpHelp("r[P2]=count()"),
24488      /*  51 */ "ReadCookie"       OpHelp(""),
24489      /*  52 */ "SetCookie"        OpHelp(""),
24490      /*  53 */ "ReopenIdx"        OpHelp("root=P2 iDb=P3"),
24491      /*  54 */ "OpenRead"         OpHelp("root=P2 iDb=P3"),
24492      /*  55 */ "OpenWrite"        OpHelp("root=P2 iDb=P3"),
24493      /*  56 */ "OpenAutoindex"    OpHelp("nColumn=P2"),
24494      /*  57 */ "OpenEphemeral"    OpHelp("nColumn=P2"),
24495      /*  58 */ "SorterOpen"       OpHelp(""),
24496      /*  59 */ "SequenceTest"     OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
24497      /*  60 */ "OpenPseudo"       OpHelp("P3 columns in r[P2]"),
24498      /*  61 */ "Close"            OpHelp(""),
24499      /*  62 */ "SeekLT"           OpHelp("key=r[P3@P4]"),
24500      /*  63 */ "SeekLE"           OpHelp("key=r[P3@P4]"),
24501      /*  64 */ "SeekGE"           OpHelp("key=r[P3@P4]"),
24502      /*  65 */ "SeekGT"           OpHelp("key=r[P3@P4]"),
24503      /*  66 */ "Seek"             OpHelp("intkey=r[P2]"),
24504      /*  67 */ "NoConflict"       OpHelp("key=r[P3@P4]"),
24505      /*  68 */ "NotFound"         OpHelp("key=r[P3@P4]"),
24506      /*  69 */ "Found"            OpHelp("key=r[P3@P4]"),
24507      /*  70 */ "NotExists"        OpHelp("intkey=r[P3]"),
24508      /*  71 */ "Or"               OpHelp("r[P3]=(r[P1] || r[P2])"),
24509      /*  72 */ "And"              OpHelp("r[P3]=(r[P1] && r[P2])"),
24510      /*  73 */ "Sequence"         OpHelp("r[P2]=cursor[P1].ctr++"),
24511      /*  74 */ "NewRowid"         OpHelp("r[P2]=rowid"),
24512      /*  75 */ "Insert"           OpHelp("intkey=r[P3] data=r[P2]"),
24513      /*  76 */ "IsNull"           OpHelp("if r[P1]==NULL goto P2"),
24514      /*  77 */ "NotNull"          OpHelp("if r[P1]!=NULL goto P2"),
24515      /*  78 */ "Ne"               OpHelp("if r[P1]!=r[P3] goto P2"),
24516      /*  79 */ "Eq"               OpHelp("if r[P1]==r[P3] goto P2"),
24517      /*  80 */ "Gt"               OpHelp("if r[P1]>r[P3] goto P2"),
24518      /*  81 */ "Le"               OpHelp("if r[P1]<=r[P3] goto P2"),
24519      /*  82 */ "Lt"               OpHelp("if r[P1]<r[P3] goto P2"),
24520      /*  83 */ "Ge"               OpHelp("if r[P1]>=r[P3] goto P2"),
24521      /*  84 */ "InsertInt"        OpHelp("intkey=P3 data=r[P2]"),
24522      /*  85 */ "BitAnd"           OpHelp("r[P3]=r[P1]&r[P2]"),
24523      /*  86 */ "BitOr"            OpHelp("r[P3]=r[P1]|r[P2]"),
24524      /*  87 */ "ShiftLeft"        OpHelp("r[P3]=r[P2]<<r[P1]"),
24525      /*  88 */ "ShiftRight"       OpHelp("r[P3]=r[P2]>>r[P1]"),
24526      /*  89 */ "Add"              OpHelp("r[P3]=r[P1]+r[P2]"),
24527      /*  90 */ "Subtract"         OpHelp("r[P3]=r[P2]-r[P1]"),
24528      /*  91 */ "Multiply"         OpHelp("r[P3]=r[P1]*r[P2]"),
24529      /*  92 */ "Divide"           OpHelp("r[P3]=r[P2]/r[P1]"),
24530      /*  93 */ "Remainder"        OpHelp("r[P3]=r[P2]%r[P1]"),
24531      /*  94 */ "Concat"           OpHelp("r[P3]=r[P2]+r[P1]"),
24532      /*  95 */ "Delete"           OpHelp(""),
24533      /*  96 */ "BitNot"           OpHelp("r[P1]= ~r[P1]"),
24534      /*  97 */ "String8"          OpHelp("r[P2]='P4'"),
24535      /*  98 */ "ResetCount"       OpHelp(""),
24536      /*  99 */ "SorterCompare"    OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
24537      /* 100 */ "SorterData"       OpHelp("r[P2]=data"),
24538      /* 101 */ "RowKey"           OpHelp("r[P2]=key"),
24539      /* 102 */ "RowData"          OpHelp("r[P2]=data"),
24540      /* 103 */ "Rowid"            OpHelp("r[P2]=rowid"),
24541      /* 104 */ "NullRow"          OpHelp(""),
24542      /* 105 */ "Last"             OpHelp(""),
24543      /* 106 */ "SorterSort"       OpHelp(""),
24544      /* 107 */ "Sort"             OpHelp(""),
24545      /* 108 */ "Rewind"           OpHelp(""),
24546      /* 109 */ "SorterInsert"     OpHelp(""),
24547      /* 110 */ "IdxInsert"        OpHelp("key=r[P2]"),
24548      /* 111 */ "IdxDelete"        OpHelp("key=r[P2@P3]"),
24549      /* 112 */ "IdxRowid"         OpHelp("r[P2]=rowid"),
24550      /* 113 */ "IdxLE"            OpHelp("key=r[P3@P4]"),
24551      /* 114 */ "IdxGT"            OpHelp("key=r[P3@P4]"),
24552      /* 115 */ "IdxLT"            OpHelp("key=r[P3@P4]"),
24553      /* 116 */ "IdxGE"            OpHelp("key=r[P3@P4]"),
24554      /* 117 */ "Destroy"          OpHelp(""),
24555      /* 118 */ "Clear"            OpHelp(""),
24556      /* 119 */ "ResetSorter"      OpHelp(""),
24557      /* 120 */ "CreateIndex"      OpHelp("r[P2]=root iDb=P1"),
24558      /* 121 */ "CreateTable"      OpHelp("r[P2]=root iDb=P1"),
24559      /* 122 */ "ParseSchema"      OpHelp(""),
24560      /* 123 */ "LoadAnalysis"     OpHelp(""),
24561      /* 124 */ "DropTable"        OpHelp(""),
24562      /* 125 */ "DropIndex"        OpHelp(""),
24563      /* 126 */ "DropTrigger"      OpHelp(""),
24564      /* 127 */ "IntegrityCk"      OpHelp(""),
24565      /* 128 */ "RowSetAdd"        OpHelp("rowset(P1)=r[P2]"),
24566      /* 129 */ "RowSetRead"       OpHelp("r[P3]=rowset(P1)"),
24567      /* 130 */ "RowSetTest"       OpHelp("if r[P3] in rowset(P1) goto P2"),
24568      /* 131 */ "Program"          OpHelp(""),
24569      /* 132 */ "Param"            OpHelp(""),
24570      /* 133 */ "Real"             OpHelp("r[P2]=P4"),
24571      /* 134 */ "FkCounter"        OpHelp("fkctr[P1]+=P2"),
24572      /* 135 */ "FkIfZero"         OpHelp("if fkctr[P1]==0 goto P2"),
24573      /* 136 */ "MemMax"           OpHelp("r[P1]=max(r[P1],r[P2])"),
24574      /* 137 */ "IfPos"            OpHelp("if r[P1]>0 goto P2"),
24575      /* 138 */ "IfNeg"            OpHelp("r[P1]+=P3, if r[P1]<0 goto P2"),
24576      /* 139 */ "IfZero"           OpHelp("r[P1]+=P3, if r[P1]==0 goto P2"),
24577      /* 140 */ "AggFinal"         OpHelp("accum=r[P1] N=P2"),
24578      /* 141 */ "IncrVacuum"       OpHelp(""),
24579      /* 142 */ "Expire"           OpHelp(""),
24580      /* 143 */ "TableLock"        OpHelp("iDb=P1 root=P2 write=P3"),
24581      /* 144 */ "VBegin"           OpHelp(""),
24582      /* 145 */ "VCreate"          OpHelp(""),
24583      /* 146 */ "VDestroy"         OpHelp(""),
24584      /* 147 */ "VOpen"            OpHelp(""),
24585      /* 148 */ "VColumn"          OpHelp("r[P3]=vcolumn(P2)"),
24586      /* 149 */ "VNext"            OpHelp(""),
24587      /* 150 */ "VRename"          OpHelp(""),
24588      /* 151 */ "Pagecount"        OpHelp(""),
24589      /* 152 */ "MaxPgcnt"         OpHelp(""),
24590      /* 153 */ "Init"             OpHelp("Start at P2"),
24591      /* 154 */ "Noop"             OpHelp(""),
24592      /* 155 */ "Explain"          OpHelp(""),
24593   };
24594   return azName[i];
24595 }
24596 #endif
24597 
24598 /************** End of opcodes.c *********************************************/
24599 /************** Begin file os_unix.c *****************************************/
24600 /*
24601 ** 2004 May 22
24602 **
24603 ** The author disclaims copyright to this source code.  In place of
24604 ** a legal notice, here is a blessing:
24605 **
24606 **    May you do good and not evil.
24607 **    May you find forgiveness for yourself and forgive others.
24608 **    May you share freely, never taking more than you give.
24609 **
24610 ******************************************************************************
24611 **
24612 ** This file contains the VFS implementation for unix-like operating systems
24613 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
24614 **
24615 ** There are actually several different VFS implementations in this file.
24616 ** The differences are in the way that file locking is done.  The default
24617 ** implementation uses Posix Advisory Locks.  Alternative implementations
24618 ** use flock(), dot-files, various proprietary locking schemas, or simply
24619 ** skip locking all together.
24620 **
24621 ** This source file is organized into divisions where the logic for various
24622 ** subfunctions is contained within the appropriate division.  PLEASE
24623 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
24624 ** in the correct division and should be clearly labeled.
24625 **
24626 ** The layout of divisions is as follows:
24627 **
24628 **   *  General-purpose declarations and utility functions.
24629 **   *  Unique file ID logic used by VxWorks.
24630 **   *  Various locking primitive implementations (all except proxy locking):
24631 **      + for Posix Advisory Locks
24632 **      + for no-op locks
24633 **      + for dot-file locks
24634 **      + for flock() locking
24635 **      + for named semaphore locks (VxWorks only)
24636 **      + for AFP filesystem locks (MacOSX only)
24637 **   *  sqlite3_file methods not associated with locking.
24638 **   *  Definitions of sqlite3_io_methods objects for all locking
24639 **      methods plus "finder" functions for each locking method.
24640 **   *  sqlite3_vfs method implementations.
24641 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
24642 **   *  Definitions of sqlite3_vfs objects for all locking methods
24643 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
24644 */
24645 #if SQLITE_OS_UNIX              /* This file is used on unix only */
24646 
24647 /*
24648 ** There are various methods for file locking used for concurrency
24649 ** control:
24650 **
24651 **   1. POSIX locking (the default),
24652 **   2. No locking,
24653 **   3. Dot-file locking,
24654 **   4. flock() locking,
24655 **   5. AFP locking (OSX only),
24656 **   6. Named POSIX semaphores (VXWorks only),
24657 **   7. proxy locking. (OSX only)
24658 **
24659 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
24660 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
24661 ** selection of the appropriate locking style based on the filesystem
24662 ** where the database is located.
24663 */
24664 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
24665 #  if defined(__APPLE__)
24666 #    define SQLITE_ENABLE_LOCKING_STYLE 1
24667 #  else
24668 #    define SQLITE_ENABLE_LOCKING_STYLE 0
24669 #  endif
24670 #endif
24671 
24672 /*
24673 ** Define the OS_VXWORKS pre-processor macro to 1 if building on
24674 ** vxworks, or 0 otherwise.
24675 */
24676 #ifndef OS_VXWORKS
24677 #  if defined(__RTP__) || defined(_WRS_KERNEL)
24678 #    define OS_VXWORKS 1
24679 #  else
24680 #    define OS_VXWORKS 0
24681 #  endif
24682 #endif
24683 
24684 /*
24685 ** standard include files.
24686 */
24687 #include <sys/types.h>
24688 #include <sys/stat.h>
24689 #include <fcntl.h>
24690 #include <unistd.h>
24691 /* #include <time.h> */
24692 #include <sys/time.h>
24693 #include <errno.h>
24694 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
24695 # include <sys/mman.h>
24696 #endif
24697 
24698 #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
24699 # include <sys/ioctl.h>
24700 # if OS_VXWORKS
24701 #  include <semaphore.h>
24702 #  include <limits.h>
24703 # else
24704 #  include <sys/file.h>
24705 #  include <sys/param.h>
24706 # endif
24707 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
24708 
24709 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
24710 # include <sys/mount.h>
24711 #endif
24712 
24713 #ifdef HAVE_UTIME
24714 # include <utime.h>
24715 #endif
24716 
24717 /*
24718 ** Allowed values of unixFile.fsFlags
24719 */
24720 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
24721 
24722 /*
24723 ** If we are to be thread-safe, include the pthreads header and define
24724 ** the SQLITE_UNIX_THREADS macro.
24725 */
24726 #if SQLITE_THREADSAFE
24727 /* # include <pthread.h> */
24728 # define SQLITE_UNIX_THREADS 1
24729 #endif
24730 
24731 /*
24732 ** Default permissions when creating a new file
24733 */
24734 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
24735 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
24736 #endif
24737 
24738 /*
24739 ** Default permissions when creating auto proxy dir
24740 */
24741 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
24742 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
24743 #endif
24744 
24745 /*
24746 ** Maximum supported path-length.
24747 */
24748 #define MAX_PATHNAME 512
24749 
24750 /*
24751 ** Only set the lastErrno if the error code is a real error and not
24752 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
24753 */
24754 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
24755 
24756 /* Forward references */
24757 typedef struct unixShm unixShm;               /* Connection shared memory */
24758 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
24759 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
24760 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
24761 
24762 /*
24763 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
24764 ** cannot be closed immediately. In these cases, instances of the following
24765 ** structure are used to store the file descriptor while waiting for an
24766 ** opportunity to either close or reuse it.
24767 */
24768 struct UnixUnusedFd {
24769   int fd;                   /* File descriptor to close */
24770   int flags;                /* Flags this file descriptor was opened with */
24771   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
24772 };
24773 
24774 /*
24775 ** The unixFile structure is subclass of sqlite3_file specific to the unix
24776 ** VFS implementations.
24777 */
24778 typedef struct unixFile unixFile;
24779 struct unixFile {
24780   sqlite3_io_methods const *pMethod;  /* Always the first entry */
24781   sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
24782   unixInodeInfo *pInode;              /* Info about locks on this inode */
24783   int h;                              /* The file descriptor */
24784   unsigned char eFileLock;            /* The type of lock held on this fd */
24785   unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
24786   int lastErrno;                      /* The unix errno from last I/O error */
24787   void *lockingContext;               /* Locking style specific state */
24788   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
24789   const char *zPath;                  /* Name of the file */
24790   unixShm *pShm;                      /* Shared memory segment information */
24791   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
24792 #if SQLITE_MAX_MMAP_SIZE>0
24793   int nFetchOut;                      /* Number of outstanding xFetch refs */
24794   sqlite3_int64 mmapSize;             /* Usable size of mapping at pMapRegion */
24795   sqlite3_int64 mmapSizeActual;       /* Actual size of mapping at pMapRegion */
24796   sqlite3_int64 mmapSizeMax;          /* Configured FCNTL_MMAP_SIZE value */
24797   void *pMapRegion;                   /* Memory mapped region */
24798 #endif
24799 #ifdef __QNXNTO__
24800   int sectorSize;                     /* Device sector size */
24801   int deviceCharacteristics;          /* Precomputed device characteristics */
24802 #endif
24803 #if SQLITE_ENABLE_LOCKING_STYLE
24804   int openFlags;                      /* The flags specified at open() */
24805 #endif
24806 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
24807   unsigned fsFlags;                   /* cached details from statfs() */
24808 #endif
24809 #if OS_VXWORKS
24810   struct vxworksFileId *pId;          /* Unique file ID */
24811 #endif
24812 #ifdef SQLITE_DEBUG
24813   /* The next group of variables are used to track whether or not the
24814   ** transaction counter in bytes 24-27 of database files are updated
24815   ** whenever any part of the database changes.  An assertion fault will
24816   ** occur if a file is updated without also updating the transaction
24817   ** counter.  This test is made to avoid new problems similar to the
24818   ** one described by ticket #3584.
24819   */
24820   unsigned char transCntrChng;   /* True if the transaction counter changed */
24821   unsigned char dbUpdate;        /* True if any part of database file changed */
24822   unsigned char inNormalWrite;   /* True if in a normal write operation */
24823 
24824 #endif
24825 
24826 #ifdef SQLITE_TEST
24827   /* In test mode, increase the size of this structure a bit so that
24828   ** it is larger than the struct CrashFile defined in test6.c.
24829   */
24830   char aPadding[32];
24831 #endif
24832 };
24833 
24834 /* This variable holds the process id (pid) from when the xRandomness()
24835 ** method was called.  If xOpen() is called from a different process id,
24836 ** indicating that a fork() has occurred, the PRNG will be reset.
24837 */
24838 static int randomnessPid = 0;
24839 
24840 /*
24841 ** Allowed values for the unixFile.ctrlFlags bitmask:
24842 */
24843 #define UNIXFILE_EXCL        0x01     /* Connections from one process only */
24844 #define UNIXFILE_RDONLY      0x02     /* Connection is read only */
24845 #define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
24846 #ifndef SQLITE_DISABLE_DIRSYNC
24847 # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
24848 #else
24849 # define UNIXFILE_DIRSYNC    0x00
24850 #endif
24851 #define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
24852 #define UNIXFILE_DELETE      0x20     /* Delete on close */
24853 #define UNIXFILE_URI         0x40     /* Filename might have query parameters */
24854 #define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
24855 #define UNIXFILE_WARNED    0x0100     /* verifyDbFile() warnings have been issued */
24856 
24857 /*
24858 ** Include code that is common to all os_*.c files
24859 */
24860 /************** Include os_common.h in the middle of os_unix.c ***************/
24861 /************** Begin file os_common.h ***************************************/
24862 /*
24863 ** 2004 May 22
24864 **
24865 ** The author disclaims copyright to this source code.  In place of
24866 ** a legal notice, here is a blessing:
24867 **
24868 **    May you do good and not evil.
24869 **    May you find forgiveness for yourself and forgive others.
24870 **    May you share freely, never taking more than you give.
24871 **
24872 ******************************************************************************
24873 **
24874 ** This file contains macros and a little bit of code that is common to
24875 ** all of the platform-specific files (os_*.c) and is #included into those
24876 ** files.
24877 **
24878 ** This file should be #included by the os_*.c files only.  It is not a
24879 ** general purpose header file.
24880 */
24881 #ifndef _OS_COMMON_H_
24882 #define _OS_COMMON_H_
24883 
24884 /*
24885 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
24886 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
24887 ** switch.  The following code should catch this problem at compile-time.
24888 */
24889 #ifdef MEMORY_DEBUG
24890 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
24891 #endif
24892 
24893 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
24894 # ifndef SQLITE_DEBUG_OS_TRACE
24895 #   define SQLITE_DEBUG_OS_TRACE 0
24896 # endif
24897   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
24898 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
24899 #else
24900 # define OSTRACE(X)
24901 #endif
24902 
24903 /*
24904 ** Macros for performance tracing.  Normally turned off.  Only works
24905 ** on i486 hardware.
24906 */
24907 #ifdef SQLITE_PERFORMANCE_TRACE
24908 
24909 /*
24910 ** hwtime.h contains inline assembler code for implementing
24911 ** high-performance timing routines.
24912 */
24913 /************** Include hwtime.h in the middle of os_common.h ****************/
24914 /************** Begin file hwtime.h ******************************************/
24915 /*
24916 ** 2008 May 27
24917 **
24918 ** The author disclaims copyright to this source code.  In place of
24919 ** a legal notice, here is a blessing:
24920 **
24921 **    May you do good and not evil.
24922 **    May you find forgiveness for yourself and forgive others.
24923 **    May you share freely, never taking more than you give.
24924 **
24925 ******************************************************************************
24926 **
24927 ** This file contains inline asm code for retrieving "high-performance"
24928 ** counters for x86 class CPUs.
24929 */
24930 #ifndef _HWTIME_H_
24931 #define _HWTIME_H_
24932 
24933 /*
24934 ** The following routine only works on pentium-class (or newer) processors.
24935 ** It uses the RDTSC opcode to read the cycle count value out of the
24936 ** processor and returns that value.  This can be used for high-res
24937 ** profiling.
24938 */
24939 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
24940       (defined(i386) || defined(__i386__) || defined(_M_IX86))
24941 
24942   #if defined(__GNUC__)
24943 
24944   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24945      unsigned int lo, hi;
24946      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
24947      return (sqlite_uint64)hi << 32 | lo;
24948   }
24949 
24950   #elif defined(_MSC_VER)
24951 
24952   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
24953      __asm {
24954         rdtsc
24955         ret       ; return value at EDX:EAX
24956      }
24957   }
24958 
24959   #endif
24960 
24961 #elif (defined(__GNUC__) && defined(__x86_64__))
24962 
24963   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24964       unsigned long val;
24965       __asm__ __volatile__ ("rdtsc" : "=A" (val));
24966       return val;
24967   }
24968 
24969 #elif (defined(__GNUC__) && defined(__ppc__))
24970 
24971   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24972       unsigned long long retval;
24973       unsigned long junk;
24974       __asm__ __volatile__ ("\n\
24975           1:      mftbu   %1\n\
24976                   mftb    %L0\n\
24977                   mftbu   %0\n\
24978                   cmpw    %0,%1\n\
24979                   bne     1b"
24980                   : "=r" (retval), "=r" (junk));
24981       return retval;
24982   }
24983 
24984 #else
24985 
24986   #error Need implementation of sqlite3Hwtime() for your platform.
24987 
24988   /*
24989   ** To compile without implementing sqlite3Hwtime() for your platform,
24990   ** you can remove the above #error and use the following
24991   ** stub function.  You will lose timing support for many
24992   ** of the debugging and testing utilities, but it should at
24993   ** least compile and run.
24994   */
24995 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
24996 
24997 #endif
24998 
24999 #endif /* !defined(_HWTIME_H_) */
25000 
25001 /************** End of hwtime.h **********************************************/
25002 /************** Continuing where we left off in os_common.h ******************/
25003 
25004 static sqlite_uint64 g_start;
25005 static sqlite_uint64 g_elapsed;
25006 #define TIMER_START       g_start=sqlite3Hwtime()
25007 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
25008 #define TIMER_ELAPSED     g_elapsed
25009 #else
25010 #define TIMER_START
25011 #define TIMER_END
25012 #define TIMER_ELAPSED     ((sqlite_uint64)0)
25013 #endif
25014 
25015 /*
25016 ** If we compile with the SQLITE_TEST macro set, then the following block
25017 ** of code will give us the ability to simulate a disk I/O error.  This
25018 ** is used for testing the I/O recovery logic.
25019 */
25020 #ifdef SQLITE_TEST
25021 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
25022 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
25023 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
25024 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
25025 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
25026 SQLITE_API int sqlite3_diskfull_pending = 0;
25027 SQLITE_API int sqlite3_diskfull = 0;
25028 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
25029 #define SimulateIOError(CODE)  \
25030   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
25031        || sqlite3_io_error_pending-- == 1 )  \
25032               { local_ioerr(); CODE; }
25033 static void local_ioerr(){
25034   IOTRACE(("IOERR\n"));
25035   sqlite3_io_error_hit++;
25036   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
25037 }
25038 #define SimulateDiskfullError(CODE) \
25039    if( sqlite3_diskfull_pending ){ \
25040      if( sqlite3_diskfull_pending == 1 ){ \
25041        local_ioerr(); \
25042        sqlite3_diskfull = 1; \
25043        sqlite3_io_error_hit = 1; \
25044        CODE; \
25045      }else{ \
25046        sqlite3_diskfull_pending--; \
25047      } \
25048    }
25049 #else
25050 #define SimulateIOErrorBenign(X)
25051 #define SimulateIOError(A)
25052 #define SimulateDiskfullError(A)
25053 #endif
25054 
25055 /*
25056 ** When testing, keep a count of the number of open files.
25057 */
25058 #ifdef SQLITE_TEST
25059 SQLITE_API int sqlite3_open_file_count = 0;
25060 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
25061 #else
25062 #define OpenCounter(X)
25063 #endif
25064 
25065 #endif /* !defined(_OS_COMMON_H_) */
25066 
25067 /************** End of os_common.h *******************************************/
25068 /************** Continuing where we left off in os_unix.c ********************/
25069 
25070 /*
25071 ** Define various macros that are missing from some systems.
25072 */
25073 #ifndef O_LARGEFILE
25074 # define O_LARGEFILE 0
25075 #endif
25076 #ifdef SQLITE_DISABLE_LFS
25077 # undef O_LARGEFILE
25078 # define O_LARGEFILE 0
25079 #endif
25080 #ifndef O_NOFOLLOW
25081 # define O_NOFOLLOW 0
25082 #endif
25083 #ifndef O_BINARY
25084 # define O_BINARY 0
25085 #endif
25086 
25087 /*
25088 ** The threadid macro resolves to the thread-id or to 0.  Used for
25089 ** testing and debugging only.
25090 */
25091 #if SQLITE_THREADSAFE
25092 #define threadid pthread_self()
25093 #else
25094 #define threadid 0
25095 #endif
25096 
25097 /*
25098 ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
25099 */
25100 #if !defined(HAVE_MREMAP)
25101 # if defined(__linux__) && defined(_GNU_SOURCE)
25102 #  define HAVE_MREMAP 1
25103 # else
25104 #  define HAVE_MREMAP 0
25105 # endif
25106 #endif
25107 
25108 /*
25109 ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
25110 ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
25111 */
25112 #ifdef __ANDROID__
25113 # define lseek lseek64
25114 #endif
25115 
25116 /*
25117 ** Different Unix systems declare open() in different ways.  Same use
25118 ** open(const char*,int,mode_t).  Others use open(const char*,int,...).
25119 ** The difference is important when using a pointer to the function.
25120 **
25121 ** The safest way to deal with the problem is to always use this wrapper
25122 ** which always has the same well-defined interface.
25123 */
25124 static int posixOpen(const char *zFile, int flags, int mode){
25125   return open(zFile, flags, mode);
25126 }
25127 
25128 /*
25129 ** On some systems, calls to fchown() will trigger a message in a security
25130 ** log if they come from non-root processes.  So avoid calling fchown() if
25131 ** we are not running as root.
25132 */
25133 static int posixFchown(int fd, uid_t uid, gid_t gid){
25134 #if OS_VXWORKS
25135   return 0;
25136 #else
25137   return geteuid() ? 0 : fchown(fd,uid,gid);
25138 #endif
25139 }
25140 
25141 /* Forward reference */
25142 static int openDirectory(const char*, int*);
25143 static int unixGetpagesize(void);
25144 
25145 /*
25146 ** Many system calls are accessed through pointer-to-functions so that
25147 ** they may be overridden at runtime to facilitate fault injection during
25148 ** testing and sandboxing.  The following array holds the names and pointers
25149 ** to all overrideable system calls.
25150 */
25151 static struct unix_syscall {
25152   const char *zName;            /* Name of the system call */
25153   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
25154   sqlite3_syscall_ptr pDefault; /* Default value */
25155 } aSyscall[] = {
25156   { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
25157 #define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
25158 
25159   { "close",        (sqlite3_syscall_ptr)close,      0  },
25160 #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
25161 
25162   { "access",       (sqlite3_syscall_ptr)access,     0  },
25163 #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
25164 
25165   { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
25166 #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
25167 
25168   { "stat",         (sqlite3_syscall_ptr)stat,       0  },
25169 #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
25170 
25171 /*
25172 ** The DJGPP compiler environment looks mostly like Unix, but it
25173 ** lacks the fcntl() system call.  So redefine fcntl() to be something
25174 ** that always succeeds.  This means that locking does not occur under
25175 ** DJGPP.  But it is DOS - what did you expect?
25176 */
25177 #ifdef __DJGPP__
25178   { "fstat",        0,                 0  },
25179 #define osFstat(a,b,c)    0
25180 #else
25181   { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
25182 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
25183 #endif
25184 
25185   { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
25186 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
25187 
25188   { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
25189 #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
25190 
25191   { "read",         (sqlite3_syscall_ptr)read,       0  },
25192 #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
25193 
25194 #if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
25195   { "pread",        (sqlite3_syscall_ptr)pread,      0  },
25196 #else
25197   { "pread",        (sqlite3_syscall_ptr)0,          0  },
25198 #endif
25199 #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
25200 
25201 #if defined(USE_PREAD64)
25202   { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
25203 #else
25204   { "pread64",      (sqlite3_syscall_ptr)0,          0  },
25205 #endif
25206 #define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
25207 
25208   { "write",        (sqlite3_syscall_ptr)write,      0  },
25209 #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
25210 
25211 #if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
25212   { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
25213 #else
25214   { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
25215 #endif
25216 #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
25217                     aSyscall[12].pCurrent)
25218 
25219 #if defined(USE_PREAD64)
25220   { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
25221 #else
25222   { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
25223 #endif
25224 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
25225                     aSyscall[13].pCurrent)
25226 
25227   { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
25228 #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
25229 
25230 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
25231   { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
25232 #else
25233   { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
25234 #endif
25235 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
25236 
25237   { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
25238 #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
25239 
25240   { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
25241 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
25242 
25243   { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
25244 #define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
25245 
25246   { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
25247 #define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
25248 
25249   { "fchown",       (sqlite3_syscall_ptr)posixFchown,     0 },
25250 #define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
25251 
25252 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
25253   { "mmap",       (sqlite3_syscall_ptr)mmap,     0 },
25254 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
25255 
25256   { "munmap",       (sqlite3_syscall_ptr)munmap,          0 },
25257 #define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
25258 
25259 #if HAVE_MREMAP
25260   { "mremap",       (sqlite3_syscall_ptr)mremap,          0 },
25261 #else
25262   { "mremap",       (sqlite3_syscall_ptr)0,               0 },
25263 #endif
25264 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
25265   { "getpagesize",  (sqlite3_syscall_ptr)unixGetpagesize, 0 },
25266 #define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
25267 
25268 #endif
25269 
25270 }; /* End of the overrideable system calls */
25271 
25272 /*
25273 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
25274 ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
25275 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
25276 ** system call named zName.
25277 */
25278 static int unixSetSystemCall(
25279   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
25280   const char *zName,            /* Name of system call to override */
25281   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
25282 ){
25283   unsigned int i;
25284   int rc = SQLITE_NOTFOUND;
25285 
25286   UNUSED_PARAMETER(pNotUsed);
25287   if( zName==0 ){
25288     /* If no zName is given, restore all system calls to their default
25289     ** settings and return NULL
25290     */
25291     rc = SQLITE_OK;
25292     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25293       if( aSyscall[i].pDefault ){
25294         aSyscall[i].pCurrent = aSyscall[i].pDefault;
25295       }
25296     }
25297   }else{
25298     /* If zName is specified, operate on only the one system call
25299     ** specified.
25300     */
25301     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25302       if( strcmp(zName, aSyscall[i].zName)==0 ){
25303         if( aSyscall[i].pDefault==0 ){
25304           aSyscall[i].pDefault = aSyscall[i].pCurrent;
25305         }
25306         rc = SQLITE_OK;
25307         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
25308         aSyscall[i].pCurrent = pNewFunc;
25309         break;
25310       }
25311     }
25312   }
25313   return rc;
25314 }
25315 
25316 /*
25317 ** Return the value of a system call.  Return NULL if zName is not a
25318 ** recognized system call name.  NULL is also returned if the system call
25319 ** is currently undefined.
25320 */
25321 static sqlite3_syscall_ptr unixGetSystemCall(
25322   sqlite3_vfs *pNotUsed,
25323   const char *zName
25324 ){
25325   unsigned int i;
25326 
25327   UNUSED_PARAMETER(pNotUsed);
25328   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25329     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
25330   }
25331   return 0;
25332 }
25333 
25334 /*
25335 ** Return the name of the first system call after zName.  If zName==NULL
25336 ** then return the name of the first system call.  Return NULL if zName
25337 ** is the last system call or if zName is not the name of a valid
25338 ** system call.
25339 */
25340 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
25341   int i = -1;
25342 
25343   UNUSED_PARAMETER(p);
25344   if( zName ){
25345     for(i=0; i<ArraySize(aSyscall)-1; i++){
25346       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
25347     }
25348   }
25349   for(i++; i<ArraySize(aSyscall); i++){
25350     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
25351   }
25352   return 0;
25353 }
25354 
25355 /*
25356 ** Do not accept any file descriptor less than this value, in order to avoid
25357 ** opening database file using file descriptors that are commonly used for
25358 ** standard input, output, and error.
25359 */
25360 #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
25361 # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
25362 #endif
25363 
25364 /*
25365 ** Invoke open().  Do so multiple times, until it either succeeds or
25366 ** fails for some reason other than EINTR.
25367 **
25368 ** If the file creation mode "m" is 0 then set it to the default for
25369 ** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
25370 ** 0644) as modified by the system umask.  If m is not 0, then
25371 ** make the file creation mode be exactly m ignoring the umask.
25372 **
25373 ** The m parameter will be non-zero only when creating -wal, -journal,
25374 ** and -shm files.  We want those files to have *exactly* the same
25375 ** permissions as their original database, unadulterated by the umask.
25376 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
25377 ** transaction crashes and leaves behind hot journals, then any
25378 ** process that is able to write to the database will also be able to
25379 ** recover the hot journals.
25380 */
25381 static int robust_open(const char *z, int f, mode_t m){
25382   int fd;
25383   mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
25384   while(1){
25385 #if defined(O_CLOEXEC)
25386     fd = osOpen(z,f|O_CLOEXEC,m2);
25387 #else
25388     fd = osOpen(z,f,m2);
25389 #endif
25390     if( fd<0 ){
25391       if( errno==EINTR ) continue;
25392       break;
25393     }
25394     if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
25395     osClose(fd);
25396     sqlite3_log(SQLITE_WARNING,
25397                 "attempt to open \"%s\" as file descriptor %d", z, fd);
25398     fd = -1;
25399     if( osOpen("/dev/null", f, m)<0 ) break;
25400   }
25401   if( fd>=0 ){
25402     if( m!=0 ){
25403       struct stat statbuf;
25404       if( osFstat(fd, &statbuf)==0
25405        && statbuf.st_size==0
25406        && (statbuf.st_mode&0777)!=m
25407       ){
25408         osFchmod(fd, m);
25409       }
25410     }
25411 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
25412     osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
25413 #endif
25414   }
25415   return fd;
25416 }
25417 
25418 /*
25419 ** Helper functions to obtain and relinquish the global mutex. The
25420 ** global mutex is used to protect the unixInodeInfo and
25421 ** vxworksFileId objects used by this file, all of which may be
25422 ** shared by multiple threads.
25423 **
25424 ** Function unixMutexHeld() is used to assert() that the global mutex
25425 ** is held when required. This function is only used as part of assert()
25426 ** statements. e.g.
25427 **
25428 **   unixEnterMutex()
25429 **     assert( unixMutexHeld() );
25430 **   unixEnterLeave()
25431 */
25432 static void unixEnterMutex(void){
25433   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25434 }
25435 static void unixLeaveMutex(void){
25436   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25437 }
25438 #ifdef SQLITE_DEBUG
25439 static int unixMutexHeld(void) {
25440   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25441 }
25442 #endif
25443 
25444 
25445 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
25446 /*
25447 ** Helper function for printing out trace information from debugging
25448 ** binaries. This returns the string representation of the supplied
25449 ** integer lock-type.
25450 */
25451 static const char *azFileLock(int eFileLock){
25452   switch( eFileLock ){
25453     case NO_LOCK: return "NONE";
25454     case SHARED_LOCK: return "SHARED";
25455     case RESERVED_LOCK: return "RESERVED";
25456     case PENDING_LOCK: return "PENDING";
25457     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
25458   }
25459   return "ERROR";
25460 }
25461 #endif
25462 
25463 #ifdef SQLITE_LOCK_TRACE
25464 /*
25465 ** Print out information about all locking operations.
25466 **
25467 ** This routine is used for troubleshooting locks on multithreaded
25468 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
25469 ** command-line option on the compiler.  This code is normally
25470 ** turned off.
25471 */
25472 static int lockTrace(int fd, int op, struct flock *p){
25473   char *zOpName, *zType;
25474   int s;
25475   int savedErrno;
25476   if( op==F_GETLK ){
25477     zOpName = "GETLK";
25478   }else if( op==F_SETLK ){
25479     zOpName = "SETLK";
25480   }else{
25481     s = osFcntl(fd, op, p);
25482     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
25483     return s;
25484   }
25485   if( p->l_type==F_RDLCK ){
25486     zType = "RDLCK";
25487   }else if( p->l_type==F_WRLCK ){
25488     zType = "WRLCK";
25489   }else if( p->l_type==F_UNLCK ){
25490     zType = "UNLCK";
25491   }else{
25492     assert( 0 );
25493   }
25494   assert( p->l_whence==SEEK_SET );
25495   s = osFcntl(fd, op, p);
25496   savedErrno = errno;
25497   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
25498      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
25499      (int)p->l_pid, s);
25500   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
25501     struct flock l2;
25502     l2 = *p;
25503     osFcntl(fd, F_GETLK, &l2);
25504     if( l2.l_type==F_RDLCK ){
25505       zType = "RDLCK";
25506     }else if( l2.l_type==F_WRLCK ){
25507       zType = "WRLCK";
25508     }else if( l2.l_type==F_UNLCK ){
25509       zType = "UNLCK";
25510     }else{
25511       assert( 0 );
25512     }
25513     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
25514        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
25515   }
25516   errno = savedErrno;
25517   return s;
25518 }
25519 #undef osFcntl
25520 #define osFcntl lockTrace
25521 #endif /* SQLITE_LOCK_TRACE */
25522 
25523 /*
25524 ** Retry ftruncate() calls that fail due to EINTR
25525 **
25526 ** All calls to ftruncate() within this file should be made through this wrapper.
25527 ** On the Android platform, bypassing the logic below could lead to a corrupt
25528 ** database.
25529 */
25530 static int robust_ftruncate(int h, sqlite3_int64 sz){
25531   int rc;
25532 #ifdef __ANDROID__
25533   /* On Android, ftruncate() always uses 32-bit offsets, even if
25534   ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
25535   ** truncate a file to any size larger than 2GiB. Silently ignore any
25536   ** such attempts.  */
25537   if( sz>(sqlite3_int64)0x7FFFFFFF ){
25538     rc = SQLITE_OK;
25539   }else
25540 #endif
25541   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
25542   return rc;
25543 }
25544 
25545 /*
25546 ** This routine translates a standard POSIX errno code into something
25547 ** useful to the clients of the sqlite3 functions.  Specifically, it is
25548 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
25549 ** and a variety of "please close the file descriptor NOW" errors into
25550 ** SQLITE_IOERR
25551 **
25552 ** Errors during initialization of locks, or file system support for locks,
25553 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
25554 */
25555 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
25556   switch (posixError) {
25557 #if 0
25558   /* At one point this code was not commented out. In theory, this branch
25559   ** should never be hit, as this function should only be called after
25560   ** a locking-related function (i.e. fcntl()) has returned non-zero with
25561   ** the value of errno as the first argument. Since a system call has failed,
25562   ** errno should be non-zero.
25563   **
25564   ** Despite this, if errno really is zero, we still don't want to return
25565   ** SQLITE_OK. The system call failed, and *some* SQLite error should be
25566   ** propagated back to the caller. Commenting this branch out means errno==0
25567   ** will be handled by the "default:" case below.
25568   */
25569   case 0:
25570     return SQLITE_OK;
25571 #endif
25572 
25573   case EAGAIN:
25574   case ETIMEDOUT:
25575   case EBUSY:
25576   case EINTR:
25577   case ENOLCK:
25578     /* random NFS retry error, unless during file system support
25579      * introspection, in which it actually means what it says */
25580     return SQLITE_BUSY;
25581 
25582   case EACCES:
25583     /* EACCES is like EAGAIN during locking operations, but not any other time*/
25584     if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
25585         (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
25586         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
25587         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
25588       return SQLITE_BUSY;
25589     }
25590     /* else fall through */
25591   case EPERM:
25592     return SQLITE_PERM;
25593 
25594 #if EOPNOTSUPP!=ENOTSUP
25595   case EOPNOTSUPP:
25596     /* something went terribly awry, unless during file system support
25597      * introspection, in which it actually means what it says */
25598 #endif
25599 #ifdef ENOTSUP
25600   case ENOTSUP:
25601     /* invalid fd, unless during file system support introspection, in which
25602      * it actually means what it says */
25603 #endif
25604   case EIO:
25605   case EBADF:
25606   case EINVAL:
25607   case ENOTCONN:
25608   case ENODEV:
25609   case ENXIO:
25610   case ENOENT:
25611 #ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
25612   case ESTALE:
25613 #endif
25614   case ENOSYS:
25615     /* these should force the client to close the file and reconnect */
25616 
25617   default:
25618     return sqliteIOErr;
25619   }
25620 }
25621 
25622 
25623 /******************************************************************************
25624 ****************** Begin Unique File ID Utility Used By VxWorks ***************
25625 **
25626 ** On most versions of unix, we can get a unique ID for a file by concatenating
25627 ** the device number and the inode number.  But this does not work on VxWorks.
25628 ** On VxWorks, a unique file id must be based on the canonical filename.
25629 **
25630 ** A pointer to an instance of the following structure can be used as a
25631 ** unique file ID in VxWorks.  Each instance of this structure contains
25632 ** a copy of the canonical filename.  There is also a reference count.
25633 ** The structure is reclaimed when the number of pointers to it drops to
25634 ** zero.
25635 **
25636 ** There are never very many files open at one time and lookups are not
25637 ** a performance-critical path, so it is sufficient to put these
25638 ** structures on a linked list.
25639 */
25640 struct vxworksFileId {
25641   struct vxworksFileId *pNext;  /* Next in a list of them all */
25642   int nRef;                     /* Number of references to this one */
25643   int nName;                    /* Length of the zCanonicalName[] string */
25644   char *zCanonicalName;         /* Canonical filename */
25645 };
25646 
25647 #if OS_VXWORKS
25648 /*
25649 ** All unique filenames are held on a linked list headed by this
25650 ** variable:
25651 */
25652 static struct vxworksFileId *vxworksFileList = 0;
25653 
25654 /*
25655 ** Simplify a filename into its canonical form
25656 ** by making the following changes:
25657 **
25658 **  * removing any trailing and duplicate /
25659 **  * convert /./ into just /
25660 **  * convert /A/../ where A is any simple name into just /
25661 **
25662 ** Changes are made in-place.  Return the new name length.
25663 **
25664 ** The original filename is in z[0..n-1].  Return the number of
25665 ** characters in the simplified name.
25666 */
25667 static int vxworksSimplifyName(char *z, int n){
25668   int i, j;
25669   while( n>1 && z[n-1]=='/' ){ n--; }
25670   for(i=j=0; i<n; i++){
25671     if( z[i]=='/' ){
25672       if( z[i+1]=='/' ) continue;
25673       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
25674         i += 1;
25675         continue;
25676       }
25677       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
25678         while( j>0 && z[j-1]!='/' ){ j--; }
25679         if( j>0 ){ j--; }
25680         i += 2;
25681         continue;
25682       }
25683     }
25684     z[j++] = z[i];
25685   }
25686   z[j] = 0;
25687   return j;
25688 }
25689 
25690 /*
25691 ** Find a unique file ID for the given absolute pathname.  Return
25692 ** a pointer to the vxworksFileId object.  This pointer is the unique
25693 ** file ID.
25694 **
25695 ** The nRef field of the vxworksFileId object is incremented before
25696 ** the object is returned.  A new vxworksFileId object is created
25697 ** and added to the global list if necessary.
25698 **
25699 ** If a memory allocation error occurs, return NULL.
25700 */
25701 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
25702   struct vxworksFileId *pNew;         /* search key and new file ID */
25703   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
25704   int n;                              /* Length of zAbsoluteName string */
25705 
25706   assert( zAbsoluteName[0]=='/' );
25707   n = (int)strlen(zAbsoluteName);
25708   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
25709   if( pNew==0 ) return 0;
25710   pNew->zCanonicalName = (char*)&pNew[1];
25711   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
25712   n = vxworksSimplifyName(pNew->zCanonicalName, n);
25713 
25714   /* Search for an existing entry that matching the canonical name.
25715   ** If found, increment the reference count and return a pointer to
25716   ** the existing file ID.
25717   */
25718   unixEnterMutex();
25719   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
25720     if( pCandidate->nName==n
25721      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
25722     ){
25723        sqlite3_free(pNew);
25724        pCandidate->nRef++;
25725        unixLeaveMutex();
25726        return pCandidate;
25727     }
25728   }
25729 
25730   /* No match was found.  We will make a new file ID */
25731   pNew->nRef = 1;
25732   pNew->nName = n;
25733   pNew->pNext = vxworksFileList;
25734   vxworksFileList = pNew;
25735   unixLeaveMutex();
25736   return pNew;
25737 }
25738 
25739 /*
25740 ** Decrement the reference count on a vxworksFileId object.  Free
25741 ** the object when the reference count reaches zero.
25742 */
25743 static void vxworksReleaseFileId(struct vxworksFileId *pId){
25744   unixEnterMutex();
25745   assert( pId->nRef>0 );
25746   pId->nRef--;
25747   if( pId->nRef==0 ){
25748     struct vxworksFileId **pp;
25749     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
25750     assert( *pp==pId );
25751     *pp = pId->pNext;
25752     sqlite3_free(pId);
25753   }
25754   unixLeaveMutex();
25755 }
25756 #endif /* OS_VXWORKS */
25757 /*************** End of Unique File ID Utility Used By VxWorks ****************
25758 ******************************************************************************/
25759 
25760 
25761 /******************************************************************************
25762 *************************** Posix Advisory Locking ****************************
25763 **
25764 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
25765 ** section 6.5.2.2 lines 483 through 490 specify that when a process
25766 ** sets or clears a lock, that operation overrides any prior locks set
25767 ** by the same process.  It does not explicitly say so, but this implies
25768 ** that it overrides locks set by the same process using a different
25769 ** file descriptor.  Consider this test case:
25770 **
25771 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
25772 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
25773 **
25774 ** Suppose ./file1 and ./file2 are really the same file (because
25775 ** one is a hard or symbolic link to the other) then if you set
25776 ** an exclusive lock on fd1, then try to get an exclusive lock
25777 ** on fd2, it works.  I would have expected the second lock to
25778 ** fail since there was already a lock on the file due to fd1.
25779 ** But not so.  Since both locks came from the same process, the
25780 ** second overrides the first, even though they were on different
25781 ** file descriptors opened on different file names.
25782 **
25783 ** This means that we cannot use POSIX locks to synchronize file access
25784 ** among competing threads of the same process.  POSIX locks will work fine
25785 ** to synchronize access for threads in separate processes, but not
25786 ** threads within the same process.
25787 **
25788 ** To work around the problem, SQLite has to manage file locks internally
25789 ** on its own.  Whenever a new database is opened, we have to find the
25790 ** specific inode of the database file (the inode is determined by the
25791 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
25792 ** and check for locks already existing on that inode.  When locks are
25793 ** created or removed, we have to look at our own internal record of the
25794 ** locks to see if another thread has previously set a lock on that same
25795 ** inode.
25796 **
25797 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
25798 ** For VxWorks, we have to use the alternative unique ID system based on
25799 ** canonical filename and implemented in the previous division.)
25800 **
25801 ** The sqlite3_file structure for POSIX is no longer just an integer file
25802 ** descriptor.  It is now a structure that holds the integer file
25803 ** descriptor and a pointer to a structure that describes the internal
25804 ** locks on the corresponding inode.  There is one locking structure
25805 ** per inode, so if the same inode is opened twice, both unixFile structures
25806 ** point to the same locking structure.  The locking structure keeps
25807 ** a reference count (so we will know when to delete it) and a "cnt"
25808 ** field that tells us its internal lock status.  cnt==0 means the
25809 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
25810 ** cnt>0 means there are cnt shared locks on the file.
25811 **
25812 ** Any attempt to lock or unlock a file first checks the locking
25813 ** structure.  The fcntl() system call is only invoked to set a
25814 ** POSIX lock if the internal lock structure transitions between
25815 ** a locked and an unlocked state.
25816 **
25817 ** But wait:  there are yet more problems with POSIX advisory locks.
25818 **
25819 ** If you close a file descriptor that points to a file that has locks,
25820 ** all locks on that file that are owned by the current process are
25821 ** released.  To work around this problem, each unixInodeInfo object
25822 ** maintains a count of the number of pending locks on tha inode.
25823 ** When an attempt is made to close an unixFile, if there are
25824 ** other unixFile open on the same inode that are holding locks, the call
25825 ** to close() the file descriptor is deferred until all of the locks clear.
25826 ** The unixInodeInfo structure keeps a list of file descriptors that need to
25827 ** be closed and that list is walked (and cleared) when the last lock
25828 ** clears.
25829 **
25830 ** Yet another problem:  LinuxThreads do not play well with posix locks.
25831 **
25832 ** Many older versions of linux use the LinuxThreads library which is
25833 ** not posix compliant.  Under LinuxThreads, a lock created by thread
25834 ** A cannot be modified or overridden by a different thread B.
25835 ** Only thread A can modify the lock.  Locking behavior is correct
25836 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
25837 ** on linux - with NPTL a lock created by thread A can override locks
25838 ** in thread B.  But there is no way to know at compile-time which
25839 ** threading library is being used.  So there is no way to know at
25840 ** compile-time whether or not thread A can override locks on thread B.
25841 ** One has to do a run-time check to discover the behavior of the
25842 ** current process.
25843 **
25844 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
25845 ** was dropped beginning with version 3.7.0.  SQLite will still work with
25846 ** LinuxThreads provided that (1) there is no more than one connection
25847 ** per database file in the same process and (2) database connections
25848 ** do not move across threads.
25849 */
25850 
25851 /*
25852 ** An instance of the following structure serves as the key used
25853 ** to locate a particular unixInodeInfo object.
25854 */
25855 struct unixFileId {
25856   dev_t dev;                  /* Device number */
25857 #if OS_VXWORKS
25858   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
25859 #else
25860   ino_t ino;                  /* Inode number */
25861 #endif
25862 };
25863 
25864 /*
25865 ** An instance of the following structure is allocated for each open
25866 ** inode.  Or, on LinuxThreads, there is one of these structures for
25867 ** each inode opened by each thread.
25868 **
25869 ** A single inode can have multiple file descriptors, so each unixFile
25870 ** structure contains a pointer to an instance of this object and this
25871 ** object keeps a count of the number of unixFile pointing to it.
25872 */
25873 struct unixInodeInfo {
25874   struct unixFileId fileId;       /* The lookup key */
25875   int nShared;                    /* Number of SHARED locks held */
25876   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
25877   unsigned char bProcessLock;     /* An exclusive process lock is held */
25878   int nRef;                       /* Number of pointers to this structure */
25879   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
25880   int nLock;                      /* Number of outstanding file locks */
25881   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
25882   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
25883   unixInodeInfo *pPrev;           /*    .... doubly linked */
25884 #if SQLITE_ENABLE_LOCKING_STYLE
25885   unsigned long long sharedByte;  /* for AFP simulated shared lock */
25886 #endif
25887 #if OS_VXWORKS
25888   sem_t *pSem;                    /* Named POSIX semaphore */
25889   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
25890 #endif
25891 };
25892 
25893 /*
25894 ** A lists of all unixInodeInfo objects.
25895 */
25896 static unixInodeInfo *inodeList = 0;
25897 
25898 /*
25899 **
25900 ** This function - unixLogError_x(), is only ever called via the macro
25901 ** unixLogError().
25902 **
25903 ** It is invoked after an error occurs in an OS function and errno has been
25904 ** set. It logs a message using sqlite3_log() containing the current value of
25905 ** errno and, if possible, the human-readable equivalent from strerror() or
25906 ** strerror_r().
25907 **
25908 ** The first argument passed to the macro should be the error code that
25909 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
25910 ** The two subsequent arguments should be the name of the OS function that
25911 ** failed (e.g. "unlink", "open") and the associated file-system path,
25912 ** if any.
25913 */
25914 #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
25915 static int unixLogErrorAtLine(
25916   int errcode,                    /* SQLite error code */
25917   const char *zFunc,              /* Name of OS function that failed */
25918   const char *zPath,              /* File path associated with error */
25919   int iLine                       /* Source line number where error occurred */
25920 ){
25921   char *zErr;                     /* Message from strerror() or equivalent */
25922   int iErrno = errno;             /* Saved syscall error number */
25923 
25924   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
25925   ** the strerror() function to obtain the human-readable error message
25926   ** equivalent to errno. Otherwise, use strerror_r().
25927   */
25928 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
25929   char aErr[80];
25930   memset(aErr, 0, sizeof(aErr));
25931   zErr = aErr;
25932 
25933   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
25934   ** assume that the system provides the GNU version of strerror_r() that
25935   ** returns a pointer to a buffer containing the error message. That pointer
25936   ** may point to aErr[], or it may point to some static storage somewhere.
25937   ** Otherwise, assume that the system provides the POSIX version of
25938   ** strerror_r(), which always writes an error message into aErr[].
25939   **
25940   ** If the code incorrectly assumes that it is the POSIX version that is
25941   ** available, the error message will often be an empty string. Not a
25942   ** huge problem. Incorrectly concluding that the GNU version is available
25943   ** could lead to a segfault though.
25944   */
25945 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
25946   zErr =
25947 # endif
25948   strerror_r(iErrno, aErr, sizeof(aErr)-1);
25949 
25950 #elif SQLITE_THREADSAFE
25951   /* This is a threadsafe build, but strerror_r() is not available. */
25952   zErr = "";
25953 #else
25954   /* Non-threadsafe build, use strerror(). */
25955   zErr = strerror(iErrno);
25956 #endif
25957 
25958   if( zPath==0 ) zPath = "";
25959   sqlite3_log(errcode,
25960       "os_unix.c:%d: (%d) %s(%s) - %s",
25961       iLine, iErrno, zFunc, zPath, zErr
25962   );
25963 
25964   return errcode;
25965 }
25966 
25967 /*
25968 ** Close a file descriptor.
25969 **
25970 ** We assume that close() almost always works, since it is only in a
25971 ** very sick application or on a very sick platform that it might fail.
25972 ** If it does fail, simply leak the file descriptor, but do log the
25973 ** error.
25974 **
25975 ** Note that it is not safe to retry close() after EINTR since the
25976 ** file descriptor might have already been reused by another thread.
25977 ** So we don't even try to recover from an EINTR.  Just log the error
25978 ** and move on.
25979 */
25980 static void robust_close(unixFile *pFile, int h, int lineno){
25981   if( osClose(h) ){
25982     unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
25983                        pFile ? pFile->zPath : 0, lineno);
25984   }
25985 }
25986 
25987 /*
25988 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
25989 */
25990 static void closePendingFds(unixFile *pFile){
25991   unixInodeInfo *pInode = pFile->pInode;
25992   UnixUnusedFd *p;
25993   UnixUnusedFd *pNext;
25994   for(p=pInode->pUnused; p; p=pNext){
25995     pNext = p->pNext;
25996     robust_close(pFile, p->fd, __LINE__);
25997     sqlite3_free(p);
25998   }
25999   pInode->pUnused = 0;
26000 }
26001 
26002 /*
26003 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
26004 **
26005 ** The mutex entered using the unixEnterMutex() function must be held
26006 ** when this function is called.
26007 */
26008 static void releaseInodeInfo(unixFile *pFile){
26009   unixInodeInfo *pInode = pFile->pInode;
26010   assert( unixMutexHeld() );
26011   if( ALWAYS(pInode) ){
26012     pInode->nRef--;
26013     if( pInode->nRef==0 ){
26014       assert( pInode->pShmNode==0 );
26015       closePendingFds(pFile);
26016       if( pInode->pPrev ){
26017         assert( pInode->pPrev->pNext==pInode );
26018         pInode->pPrev->pNext = pInode->pNext;
26019       }else{
26020         assert( inodeList==pInode );
26021         inodeList = pInode->pNext;
26022       }
26023       if( pInode->pNext ){
26024         assert( pInode->pNext->pPrev==pInode );
26025         pInode->pNext->pPrev = pInode->pPrev;
26026       }
26027       sqlite3_free(pInode);
26028     }
26029   }
26030 }
26031 
26032 /*
26033 ** Given a file descriptor, locate the unixInodeInfo object that
26034 ** describes that file descriptor.  Create a new one if necessary.  The
26035 ** return value might be uninitialized if an error occurs.
26036 **
26037 ** The mutex entered using the unixEnterMutex() function must be held
26038 ** when this function is called.
26039 **
26040 ** Return an appropriate error code.
26041 */
26042 static int findInodeInfo(
26043   unixFile *pFile,               /* Unix file with file desc used in the key */
26044   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
26045 ){
26046   int rc;                        /* System call return code */
26047   int fd;                        /* The file descriptor for pFile */
26048   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
26049   struct stat statbuf;           /* Low-level file information */
26050   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
26051 
26052   assert( unixMutexHeld() );
26053 
26054   /* Get low-level information about the file that we can used to
26055   ** create a unique name for the file.
26056   */
26057   fd = pFile->h;
26058   rc = osFstat(fd, &statbuf);
26059   if( rc!=0 ){
26060     pFile->lastErrno = errno;
26061 #ifdef EOVERFLOW
26062     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
26063 #endif
26064     return SQLITE_IOERR;
26065   }
26066 
26067 #ifdef __APPLE__
26068   /* On OS X on an msdos filesystem, the inode number is reported
26069   ** incorrectly for zero-size files.  See ticket #3260.  To work
26070   ** around this problem (we consider it a bug in OS X, not SQLite)
26071   ** we always increase the file size to 1 by writing a single byte
26072   ** prior to accessing the inode number.  The one byte written is
26073   ** an ASCII 'S' character which also happens to be the first byte
26074   ** in the header of every SQLite database.  In this way, if there
26075   ** is a race condition such that another thread has already populated
26076   ** the first page of the database, no damage is done.
26077   */
26078   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
26079     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
26080     if( rc!=1 ){
26081       pFile->lastErrno = errno;
26082       return SQLITE_IOERR;
26083     }
26084     rc = osFstat(fd, &statbuf);
26085     if( rc!=0 ){
26086       pFile->lastErrno = errno;
26087       return SQLITE_IOERR;
26088     }
26089   }
26090 #endif
26091 
26092   memset(&fileId, 0, sizeof(fileId));
26093   fileId.dev = statbuf.st_dev;
26094 #if OS_VXWORKS
26095   fileId.pId = pFile->pId;
26096 #else
26097   fileId.ino = statbuf.st_ino;
26098 #endif
26099   pInode = inodeList;
26100   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
26101     pInode = pInode->pNext;
26102   }
26103   if( pInode==0 ){
26104     pInode = sqlite3_malloc( sizeof(*pInode) );
26105     if( pInode==0 ){
26106       return SQLITE_NOMEM;
26107     }
26108     memset(pInode, 0, sizeof(*pInode));
26109     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
26110     pInode->nRef = 1;
26111     pInode->pNext = inodeList;
26112     pInode->pPrev = 0;
26113     if( inodeList ) inodeList->pPrev = pInode;
26114     inodeList = pInode;
26115   }else{
26116     pInode->nRef++;
26117   }
26118   *ppInode = pInode;
26119   return SQLITE_OK;
26120 }
26121 
26122 /*
26123 ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
26124 */
26125 static int fileHasMoved(unixFile *pFile){
26126 #if OS_VXWORKS
26127   return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
26128 #else
26129   struct stat buf;
26130   return pFile->pInode!=0 &&
26131       (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
26132 #endif
26133 }
26134 
26135 
26136 /*
26137 ** Check a unixFile that is a database.  Verify the following:
26138 **
26139 ** (1) There is exactly one hard link on the file
26140 ** (2) The file is not a symbolic link
26141 ** (3) The file has not been renamed or unlinked
26142 **
26143 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
26144 */
26145 static void verifyDbFile(unixFile *pFile){
26146   struct stat buf;
26147   int rc;
26148   if( pFile->ctrlFlags & UNIXFILE_WARNED ){
26149     /* One or more of the following warnings have already been issued.  Do not
26150     ** repeat them so as not to clutter the error log */
26151     return;
26152   }
26153   rc = osFstat(pFile->h, &buf);
26154   if( rc!=0 ){
26155     sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
26156     pFile->ctrlFlags |= UNIXFILE_WARNED;
26157     return;
26158   }
26159   if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
26160     sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
26161     pFile->ctrlFlags |= UNIXFILE_WARNED;
26162     return;
26163   }
26164   if( buf.st_nlink>1 ){
26165     sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
26166     pFile->ctrlFlags |= UNIXFILE_WARNED;
26167     return;
26168   }
26169   if( fileHasMoved(pFile) ){
26170     sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
26171     pFile->ctrlFlags |= UNIXFILE_WARNED;
26172     return;
26173   }
26174 }
26175 
26176 
26177 /*
26178 ** This routine checks if there is a RESERVED lock held on the specified
26179 ** file by this or any other process. If such a lock is held, set *pResOut
26180 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
26181 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26182 */
26183 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
26184   int rc = SQLITE_OK;
26185   int reserved = 0;
26186   unixFile *pFile = (unixFile*)id;
26187 
26188   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26189 
26190   assert( pFile );
26191   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
26192 
26193   /* Check if a thread in this process holds such a lock */
26194   if( pFile->pInode->eFileLock>SHARED_LOCK ){
26195     reserved = 1;
26196   }
26197 
26198   /* Otherwise see if some other process holds it.
26199   */
26200 #ifndef __DJGPP__
26201   if( !reserved && !pFile->pInode->bProcessLock ){
26202     struct flock lock;
26203     lock.l_whence = SEEK_SET;
26204     lock.l_start = RESERVED_BYTE;
26205     lock.l_len = 1;
26206     lock.l_type = F_WRLCK;
26207     if( osFcntl(pFile->h, F_GETLK, &lock) ){
26208       rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
26209       pFile->lastErrno = errno;
26210     } else if( lock.l_type!=F_UNLCK ){
26211       reserved = 1;
26212     }
26213   }
26214 #endif
26215 
26216   unixLeaveMutex();
26217   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
26218 
26219   *pResOut = reserved;
26220   return rc;
26221 }
26222 
26223 /*
26224 ** Attempt to set a system-lock on the file pFile.  The lock is
26225 ** described by pLock.
26226 **
26227 ** If the pFile was opened read/write from unix-excl, then the only lock
26228 ** ever obtained is an exclusive lock, and it is obtained exactly once
26229 ** the first time any lock is attempted.  All subsequent system locking
26230 ** operations become no-ops.  Locking operations still happen internally,
26231 ** in order to coordinate access between separate database connections
26232 ** within this process, but all of that is handled in memory and the
26233 ** operating system does not participate.
26234 **
26235 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
26236 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
26237 ** and is read-only.
26238 **
26239 ** Zero is returned if the call completes successfully, or -1 if a call
26240 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
26241 */
26242 static int unixFileLock(unixFile *pFile, struct flock *pLock){
26243   int rc;
26244   unixInodeInfo *pInode = pFile->pInode;
26245   assert( unixMutexHeld() );
26246   assert( pInode!=0 );
26247   if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
26248    && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
26249   ){
26250     if( pInode->bProcessLock==0 ){
26251       struct flock lock;
26252       assert( pInode->nLock==0 );
26253       lock.l_whence = SEEK_SET;
26254       lock.l_start = SHARED_FIRST;
26255       lock.l_len = SHARED_SIZE;
26256       lock.l_type = F_WRLCK;
26257       rc = osFcntl(pFile->h, F_SETLK, &lock);
26258       if( rc<0 ) return rc;
26259       pInode->bProcessLock = 1;
26260       pInode->nLock++;
26261     }else{
26262       rc = 0;
26263     }
26264   }else{
26265     rc = osFcntl(pFile->h, F_SETLK, pLock);
26266   }
26267   return rc;
26268 }
26269 
26270 /*
26271 ** Lock the file with the lock specified by parameter eFileLock - one
26272 ** of the following:
26273 **
26274 **     (1) SHARED_LOCK
26275 **     (2) RESERVED_LOCK
26276 **     (3) PENDING_LOCK
26277 **     (4) EXCLUSIVE_LOCK
26278 **
26279 ** Sometimes when requesting one lock state, additional lock states
26280 ** are inserted in between.  The locking might fail on one of the later
26281 ** transitions leaving the lock state different from what it started but
26282 ** still short of its goal.  The following chart shows the allowed
26283 ** transitions and the inserted intermediate states:
26284 **
26285 **    UNLOCKED -> SHARED
26286 **    SHARED -> RESERVED
26287 **    SHARED -> (PENDING) -> EXCLUSIVE
26288 **    RESERVED -> (PENDING) -> EXCLUSIVE
26289 **    PENDING -> EXCLUSIVE
26290 **
26291 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26292 ** routine to lower a locking level.
26293 */
26294 static int unixLock(sqlite3_file *id, int eFileLock){
26295   /* The following describes the implementation of the various locks and
26296   ** lock transitions in terms of the POSIX advisory shared and exclusive
26297   ** lock primitives (called read-locks and write-locks below, to avoid
26298   ** confusion with SQLite lock names). The algorithms are complicated
26299   ** slightly in order to be compatible with windows systems simultaneously
26300   ** accessing the same database file, in case that is ever required.
26301   **
26302   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
26303   ** byte', each single bytes at well known offsets, and the 'shared byte
26304   ** range', a range of 510 bytes at a well known offset.
26305   **
26306   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
26307   ** byte'.  If this is successful, a random byte from the 'shared byte
26308   ** range' is read-locked and the lock on the 'pending byte' released.
26309   **
26310   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
26311   ** A RESERVED lock is implemented by grabbing a write-lock on the
26312   ** 'reserved byte'.
26313   **
26314   ** A process may only obtain a PENDING lock after it has obtained a
26315   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
26316   ** on the 'pending byte'. This ensures that no new SHARED locks can be
26317   ** obtained, but existing SHARED locks are allowed to persist. A process
26318   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
26319   ** This property is used by the algorithm for rolling back a journal file
26320   ** after a crash.
26321   **
26322   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
26323   ** implemented by obtaining a write-lock on the entire 'shared byte
26324   ** range'. Since all other locks require a read-lock on one of the bytes
26325   ** within this range, this ensures that no other locks are held on the
26326   ** database.
26327   **
26328   ** The reason a single byte cannot be used instead of the 'shared byte
26329   ** range' is that some versions of windows do not support read-locks. By
26330   ** locking a random byte from a range, concurrent SHARED locks may exist
26331   ** even if the locking primitive used is always a write-lock.
26332   */
26333   int rc = SQLITE_OK;
26334   unixFile *pFile = (unixFile*)id;
26335   unixInodeInfo *pInode;
26336   struct flock lock;
26337   int tErrno = 0;
26338 
26339   assert( pFile );
26340   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
26341       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
26342       azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
26343 
26344   /* If there is already a lock of this type or more restrictive on the
26345   ** unixFile, do nothing. Don't use the end_lock: exit path, as
26346   ** unixEnterMutex() hasn't been called yet.
26347   */
26348   if( pFile->eFileLock>=eFileLock ){
26349     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
26350             azFileLock(eFileLock)));
26351     return SQLITE_OK;
26352   }
26353 
26354   /* Make sure the locking sequence is correct.
26355   **  (1) We never move from unlocked to anything higher than shared lock.
26356   **  (2) SQLite never explicitly requests a pendig lock.
26357   **  (3) A shared lock is always held when a reserve lock is requested.
26358   */
26359   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
26360   assert( eFileLock!=PENDING_LOCK );
26361   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
26362 
26363   /* This mutex is needed because pFile->pInode is shared across threads
26364   */
26365   unixEnterMutex();
26366   pInode = pFile->pInode;
26367 
26368   /* If some thread using this PID has a lock via a different unixFile*
26369   ** handle that precludes the requested lock, return BUSY.
26370   */
26371   if( (pFile->eFileLock!=pInode->eFileLock &&
26372           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
26373   ){
26374     rc = SQLITE_BUSY;
26375     goto end_lock;
26376   }
26377 
26378   /* If a SHARED lock is requested, and some thread using this PID already
26379   ** has a SHARED or RESERVED lock, then increment reference counts and
26380   ** return SQLITE_OK.
26381   */
26382   if( eFileLock==SHARED_LOCK &&
26383       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
26384     assert( eFileLock==SHARED_LOCK );
26385     assert( pFile->eFileLock==0 );
26386     assert( pInode->nShared>0 );
26387     pFile->eFileLock = SHARED_LOCK;
26388     pInode->nShared++;
26389     pInode->nLock++;
26390     goto end_lock;
26391   }
26392 
26393 
26394   /* A PENDING lock is needed before acquiring a SHARED lock and before
26395   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
26396   ** be released.
26397   */
26398   lock.l_len = 1L;
26399   lock.l_whence = SEEK_SET;
26400   if( eFileLock==SHARED_LOCK
26401       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
26402   ){
26403     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
26404     lock.l_start = PENDING_BYTE;
26405     if( unixFileLock(pFile, &lock) ){
26406       tErrno = errno;
26407       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26408       if( rc!=SQLITE_BUSY ){
26409         pFile->lastErrno = tErrno;
26410       }
26411       goto end_lock;
26412     }
26413   }
26414 
26415 
26416   /* If control gets to this point, then actually go ahead and make
26417   ** operating system calls for the specified lock.
26418   */
26419   if( eFileLock==SHARED_LOCK ){
26420     assert( pInode->nShared==0 );
26421     assert( pInode->eFileLock==0 );
26422     assert( rc==SQLITE_OK );
26423 
26424     /* Now get the read-lock */
26425     lock.l_start = SHARED_FIRST;
26426     lock.l_len = SHARED_SIZE;
26427     if( unixFileLock(pFile, &lock) ){
26428       tErrno = errno;
26429       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26430     }
26431 
26432     /* Drop the temporary PENDING lock */
26433     lock.l_start = PENDING_BYTE;
26434     lock.l_len = 1L;
26435     lock.l_type = F_UNLCK;
26436     if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
26437       /* This could happen with a network mount */
26438       tErrno = errno;
26439       rc = SQLITE_IOERR_UNLOCK;
26440     }
26441 
26442     if( rc ){
26443       if( rc!=SQLITE_BUSY ){
26444         pFile->lastErrno = tErrno;
26445       }
26446       goto end_lock;
26447     }else{
26448       pFile->eFileLock = SHARED_LOCK;
26449       pInode->nLock++;
26450       pInode->nShared = 1;
26451     }
26452   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
26453     /* We are trying for an exclusive lock but another thread in this
26454     ** same process is still holding a shared lock. */
26455     rc = SQLITE_BUSY;
26456   }else{
26457     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
26458     ** assumed that there is a SHARED or greater lock on the file
26459     ** already.
26460     */
26461     assert( 0!=pFile->eFileLock );
26462     lock.l_type = F_WRLCK;
26463 
26464     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
26465     if( eFileLock==RESERVED_LOCK ){
26466       lock.l_start = RESERVED_BYTE;
26467       lock.l_len = 1L;
26468     }else{
26469       lock.l_start = SHARED_FIRST;
26470       lock.l_len = SHARED_SIZE;
26471     }
26472 
26473     if( unixFileLock(pFile, &lock) ){
26474       tErrno = errno;
26475       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26476       if( rc!=SQLITE_BUSY ){
26477         pFile->lastErrno = tErrno;
26478       }
26479     }
26480   }
26481 
26482 
26483 #ifdef SQLITE_DEBUG
26484   /* Set up the transaction-counter change checking flags when
26485   ** transitioning from a SHARED to a RESERVED lock.  The change
26486   ** from SHARED to RESERVED marks the beginning of a normal
26487   ** write operation (not a hot journal rollback).
26488   */
26489   if( rc==SQLITE_OK
26490    && pFile->eFileLock<=SHARED_LOCK
26491    && eFileLock==RESERVED_LOCK
26492   ){
26493     pFile->transCntrChng = 0;
26494     pFile->dbUpdate = 0;
26495     pFile->inNormalWrite = 1;
26496   }
26497 #endif
26498 
26499 
26500   if( rc==SQLITE_OK ){
26501     pFile->eFileLock = eFileLock;
26502     pInode->eFileLock = eFileLock;
26503   }else if( eFileLock==EXCLUSIVE_LOCK ){
26504     pFile->eFileLock = PENDING_LOCK;
26505     pInode->eFileLock = PENDING_LOCK;
26506   }
26507 
26508 end_lock:
26509   unixLeaveMutex();
26510   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
26511       rc==SQLITE_OK ? "ok" : "failed"));
26512   return rc;
26513 }
26514 
26515 /*
26516 ** Add the file descriptor used by file handle pFile to the corresponding
26517 ** pUnused list.
26518 */
26519 static void setPendingFd(unixFile *pFile){
26520   unixInodeInfo *pInode = pFile->pInode;
26521   UnixUnusedFd *p = pFile->pUnused;
26522   p->pNext = pInode->pUnused;
26523   pInode->pUnused = p;
26524   pFile->h = -1;
26525   pFile->pUnused = 0;
26526 }
26527 
26528 /*
26529 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26530 ** must be either NO_LOCK or SHARED_LOCK.
26531 **
26532 ** If the locking level of the file descriptor is already at or below
26533 ** the requested locking level, this routine is a no-op.
26534 **
26535 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
26536 ** the byte range is divided into 2 parts and the first part is unlocked then
26537 ** set to a read lock, then the other part is simply unlocked.  This works
26538 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
26539 ** remove the write lock on a region when a read lock is set.
26540 */
26541 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
26542   unixFile *pFile = (unixFile*)id;
26543   unixInodeInfo *pInode;
26544   struct flock lock;
26545   int rc = SQLITE_OK;
26546 
26547   assert( pFile );
26548   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
26549       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
26550       getpid()));
26551 
26552   assert( eFileLock<=SHARED_LOCK );
26553   if( pFile->eFileLock<=eFileLock ){
26554     return SQLITE_OK;
26555   }
26556   unixEnterMutex();
26557   pInode = pFile->pInode;
26558   assert( pInode->nShared!=0 );
26559   if( pFile->eFileLock>SHARED_LOCK ){
26560     assert( pInode->eFileLock==pFile->eFileLock );
26561 
26562 #ifdef SQLITE_DEBUG
26563     /* When reducing a lock such that other processes can start
26564     ** reading the database file again, make sure that the
26565     ** transaction counter was updated if any part of the database
26566     ** file changed.  If the transaction counter is not updated,
26567     ** other connections to the same file might not realize that
26568     ** the file has changed and hence might not know to flush their
26569     ** cache.  The use of a stale cache can lead to database corruption.
26570     */
26571     pFile->inNormalWrite = 0;
26572 #endif
26573 
26574     /* downgrading to a shared lock on NFS involves clearing the write lock
26575     ** before establishing the readlock - to avoid a race condition we downgrade
26576     ** the lock in 2 blocks, so that part of the range will be covered by a
26577     ** write lock until the rest is covered by a read lock:
26578     **  1:   [WWWWW]
26579     **  2:   [....W]
26580     **  3:   [RRRRW]
26581     **  4:   [RRRR.]
26582     */
26583     if( eFileLock==SHARED_LOCK ){
26584 
26585 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
26586       (void)handleNFSUnlock;
26587       assert( handleNFSUnlock==0 );
26588 #endif
26589 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26590       if( handleNFSUnlock ){
26591         int tErrno;               /* Error code from system call errors */
26592         off_t divSize = SHARED_SIZE - 1;
26593 
26594         lock.l_type = F_UNLCK;
26595         lock.l_whence = SEEK_SET;
26596         lock.l_start = SHARED_FIRST;
26597         lock.l_len = divSize;
26598         if( unixFileLock(pFile, &lock)==(-1) ){
26599           tErrno = errno;
26600           rc = SQLITE_IOERR_UNLOCK;
26601           if( IS_LOCK_ERROR(rc) ){
26602             pFile->lastErrno = tErrno;
26603           }
26604           goto end_unlock;
26605         }
26606         lock.l_type = F_RDLCK;
26607         lock.l_whence = SEEK_SET;
26608         lock.l_start = SHARED_FIRST;
26609         lock.l_len = divSize;
26610         if( unixFileLock(pFile, &lock)==(-1) ){
26611           tErrno = errno;
26612           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
26613           if( IS_LOCK_ERROR(rc) ){
26614             pFile->lastErrno = tErrno;
26615           }
26616           goto end_unlock;
26617         }
26618         lock.l_type = F_UNLCK;
26619         lock.l_whence = SEEK_SET;
26620         lock.l_start = SHARED_FIRST+divSize;
26621         lock.l_len = SHARED_SIZE-divSize;
26622         if( unixFileLock(pFile, &lock)==(-1) ){
26623           tErrno = errno;
26624           rc = SQLITE_IOERR_UNLOCK;
26625           if( IS_LOCK_ERROR(rc) ){
26626             pFile->lastErrno = tErrno;
26627           }
26628           goto end_unlock;
26629         }
26630       }else
26631 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26632       {
26633         lock.l_type = F_RDLCK;
26634         lock.l_whence = SEEK_SET;
26635         lock.l_start = SHARED_FIRST;
26636         lock.l_len = SHARED_SIZE;
26637         if( unixFileLock(pFile, &lock) ){
26638           /* In theory, the call to unixFileLock() cannot fail because another
26639           ** process is holding an incompatible lock. If it does, this
26640           ** indicates that the other process is not following the locking
26641           ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
26642           ** SQLITE_BUSY would confuse the upper layer (in practice it causes
26643           ** an assert to fail). */
26644           rc = SQLITE_IOERR_RDLOCK;
26645           pFile->lastErrno = errno;
26646           goto end_unlock;
26647         }
26648       }
26649     }
26650     lock.l_type = F_UNLCK;
26651     lock.l_whence = SEEK_SET;
26652     lock.l_start = PENDING_BYTE;
26653     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
26654     if( unixFileLock(pFile, &lock)==0 ){
26655       pInode->eFileLock = SHARED_LOCK;
26656     }else{
26657       rc = SQLITE_IOERR_UNLOCK;
26658       pFile->lastErrno = errno;
26659       goto end_unlock;
26660     }
26661   }
26662   if( eFileLock==NO_LOCK ){
26663     /* Decrement the shared lock counter.  Release the lock using an
26664     ** OS call only when all threads in this same process have released
26665     ** the lock.
26666     */
26667     pInode->nShared--;
26668     if( pInode->nShared==0 ){
26669       lock.l_type = F_UNLCK;
26670       lock.l_whence = SEEK_SET;
26671       lock.l_start = lock.l_len = 0L;
26672       if( unixFileLock(pFile, &lock)==0 ){
26673         pInode->eFileLock = NO_LOCK;
26674       }else{
26675         rc = SQLITE_IOERR_UNLOCK;
26676         pFile->lastErrno = errno;
26677         pInode->eFileLock = NO_LOCK;
26678         pFile->eFileLock = NO_LOCK;
26679       }
26680     }
26681 
26682     /* Decrement the count of locks against this same file.  When the
26683     ** count reaches zero, close any other file descriptors whose close
26684     ** was deferred because of outstanding locks.
26685     */
26686     pInode->nLock--;
26687     assert( pInode->nLock>=0 );
26688     if( pInode->nLock==0 ){
26689       closePendingFds(pFile);
26690     }
26691   }
26692 
26693 end_unlock:
26694   unixLeaveMutex();
26695   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
26696   return rc;
26697 }
26698 
26699 /*
26700 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26701 ** must be either NO_LOCK or SHARED_LOCK.
26702 **
26703 ** If the locking level of the file descriptor is already at or below
26704 ** the requested locking level, this routine is a no-op.
26705 */
26706 static int unixUnlock(sqlite3_file *id, int eFileLock){
26707 #if SQLITE_MAX_MMAP_SIZE>0
26708   assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
26709 #endif
26710   return posixUnlock(id, eFileLock, 0);
26711 }
26712 
26713 #if SQLITE_MAX_MMAP_SIZE>0
26714 static int unixMapfile(unixFile *pFd, i64 nByte);
26715 static void unixUnmapfile(unixFile *pFd);
26716 #endif
26717 
26718 /*
26719 ** This function performs the parts of the "close file" operation
26720 ** common to all locking schemes. It closes the directory and file
26721 ** handles, if they are valid, and sets all fields of the unixFile
26722 ** structure to 0.
26723 **
26724 ** It is *not* necessary to hold the mutex when this routine is called,
26725 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
26726 ** vxworksReleaseFileId() routine.
26727 */
26728 static int closeUnixFile(sqlite3_file *id){
26729   unixFile *pFile = (unixFile*)id;
26730 #if SQLITE_MAX_MMAP_SIZE>0
26731   unixUnmapfile(pFile);
26732 #endif
26733   if( pFile->h>=0 ){
26734     robust_close(pFile, pFile->h, __LINE__);
26735     pFile->h = -1;
26736   }
26737 #if OS_VXWORKS
26738   if( pFile->pId ){
26739     if( pFile->ctrlFlags & UNIXFILE_DELETE ){
26740       osUnlink(pFile->pId->zCanonicalName);
26741     }
26742     vxworksReleaseFileId(pFile->pId);
26743     pFile->pId = 0;
26744   }
26745 #endif
26746 #ifdef SQLITE_UNLINK_AFTER_CLOSE
26747   if( pFile->ctrlFlags & UNIXFILE_DELETE ){
26748     osUnlink(pFile->zPath);
26749     sqlite3_free(*(char**)&pFile->zPath);
26750     pFile->zPath = 0;
26751   }
26752 #endif
26753   OSTRACE(("CLOSE   %-3d\n", pFile->h));
26754   OpenCounter(-1);
26755   sqlite3_free(pFile->pUnused);
26756   memset(pFile, 0, sizeof(unixFile));
26757   return SQLITE_OK;
26758 }
26759 
26760 /*
26761 ** Close a file.
26762 */
26763 static int unixClose(sqlite3_file *id){
26764   int rc = SQLITE_OK;
26765   unixFile *pFile = (unixFile *)id;
26766   verifyDbFile(pFile);
26767   unixUnlock(id, NO_LOCK);
26768   unixEnterMutex();
26769 
26770   /* unixFile.pInode is always valid here. Otherwise, a different close
26771   ** routine (e.g. nolockClose()) would be called instead.
26772   */
26773   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
26774   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
26775     /* If there are outstanding locks, do not actually close the file just
26776     ** yet because that would clear those locks.  Instead, add the file
26777     ** descriptor to pInode->pUnused list.  It will be automatically closed
26778     ** when the last lock is cleared.
26779     */
26780     setPendingFd(pFile);
26781   }
26782   releaseInodeInfo(pFile);
26783   rc = closeUnixFile(id);
26784   unixLeaveMutex();
26785   return rc;
26786 }
26787 
26788 /************** End of the posix advisory lock implementation *****************
26789 ******************************************************************************/
26790 
26791 /******************************************************************************
26792 ****************************** No-op Locking **********************************
26793 **
26794 ** Of the various locking implementations available, this is by far the
26795 ** simplest:  locking is ignored.  No attempt is made to lock the database
26796 ** file for reading or writing.
26797 **
26798 ** This locking mode is appropriate for use on read-only databases
26799 ** (ex: databases that are burned into CD-ROM, for example.)  It can
26800 ** also be used if the application employs some external mechanism to
26801 ** prevent simultaneous access of the same database by two or more
26802 ** database connections.  But there is a serious risk of database
26803 ** corruption if this locking mode is used in situations where multiple
26804 ** database connections are accessing the same database file at the same
26805 ** time and one or more of those connections are writing.
26806 */
26807 
26808 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
26809   UNUSED_PARAMETER(NotUsed);
26810   *pResOut = 0;
26811   return SQLITE_OK;
26812 }
26813 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
26814   UNUSED_PARAMETER2(NotUsed, NotUsed2);
26815   return SQLITE_OK;
26816 }
26817 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
26818   UNUSED_PARAMETER2(NotUsed, NotUsed2);
26819   return SQLITE_OK;
26820 }
26821 
26822 /*
26823 ** Close the file.
26824 */
26825 static int nolockClose(sqlite3_file *id) {
26826   return closeUnixFile(id);
26827 }
26828 
26829 /******************* End of the no-op lock implementation *********************
26830 ******************************************************************************/
26831 
26832 /******************************************************************************
26833 ************************* Begin dot-file Locking ******************************
26834 **
26835 ** The dotfile locking implementation uses the existence of separate lock
26836 ** files (really a directory) to control access to the database.  This works
26837 ** on just about every filesystem imaginable.  But there are serious downsides:
26838 **
26839 **    (1)  There is zero concurrency.  A single reader blocks all other
26840 **         connections from reading or writing the database.
26841 **
26842 **    (2)  An application crash or power loss can leave stale lock files
26843 **         sitting around that need to be cleared manually.
26844 **
26845 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
26846 ** other locking strategy is available.
26847 **
26848 ** Dotfile locking works by creating a subdirectory in the same directory as
26849 ** the database and with the same name but with a ".lock" extension added.
26850 ** The existence of a lock directory implies an EXCLUSIVE lock.  All other
26851 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
26852 */
26853 
26854 /*
26855 ** The file suffix added to the data base filename in order to create the
26856 ** lock directory.
26857 */
26858 #define DOTLOCK_SUFFIX ".lock"
26859 
26860 /*
26861 ** This routine checks if there is a RESERVED lock held on the specified
26862 ** file by this or any other process. If such a lock is held, set *pResOut
26863 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
26864 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26865 **
26866 ** In dotfile locking, either a lock exists or it does not.  So in this
26867 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
26868 ** is held on the file and false if the file is unlocked.
26869 */
26870 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
26871   int rc = SQLITE_OK;
26872   int reserved = 0;
26873   unixFile *pFile = (unixFile*)id;
26874 
26875   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26876 
26877   assert( pFile );
26878 
26879   /* Check if a thread in this process holds such a lock */
26880   if( pFile->eFileLock>SHARED_LOCK ){
26881     /* Either this connection or some other connection in the same process
26882     ** holds a lock on the file.  No need to check further. */
26883     reserved = 1;
26884   }else{
26885     /* The lock is held if and only if the lockfile exists */
26886     const char *zLockFile = (const char*)pFile->lockingContext;
26887     reserved = osAccess(zLockFile, 0)==0;
26888   }
26889   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
26890   *pResOut = reserved;
26891   return rc;
26892 }
26893 
26894 /*
26895 ** Lock the file with the lock specified by parameter eFileLock - one
26896 ** of the following:
26897 **
26898 **     (1) SHARED_LOCK
26899 **     (2) RESERVED_LOCK
26900 **     (3) PENDING_LOCK
26901 **     (4) EXCLUSIVE_LOCK
26902 **
26903 ** Sometimes when requesting one lock state, additional lock states
26904 ** are inserted in between.  The locking might fail on one of the later
26905 ** transitions leaving the lock state different from what it started but
26906 ** still short of its goal.  The following chart shows the allowed
26907 ** transitions and the inserted intermediate states:
26908 **
26909 **    UNLOCKED -> SHARED
26910 **    SHARED -> RESERVED
26911 **    SHARED -> (PENDING) -> EXCLUSIVE
26912 **    RESERVED -> (PENDING) -> EXCLUSIVE
26913 **    PENDING -> EXCLUSIVE
26914 **
26915 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26916 ** routine to lower a locking level.
26917 **
26918 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
26919 ** But we track the other locking levels internally.
26920 */
26921 static int dotlockLock(sqlite3_file *id, int eFileLock) {
26922   unixFile *pFile = (unixFile*)id;
26923   char *zLockFile = (char *)pFile->lockingContext;
26924   int rc = SQLITE_OK;
26925 
26926 
26927   /* If we have any lock, then the lock file already exists.  All we have
26928   ** to do is adjust our internal record of the lock level.
26929   */
26930   if( pFile->eFileLock > NO_LOCK ){
26931     pFile->eFileLock = eFileLock;
26932     /* Always update the timestamp on the old file */
26933 #ifdef HAVE_UTIME
26934     utime(zLockFile, NULL);
26935 #else
26936     utimes(zLockFile, NULL);
26937 #endif
26938     return SQLITE_OK;
26939   }
26940 
26941   /* grab an exclusive lock */
26942   rc = osMkdir(zLockFile, 0777);
26943   if( rc<0 ){
26944     /* failed to open/create the lock directory */
26945     int tErrno = errno;
26946     if( EEXIST == tErrno ){
26947       rc = SQLITE_BUSY;
26948     } else {
26949       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26950       if( IS_LOCK_ERROR(rc) ){
26951         pFile->lastErrno = tErrno;
26952       }
26953     }
26954     return rc;
26955   }
26956 
26957   /* got it, set the type and return ok */
26958   pFile->eFileLock = eFileLock;
26959   return rc;
26960 }
26961 
26962 /*
26963 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26964 ** must be either NO_LOCK or SHARED_LOCK.
26965 **
26966 ** If the locking level of the file descriptor is already at or below
26967 ** the requested locking level, this routine is a no-op.
26968 **
26969 ** When the locking level reaches NO_LOCK, delete the lock file.
26970 */
26971 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
26972   unixFile *pFile = (unixFile*)id;
26973   char *zLockFile = (char *)pFile->lockingContext;
26974   int rc;
26975 
26976   assert( pFile );
26977   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
26978            pFile->eFileLock, getpid()));
26979   assert( eFileLock<=SHARED_LOCK );
26980 
26981   /* no-op if possible */
26982   if( pFile->eFileLock==eFileLock ){
26983     return SQLITE_OK;
26984   }
26985 
26986   /* To downgrade to shared, simply update our internal notion of the
26987   ** lock state.  No need to mess with the file on disk.
26988   */
26989   if( eFileLock==SHARED_LOCK ){
26990     pFile->eFileLock = SHARED_LOCK;
26991     return SQLITE_OK;
26992   }
26993 
26994   /* To fully unlock the database, delete the lock file */
26995   assert( eFileLock==NO_LOCK );
26996   rc = osRmdir(zLockFile);
26997   if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
26998   if( rc<0 ){
26999     int tErrno = errno;
27000     rc = 0;
27001     if( ENOENT != tErrno ){
27002       rc = SQLITE_IOERR_UNLOCK;
27003     }
27004     if( IS_LOCK_ERROR(rc) ){
27005       pFile->lastErrno = tErrno;
27006     }
27007     return rc;
27008   }
27009   pFile->eFileLock = NO_LOCK;
27010   return SQLITE_OK;
27011 }
27012 
27013 /*
27014 ** Close a file.  Make sure the lock has been released before closing.
27015 */
27016 static int dotlockClose(sqlite3_file *id) {
27017   int rc = SQLITE_OK;
27018   if( id ){
27019     unixFile *pFile = (unixFile*)id;
27020     dotlockUnlock(id, NO_LOCK);
27021     sqlite3_free(pFile->lockingContext);
27022     rc = closeUnixFile(id);
27023   }
27024   return rc;
27025 }
27026 /****************** End of the dot-file lock implementation *******************
27027 ******************************************************************************/
27028 
27029 /******************************************************************************
27030 ************************** Begin flock Locking ********************************
27031 **
27032 ** Use the flock() system call to do file locking.
27033 **
27034 ** flock() locking is like dot-file locking in that the various
27035 ** fine-grain locking levels supported by SQLite are collapsed into
27036 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
27037 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
27038 ** still works when you do this, but concurrency is reduced since
27039 ** only a single process can be reading the database at a time.
27040 **
27041 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
27042 ** compiling for VXWORKS.
27043 */
27044 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
27045 
27046 /*
27047 ** Retry flock() calls that fail with EINTR
27048 */
27049 #ifdef EINTR
27050 static int robust_flock(int fd, int op){
27051   int rc;
27052   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
27053   return rc;
27054 }
27055 #else
27056 # define robust_flock(a,b) flock(a,b)
27057 #endif
27058 
27059 
27060 /*
27061 ** This routine checks if there is a RESERVED lock held on the specified
27062 ** file by this or any other process. If such a lock is held, set *pResOut
27063 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
27064 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27065 */
27066 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
27067   int rc = SQLITE_OK;
27068   int reserved = 0;
27069   unixFile *pFile = (unixFile*)id;
27070 
27071   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27072 
27073   assert( pFile );
27074 
27075   /* Check if a thread in this process holds such a lock */
27076   if( pFile->eFileLock>SHARED_LOCK ){
27077     reserved = 1;
27078   }
27079 
27080   /* Otherwise see if some other process holds it. */
27081   if( !reserved ){
27082     /* attempt to get the lock */
27083     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
27084     if( !lrc ){
27085       /* got the lock, unlock it */
27086       lrc = robust_flock(pFile->h, LOCK_UN);
27087       if ( lrc ) {
27088         int tErrno = errno;
27089         /* unlock failed with an error */
27090         lrc = SQLITE_IOERR_UNLOCK;
27091         if( IS_LOCK_ERROR(lrc) ){
27092           pFile->lastErrno = tErrno;
27093           rc = lrc;
27094         }
27095       }
27096     } else {
27097       int tErrno = errno;
27098       reserved = 1;
27099       /* someone else might have it reserved */
27100       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27101       if( IS_LOCK_ERROR(lrc) ){
27102         pFile->lastErrno = tErrno;
27103         rc = lrc;
27104       }
27105     }
27106   }
27107   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
27108 
27109 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27110   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
27111     rc = SQLITE_OK;
27112     reserved=1;
27113   }
27114 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27115   *pResOut = reserved;
27116   return rc;
27117 }
27118 
27119 /*
27120 ** Lock the file with the lock specified by parameter eFileLock - one
27121 ** of the following:
27122 **
27123 **     (1) SHARED_LOCK
27124 **     (2) RESERVED_LOCK
27125 **     (3) PENDING_LOCK
27126 **     (4) EXCLUSIVE_LOCK
27127 **
27128 ** Sometimes when requesting one lock state, additional lock states
27129 ** are inserted in between.  The locking might fail on one of the later
27130 ** transitions leaving the lock state different from what it started but
27131 ** still short of its goal.  The following chart shows the allowed
27132 ** transitions and the inserted intermediate states:
27133 **
27134 **    UNLOCKED -> SHARED
27135 **    SHARED -> RESERVED
27136 **    SHARED -> (PENDING) -> EXCLUSIVE
27137 **    RESERVED -> (PENDING) -> EXCLUSIVE
27138 **    PENDING -> EXCLUSIVE
27139 **
27140 ** flock() only really support EXCLUSIVE locks.  We track intermediate
27141 ** lock states in the sqlite3_file structure, but all locks SHARED or
27142 ** above are really EXCLUSIVE locks and exclude all other processes from
27143 ** access the file.
27144 **
27145 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27146 ** routine to lower a locking level.
27147 */
27148 static int flockLock(sqlite3_file *id, int eFileLock) {
27149   int rc = SQLITE_OK;
27150   unixFile *pFile = (unixFile*)id;
27151 
27152   assert( pFile );
27153 
27154   /* if we already have a lock, it is exclusive.
27155   ** Just adjust level and punt on outta here. */
27156   if (pFile->eFileLock > NO_LOCK) {
27157     pFile->eFileLock = eFileLock;
27158     return SQLITE_OK;
27159   }
27160 
27161   /* grab an exclusive lock */
27162 
27163   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
27164     int tErrno = errno;
27165     /* didn't get, must be busy */
27166     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27167     if( IS_LOCK_ERROR(rc) ){
27168       pFile->lastErrno = tErrno;
27169     }
27170   } else {
27171     /* got it, set the type and return ok */
27172     pFile->eFileLock = eFileLock;
27173   }
27174   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
27175            rc==SQLITE_OK ? "ok" : "failed"));
27176 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27177   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
27178     rc = SQLITE_BUSY;
27179   }
27180 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27181   return rc;
27182 }
27183 
27184 
27185 /*
27186 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27187 ** must be either NO_LOCK or SHARED_LOCK.
27188 **
27189 ** If the locking level of the file descriptor is already at or below
27190 ** the requested locking level, this routine is a no-op.
27191 */
27192 static int flockUnlock(sqlite3_file *id, int eFileLock) {
27193   unixFile *pFile = (unixFile*)id;
27194 
27195   assert( pFile );
27196   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
27197            pFile->eFileLock, getpid()));
27198   assert( eFileLock<=SHARED_LOCK );
27199 
27200   /* no-op if possible */
27201   if( pFile->eFileLock==eFileLock ){
27202     return SQLITE_OK;
27203   }
27204 
27205   /* shared can just be set because we always have an exclusive */
27206   if (eFileLock==SHARED_LOCK) {
27207     pFile->eFileLock = eFileLock;
27208     return SQLITE_OK;
27209   }
27210 
27211   /* no, really, unlock. */
27212   if( robust_flock(pFile->h, LOCK_UN) ){
27213 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27214     return SQLITE_OK;
27215 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27216     return SQLITE_IOERR_UNLOCK;
27217   }else{
27218     pFile->eFileLock = NO_LOCK;
27219     return SQLITE_OK;
27220   }
27221 }
27222 
27223 /*
27224 ** Close a file.
27225 */
27226 static int flockClose(sqlite3_file *id) {
27227   int rc = SQLITE_OK;
27228   if( id ){
27229     flockUnlock(id, NO_LOCK);
27230     rc = closeUnixFile(id);
27231   }
27232   return rc;
27233 }
27234 
27235 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
27236 
27237 /******************* End of the flock lock implementation *********************
27238 ******************************************************************************/
27239 
27240 /******************************************************************************
27241 ************************ Begin Named Semaphore Locking ************************
27242 **
27243 ** Named semaphore locking is only supported on VxWorks.
27244 **
27245 ** Semaphore locking is like dot-lock and flock in that it really only
27246 ** supports EXCLUSIVE locking.  Only a single process can read or write
27247 ** the database file at a time.  This reduces potential concurrency, but
27248 ** makes the lock implementation much easier.
27249 */
27250 #if OS_VXWORKS
27251 
27252 /*
27253 ** This routine checks if there is a RESERVED lock held on the specified
27254 ** file by this or any other process. If such a lock is held, set *pResOut
27255 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
27256 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27257 */
27258 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
27259   int rc = SQLITE_OK;
27260   int reserved = 0;
27261   unixFile *pFile = (unixFile*)id;
27262 
27263   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27264 
27265   assert( pFile );
27266 
27267   /* Check if a thread in this process holds such a lock */
27268   if( pFile->eFileLock>SHARED_LOCK ){
27269     reserved = 1;
27270   }
27271 
27272   /* Otherwise see if some other process holds it. */
27273   if( !reserved ){
27274     sem_t *pSem = pFile->pInode->pSem;
27275 
27276     if( sem_trywait(pSem)==-1 ){
27277       int tErrno = errno;
27278       if( EAGAIN != tErrno ){
27279         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
27280         pFile->lastErrno = tErrno;
27281       } else {
27282         /* someone else has the lock when we are in NO_LOCK */
27283         reserved = (pFile->eFileLock < SHARED_LOCK);
27284       }
27285     }else{
27286       /* we could have it if we want it */
27287       sem_post(pSem);
27288     }
27289   }
27290   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
27291 
27292   *pResOut = reserved;
27293   return rc;
27294 }
27295 
27296 /*
27297 ** Lock the file with the lock specified by parameter eFileLock - one
27298 ** of the following:
27299 **
27300 **     (1) SHARED_LOCK
27301 **     (2) RESERVED_LOCK
27302 **     (3) PENDING_LOCK
27303 **     (4) EXCLUSIVE_LOCK
27304 **
27305 ** Sometimes when requesting one lock state, additional lock states
27306 ** are inserted in between.  The locking might fail on one of the later
27307 ** transitions leaving the lock state different from what it started but
27308 ** still short of its goal.  The following chart shows the allowed
27309 ** transitions and the inserted intermediate states:
27310 **
27311 **    UNLOCKED -> SHARED
27312 **    SHARED -> RESERVED
27313 **    SHARED -> (PENDING) -> EXCLUSIVE
27314 **    RESERVED -> (PENDING) -> EXCLUSIVE
27315 **    PENDING -> EXCLUSIVE
27316 **
27317 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
27318 ** lock states in the sqlite3_file structure, but all locks SHARED or
27319 ** above are really EXCLUSIVE locks and exclude all other processes from
27320 ** access the file.
27321 **
27322 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27323 ** routine to lower a locking level.
27324 */
27325 static int semLock(sqlite3_file *id, int eFileLock) {
27326   unixFile *pFile = (unixFile*)id;
27327   sem_t *pSem = pFile->pInode->pSem;
27328   int rc = SQLITE_OK;
27329 
27330   /* if we already have a lock, it is exclusive.
27331   ** Just adjust level and punt on outta here. */
27332   if (pFile->eFileLock > NO_LOCK) {
27333     pFile->eFileLock = eFileLock;
27334     rc = SQLITE_OK;
27335     goto sem_end_lock;
27336   }
27337 
27338   /* lock semaphore now but bail out when already locked. */
27339   if( sem_trywait(pSem)==-1 ){
27340     rc = SQLITE_BUSY;
27341     goto sem_end_lock;
27342   }
27343 
27344   /* got it, set the type and return ok */
27345   pFile->eFileLock = eFileLock;
27346 
27347  sem_end_lock:
27348   return rc;
27349 }
27350 
27351 /*
27352 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27353 ** must be either NO_LOCK or SHARED_LOCK.
27354 **
27355 ** If the locking level of the file descriptor is already at or below
27356 ** the requested locking level, this routine is a no-op.
27357 */
27358 static int semUnlock(sqlite3_file *id, int eFileLock) {
27359   unixFile *pFile = (unixFile*)id;
27360   sem_t *pSem = pFile->pInode->pSem;
27361 
27362   assert( pFile );
27363   assert( pSem );
27364   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
27365            pFile->eFileLock, getpid()));
27366   assert( eFileLock<=SHARED_LOCK );
27367 
27368   /* no-op if possible */
27369   if( pFile->eFileLock==eFileLock ){
27370     return SQLITE_OK;
27371   }
27372 
27373   /* shared can just be set because we always have an exclusive */
27374   if (eFileLock==SHARED_LOCK) {
27375     pFile->eFileLock = eFileLock;
27376     return SQLITE_OK;
27377   }
27378 
27379   /* no, really unlock. */
27380   if ( sem_post(pSem)==-1 ) {
27381     int rc, tErrno = errno;
27382     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
27383     if( IS_LOCK_ERROR(rc) ){
27384       pFile->lastErrno = tErrno;
27385     }
27386     return rc;
27387   }
27388   pFile->eFileLock = NO_LOCK;
27389   return SQLITE_OK;
27390 }
27391 
27392 /*
27393  ** Close a file.
27394  */
27395 static int semClose(sqlite3_file *id) {
27396   if( id ){
27397     unixFile *pFile = (unixFile*)id;
27398     semUnlock(id, NO_LOCK);
27399     assert( pFile );
27400     unixEnterMutex();
27401     releaseInodeInfo(pFile);
27402     unixLeaveMutex();
27403     closeUnixFile(id);
27404   }
27405   return SQLITE_OK;
27406 }
27407 
27408 #endif /* OS_VXWORKS */
27409 /*
27410 ** Named semaphore locking is only available on VxWorks.
27411 **
27412 *************** End of the named semaphore lock implementation ****************
27413 ******************************************************************************/
27414 
27415 
27416 /******************************************************************************
27417 *************************** Begin AFP Locking *********************************
27418 **
27419 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
27420 ** on Apple Macintosh computers - both OS9 and OSX.
27421 **
27422 ** Third-party implementations of AFP are available.  But this code here
27423 ** only works on OSX.
27424 */
27425 
27426 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27427 /*
27428 ** The afpLockingContext structure contains all afp lock specific state
27429 */
27430 typedef struct afpLockingContext afpLockingContext;
27431 struct afpLockingContext {
27432   int reserved;
27433   const char *dbPath;             /* Name of the open file */
27434 };
27435 
27436 struct ByteRangeLockPB2
27437 {
27438   unsigned long long offset;        /* offset to first byte to lock */
27439   unsigned long long length;        /* nbr of bytes to lock */
27440   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
27441   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
27442   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
27443   int fd;                           /* file desc to assoc this lock with */
27444 };
27445 
27446 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
27447 
27448 /*
27449 ** This is a utility for setting or clearing a bit-range lock on an
27450 ** AFP filesystem.
27451 **
27452 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
27453 */
27454 static int afpSetLock(
27455   const char *path,              /* Name of the file to be locked or unlocked */
27456   unixFile *pFile,               /* Open file descriptor on path */
27457   unsigned long long offset,     /* First byte to be locked */
27458   unsigned long long length,     /* Number of bytes to lock */
27459   int setLockFlag                /* True to set lock.  False to clear lock */
27460 ){
27461   struct ByteRangeLockPB2 pb;
27462   int err;
27463 
27464   pb.unLockFlag = setLockFlag ? 0 : 1;
27465   pb.startEndFlag = 0;
27466   pb.offset = offset;
27467   pb.length = length;
27468   pb.fd = pFile->h;
27469 
27470   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
27471     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
27472     offset, length));
27473   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
27474   if ( err==-1 ) {
27475     int rc;
27476     int tErrno = errno;
27477     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
27478              path, tErrno, strerror(tErrno)));
27479 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
27480     rc = SQLITE_BUSY;
27481 #else
27482     rc = sqliteErrorFromPosixError(tErrno,
27483                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
27484 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
27485     if( IS_LOCK_ERROR(rc) ){
27486       pFile->lastErrno = tErrno;
27487     }
27488     return rc;
27489   } else {
27490     return SQLITE_OK;
27491   }
27492 }
27493 
27494 /*
27495 ** This routine checks if there is a RESERVED lock held on the specified
27496 ** file by this or any other process. If such a lock is held, set *pResOut
27497 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
27498 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27499 */
27500 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
27501   int rc = SQLITE_OK;
27502   int reserved = 0;
27503   unixFile *pFile = (unixFile*)id;
27504   afpLockingContext *context;
27505 
27506   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27507 
27508   assert( pFile );
27509   context = (afpLockingContext *) pFile->lockingContext;
27510   if( context->reserved ){
27511     *pResOut = 1;
27512     return SQLITE_OK;
27513   }
27514   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
27515 
27516   /* Check if a thread in this process holds such a lock */
27517   if( pFile->pInode->eFileLock>SHARED_LOCK ){
27518     reserved = 1;
27519   }
27520 
27521   /* Otherwise see if some other process holds it.
27522    */
27523   if( !reserved ){
27524     /* lock the RESERVED byte */
27525     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
27526     if( SQLITE_OK==lrc ){
27527       /* if we succeeded in taking the reserved lock, unlock it to restore
27528       ** the original state */
27529       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
27530     } else {
27531       /* if we failed to get the lock then someone else must have it */
27532       reserved = 1;
27533     }
27534     if( IS_LOCK_ERROR(lrc) ){
27535       rc=lrc;
27536     }
27537   }
27538 
27539   unixLeaveMutex();
27540   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
27541 
27542   *pResOut = reserved;
27543   return rc;
27544 }
27545 
27546 /*
27547 ** Lock the file with the lock specified by parameter eFileLock - one
27548 ** of the following:
27549 **
27550 **     (1) SHARED_LOCK
27551 **     (2) RESERVED_LOCK
27552 **     (3) PENDING_LOCK
27553 **     (4) EXCLUSIVE_LOCK
27554 **
27555 ** Sometimes when requesting one lock state, additional lock states
27556 ** are inserted in between.  The locking might fail on one of the later
27557 ** transitions leaving the lock state different from what it started but
27558 ** still short of its goal.  The following chart shows the allowed
27559 ** transitions and the inserted intermediate states:
27560 **
27561 **    UNLOCKED -> SHARED
27562 **    SHARED -> RESERVED
27563 **    SHARED -> (PENDING) -> EXCLUSIVE
27564 **    RESERVED -> (PENDING) -> EXCLUSIVE
27565 **    PENDING -> EXCLUSIVE
27566 **
27567 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27568 ** routine to lower a locking level.
27569 */
27570 static int afpLock(sqlite3_file *id, int eFileLock){
27571   int rc = SQLITE_OK;
27572   unixFile *pFile = (unixFile*)id;
27573   unixInodeInfo *pInode = pFile->pInode;
27574   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
27575 
27576   assert( pFile );
27577   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
27578            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
27579            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
27580 
27581   /* If there is already a lock of this type or more restrictive on the
27582   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
27583   ** unixEnterMutex() hasn't been called yet.
27584   */
27585   if( pFile->eFileLock>=eFileLock ){
27586     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
27587            azFileLock(eFileLock)));
27588     return SQLITE_OK;
27589   }
27590 
27591   /* Make sure the locking sequence is correct
27592   **  (1) We never move from unlocked to anything higher than shared lock.
27593   **  (2) SQLite never explicitly requests a pendig lock.
27594   **  (3) A shared lock is always held when a reserve lock is requested.
27595   */
27596   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
27597   assert( eFileLock!=PENDING_LOCK );
27598   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
27599 
27600   /* This mutex is needed because pFile->pInode is shared across threads
27601   */
27602   unixEnterMutex();
27603   pInode = pFile->pInode;
27604 
27605   /* If some thread using this PID has a lock via a different unixFile*
27606   ** handle that precludes the requested lock, return BUSY.
27607   */
27608   if( (pFile->eFileLock!=pInode->eFileLock &&
27609        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
27610      ){
27611     rc = SQLITE_BUSY;
27612     goto afp_end_lock;
27613   }
27614 
27615   /* If a SHARED lock is requested, and some thread using this PID already
27616   ** has a SHARED or RESERVED lock, then increment reference counts and
27617   ** return SQLITE_OK.
27618   */
27619   if( eFileLock==SHARED_LOCK &&
27620      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
27621     assert( eFileLock==SHARED_LOCK );
27622     assert( pFile->eFileLock==0 );
27623     assert( pInode->nShared>0 );
27624     pFile->eFileLock = SHARED_LOCK;
27625     pInode->nShared++;
27626     pInode->nLock++;
27627     goto afp_end_lock;
27628   }
27629 
27630   /* A PENDING lock is needed before acquiring a SHARED lock and before
27631   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
27632   ** be released.
27633   */
27634   if( eFileLock==SHARED_LOCK
27635       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
27636   ){
27637     int failed;
27638     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
27639     if (failed) {
27640       rc = failed;
27641       goto afp_end_lock;
27642     }
27643   }
27644 
27645   /* If control gets to this point, then actually go ahead and make
27646   ** operating system calls for the specified lock.
27647   */
27648   if( eFileLock==SHARED_LOCK ){
27649     int lrc1, lrc2, lrc1Errno = 0;
27650     long lk, mask;
27651 
27652     assert( pInode->nShared==0 );
27653     assert( pInode->eFileLock==0 );
27654 
27655     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
27656     /* Now get the read-lock SHARED_LOCK */
27657     /* note that the quality of the randomness doesn't matter that much */
27658     lk = random();
27659     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
27660     lrc1 = afpSetLock(context->dbPath, pFile,
27661           SHARED_FIRST+pInode->sharedByte, 1, 1);
27662     if( IS_LOCK_ERROR(lrc1) ){
27663       lrc1Errno = pFile->lastErrno;
27664     }
27665     /* Drop the temporary PENDING lock */
27666     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
27667 
27668     if( IS_LOCK_ERROR(lrc1) ) {
27669       pFile->lastErrno = lrc1Errno;
27670       rc = lrc1;
27671       goto afp_end_lock;
27672     } else if( IS_LOCK_ERROR(lrc2) ){
27673       rc = lrc2;
27674       goto afp_end_lock;
27675     } else if( lrc1 != SQLITE_OK ) {
27676       rc = lrc1;
27677     } else {
27678       pFile->eFileLock = SHARED_LOCK;
27679       pInode->nLock++;
27680       pInode->nShared = 1;
27681     }
27682   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
27683     /* We are trying for an exclusive lock but another thread in this
27684      ** same process is still holding a shared lock. */
27685     rc = SQLITE_BUSY;
27686   }else{
27687     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
27688     ** assumed that there is a SHARED or greater lock on the file
27689     ** already.
27690     */
27691     int failed = 0;
27692     assert( 0!=pFile->eFileLock );
27693     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
27694         /* Acquire a RESERVED lock */
27695         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
27696       if( !failed ){
27697         context->reserved = 1;
27698       }
27699     }
27700     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
27701       /* Acquire an EXCLUSIVE lock */
27702 
27703       /* Remove the shared lock before trying the range.  we'll need to
27704       ** reestablish the shared lock if we can't get the  afpUnlock
27705       */
27706       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
27707                          pInode->sharedByte, 1, 0)) ){
27708         int failed2 = SQLITE_OK;
27709         /* now attemmpt to get the exclusive lock range */
27710         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
27711                                SHARED_SIZE, 1);
27712         if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
27713                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
27714           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
27715           ** a critical I/O error
27716           */
27717           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
27718                SQLITE_IOERR_LOCK;
27719           goto afp_end_lock;
27720         }
27721       }else{
27722         rc = failed;
27723       }
27724     }
27725     if( failed ){
27726       rc = failed;
27727     }
27728   }
27729 
27730   if( rc==SQLITE_OK ){
27731     pFile->eFileLock = eFileLock;
27732     pInode->eFileLock = eFileLock;
27733   }else if( eFileLock==EXCLUSIVE_LOCK ){
27734     pFile->eFileLock = PENDING_LOCK;
27735     pInode->eFileLock = PENDING_LOCK;
27736   }
27737 
27738 afp_end_lock:
27739   unixLeaveMutex();
27740   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
27741          rc==SQLITE_OK ? "ok" : "failed"));
27742   return rc;
27743 }
27744 
27745 /*
27746 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27747 ** must be either NO_LOCK or SHARED_LOCK.
27748 **
27749 ** If the locking level of the file descriptor is already at or below
27750 ** the requested locking level, this routine is a no-op.
27751 */
27752 static int afpUnlock(sqlite3_file *id, int eFileLock) {
27753   int rc = SQLITE_OK;
27754   unixFile *pFile = (unixFile*)id;
27755   unixInodeInfo *pInode;
27756   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
27757   int skipShared = 0;
27758 #ifdef SQLITE_TEST
27759   int h = pFile->h;
27760 #endif
27761 
27762   assert( pFile );
27763   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
27764            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
27765            getpid()));
27766 
27767   assert( eFileLock<=SHARED_LOCK );
27768   if( pFile->eFileLock<=eFileLock ){
27769     return SQLITE_OK;
27770   }
27771   unixEnterMutex();
27772   pInode = pFile->pInode;
27773   assert( pInode->nShared!=0 );
27774   if( pFile->eFileLock>SHARED_LOCK ){
27775     assert( pInode->eFileLock==pFile->eFileLock );
27776     SimulateIOErrorBenign(1);
27777     SimulateIOError( h=(-1) )
27778     SimulateIOErrorBenign(0);
27779 
27780 #ifdef SQLITE_DEBUG
27781     /* When reducing a lock such that other processes can start
27782     ** reading the database file again, make sure that the
27783     ** transaction counter was updated if any part of the database
27784     ** file changed.  If the transaction counter is not updated,
27785     ** other connections to the same file might not realize that
27786     ** the file has changed and hence might not know to flush their
27787     ** cache.  The use of a stale cache can lead to database corruption.
27788     */
27789     assert( pFile->inNormalWrite==0
27790            || pFile->dbUpdate==0
27791            || pFile->transCntrChng==1 );
27792     pFile->inNormalWrite = 0;
27793 #endif
27794 
27795     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
27796       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
27797       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
27798         /* only re-establish the shared lock if necessary */
27799         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
27800         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
27801       } else {
27802         skipShared = 1;
27803       }
27804     }
27805     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
27806       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
27807     }
27808     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
27809       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
27810       if( !rc ){
27811         context->reserved = 0;
27812       }
27813     }
27814     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
27815       pInode->eFileLock = SHARED_LOCK;
27816     }
27817   }
27818   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
27819 
27820     /* Decrement the shared lock counter.  Release the lock using an
27821     ** OS call only when all threads in this same process have released
27822     ** the lock.
27823     */
27824     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
27825     pInode->nShared--;
27826     if( pInode->nShared==0 ){
27827       SimulateIOErrorBenign(1);
27828       SimulateIOError( h=(-1) )
27829       SimulateIOErrorBenign(0);
27830       if( !skipShared ){
27831         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
27832       }
27833       if( !rc ){
27834         pInode->eFileLock = NO_LOCK;
27835         pFile->eFileLock = NO_LOCK;
27836       }
27837     }
27838     if( rc==SQLITE_OK ){
27839       pInode->nLock--;
27840       assert( pInode->nLock>=0 );
27841       if( pInode->nLock==0 ){
27842         closePendingFds(pFile);
27843       }
27844     }
27845   }
27846 
27847   unixLeaveMutex();
27848   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
27849   return rc;
27850 }
27851 
27852 /*
27853 ** Close a file & cleanup AFP specific locking context
27854 */
27855 static int afpClose(sqlite3_file *id) {
27856   int rc = SQLITE_OK;
27857   if( id ){
27858     unixFile *pFile = (unixFile*)id;
27859     afpUnlock(id, NO_LOCK);
27860     unixEnterMutex();
27861     if( pFile->pInode && pFile->pInode->nLock ){
27862       /* If there are outstanding locks, do not actually close the file just
27863       ** yet because that would clear those locks.  Instead, add the file
27864       ** descriptor to pInode->aPending.  It will be automatically closed when
27865       ** the last lock is cleared.
27866       */
27867       setPendingFd(pFile);
27868     }
27869     releaseInodeInfo(pFile);
27870     sqlite3_free(pFile->lockingContext);
27871     rc = closeUnixFile(id);
27872     unixLeaveMutex();
27873   }
27874   return rc;
27875 }
27876 
27877 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27878 /*
27879 ** The code above is the AFP lock implementation.  The code is specific
27880 ** to MacOSX and does not work on other unix platforms.  No alternative
27881 ** is available.  If you don't compile for a mac, then the "unix-afp"
27882 ** VFS is not available.
27883 **
27884 ********************* End of the AFP lock implementation **********************
27885 ******************************************************************************/
27886 
27887 /******************************************************************************
27888 *************************** Begin NFS Locking ********************************/
27889 
27890 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27891 /*
27892  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27893  ** must be either NO_LOCK or SHARED_LOCK.
27894  **
27895  ** If the locking level of the file descriptor is already at or below
27896  ** the requested locking level, this routine is a no-op.
27897  */
27898 static int nfsUnlock(sqlite3_file *id, int eFileLock){
27899   return posixUnlock(id, eFileLock, 1);
27900 }
27901 
27902 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27903 /*
27904 ** The code above is the NFS lock implementation.  The code is specific
27905 ** to MacOSX and does not work on other unix platforms.  No alternative
27906 ** is available.
27907 **
27908 ********************* End of the NFS lock implementation **********************
27909 ******************************************************************************/
27910 
27911 /******************************************************************************
27912 **************** Non-locking sqlite3_file methods *****************************
27913 **
27914 ** The next division contains implementations for all methods of the
27915 ** sqlite3_file object other than the locking methods.  The locking
27916 ** methods were defined in divisions above (one locking method per
27917 ** division).  Those methods that are common to all locking modes
27918 ** are gather together into this division.
27919 */
27920 
27921 /*
27922 ** Seek to the offset passed as the second argument, then read cnt
27923 ** bytes into pBuf. Return the number of bytes actually read.
27924 **
27925 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
27926 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
27927 ** one system to another.  Since SQLite does not define USE_PREAD
27928 ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
27929 ** See tickets #2741 and #2681.
27930 **
27931 ** To avoid stomping the errno value on a failed read the lastErrno value
27932 ** is set before returning.
27933 */
27934 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
27935   int got;
27936   int prior = 0;
27937 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
27938   i64 newOffset;
27939 #endif
27940   TIMER_START;
27941   assert( cnt==(cnt&0x1ffff) );
27942   assert( id->h>2 );
27943   cnt &= 0x1ffff;
27944   do{
27945 #if defined(USE_PREAD)
27946     got = osPread(id->h, pBuf, cnt, offset);
27947     SimulateIOError( got = -1 );
27948 #elif defined(USE_PREAD64)
27949     got = osPread64(id->h, pBuf, cnt, offset);
27950     SimulateIOError( got = -1 );
27951 #else
27952     newOffset = lseek(id->h, offset, SEEK_SET);
27953     SimulateIOError( newOffset-- );
27954     if( newOffset!=offset ){
27955       if( newOffset == -1 ){
27956         ((unixFile*)id)->lastErrno = errno;
27957       }else{
27958         ((unixFile*)id)->lastErrno = 0;
27959       }
27960       return -1;
27961     }
27962     got = osRead(id->h, pBuf, cnt);
27963 #endif
27964     if( got==cnt ) break;
27965     if( got<0 ){
27966       if( errno==EINTR ){ got = 1; continue; }
27967       prior = 0;
27968       ((unixFile*)id)->lastErrno = errno;
27969       break;
27970     }else if( got>0 ){
27971       cnt -= got;
27972       offset += got;
27973       prior += got;
27974       pBuf = (void*)(got + (char*)pBuf);
27975     }
27976   }while( got>0 );
27977   TIMER_END;
27978   OSTRACE(("READ    %-3d %5d %7lld %llu\n",
27979             id->h, got+prior, offset-prior, TIMER_ELAPSED));
27980   return got+prior;
27981 }
27982 
27983 /*
27984 ** Read data from a file into a buffer.  Return SQLITE_OK if all
27985 ** bytes were read successfully and SQLITE_IOERR if anything goes
27986 ** wrong.
27987 */
27988 static int unixRead(
27989   sqlite3_file *id,
27990   void *pBuf,
27991   int amt,
27992   sqlite3_int64 offset
27993 ){
27994   unixFile *pFile = (unixFile *)id;
27995   int got;
27996   assert( id );
27997   assert( offset>=0 );
27998   assert( amt>0 );
27999 
28000   /* If this is a database file (not a journal, master-journal or temp
28001   ** file), the bytes in the locking range should never be read or written. */
28002 #if 0
28003   assert( pFile->pUnused==0
28004        || offset>=PENDING_BYTE+512
28005        || offset+amt<=PENDING_BYTE
28006   );
28007 #endif
28008 
28009 #if SQLITE_MAX_MMAP_SIZE>0
28010   /* Deal with as much of this read request as possible by transfering
28011   ** data from the memory mapping using memcpy().  */
28012   if( offset<pFile->mmapSize ){
28013     if( offset+amt <= pFile->mmapSize ){
28014       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
28015       return SQLITE_OK;
28016     }else{
28017       int nCopy = pFile->mmapSize - offset;
28018       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
28019       pBuf = &((u8 *)pBuf)[nCopy];
28020       amt -= nCopy;
28021       offset += nCopy;
28022     }
28023   }
28024 #endif
28025 
28026   got = seekAndRead(pFile, offset, pBuf, amt);
28027   if( got==amt ){
28028     return SQLITE_OK;
28029   }else if( got<0 ){
28030     /* lastErrno set by seekAndRead */
28031     return SQLITE_IOERR_READ;
28032   }else{
28033     pFile->lastErrno = 0; /* not a system error */
28034     /* Unread parts of the buffer must be zero-filled */
28035     memset(&((char*)pBuf)[got], 0, amt-got);
28036     return SQLITE_IOERR_SHORT_READ;
28037   }
28038 }
28039 
28040 /*
28041 ** Attempt to seek the file-descriptor passed as the first argument to
28042 ** absolute offset iOff, then attempt to write nBuf bytes of data from
28043 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
28044 ** return the actual number of bytes written (which may be less than
28045 ** nBuf).
28046 */
28047 static int seekAndWriteFd(
28048   int fd,                         /* File descriptor to write to */
28049   i64 iOff,                       /* File offset to begin writing at */
28050   const void *pBuf,               /* Copy data from this buffer to the file */
28051   int nBuf,                       /* Size of buffer pBuf in bytes */
28052   int *piErrno                    /* OUT: Error number if error occurs */
28053 ){
28054   int rc = 0;                     /* Value returned by system call */
28055 
28056   assert( nBuf==(nBuf&0x1ffff) );
28057   assert( fd>2 );
28058   nBuf &= 0x1ffff;
28059   TIMER_START;
28060 
28061 #if defined(USE_PREAD)
28062   do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
28063 #elif defined(USE_PREAD64)
28064   do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
28065 #else
28066   do{
28067     i64 iSeek = lseek(fd, iOff, SEEK_SET);
28068     SimulateIOError( iSeek-- );
28069 
28070     if( iSeek!=iOff ){
28071       if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
28072       return -1;
28073     }
28074     rc = osWrite(fd, pBuf, nBuf);
28075   }while( rc<0 && errno==EINTR );
28076 #endif
28077 
28078   TIMER_END;
28079   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
28080 
28081   if( rc<0 && piErrno ) *piErrno = errno;
28082   return rc;
28083 }
28084 
28085 
28086 /*
28087 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
28088 ** Return the number of bytes actually read.  Update the offset.
28089 **
28090 ** To avoid stomping the errno value on a failed write the lastErrno value
28091 ** is set before returning.
28092 */
28093 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
28094   return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
28095 }
28096 
28097 
28098 /*
28099 ** Write data from a buffer into a file.  Return SQLITE_OK on success
28100 ** or some other error code on failure.
28101 */
28102 static int unixWrite(
28103   sqlite3_file *id,
28104   const void *pBuf,
28105   int amt,
28106   sqlite3_int64 offset
28107 ){
28108   unixFile *pFile = (unixFile*)id;
28109   int wrote = 0;
28110   assert( id );
28111   assert( amt>0 );
28112 
28113   /* If this is a database file (not a journal, master-journal or temp
28114   ** file), the bytes in the locking range should never be read or written. */
28115 #if 0
28116   assert( pFile->pUnused==0
28117        || offset>=PENDING_BYTE+512
28118        || offset+amt<=PENDING_BYTE
28119   );
28120 #endif
28121 
28122 #ifdef SQLITE_DEBUG
28123   /* If we are doing a normal write to a database file (as opposed to
28124   ** doing a hot-journal rollback or a write to some file other than a
28125   ** normal database file) then record the fact that the database
28126   ** has changed.  If the transaction counter is modified, record that
28127   ** fact too.
28128   */
28129   if( pFile->inNormalWrite ){
28130     pFile->dbUpdate = 1;  /* The database has been modified */
28131     if( offset<=24 && offset+amt>=27 ){
28132       int rc;
28133       char oldCntr[4];
28134       SimulateIOErrorBenign(1);
28135       rc = seekAndRead(pFile, 24, oldCntr, 4);
28136       SimulateIOErrorBenign(0);
28137       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
28138         pFile->transCntrChng = 1;  /* The transaction counter has changed */
28139       }
28140     }
28141   }
28142 #endif
28143 
28144 #if SQLITE_MAX_MMAP_SIZE>0
28145   /* Deal with as much of this write request as possible by transfering
28146   ** data from the memory mapping using memcpy().  */
28147   if( offset<pFile->mmapSize ){
28148     if( offset+amt <= pFile->mmapSize ){
28149       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
28150       return SQLITE_OK;
28151     }else{
28152       int nCopy = pFile->mmapSize - offset;
28153       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
28154       pBuf = &((u8 *)pBuf)[nCopy];
28155       amt -= nCopy;
28156       offset += nCopy;
28157     }
28158   }
28159 #endif
28160 
28161   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
28162     amt -= wrote;
28163     offset += wrote;
28164     pBuf = &((char*)pBuf)[wrote];
28165   }
28166   SimulateIOError(( wrote=(-1), amt=1 ));
28167   SimulateDiskfullError(( wrote=0, amt=1 ));
28168 
28169   if( amt>0 ){
28170     if( wrote<0 && pFile->lastErrno!=ENOSPC ){
28171       /* lastErrno set by seekAndWrite */
28172       return SQLITE_IOERR_WRITE;
28173     }else{
28174       pFile->lastErrno = 0; /* not a system error */
28175       return SQLITE_FULL;
28176     }
28177   }
28178 
28179   return SQLITE_OK;
28180 }
28181 
28182 #ifdef SQLITE_TEST
28183 /*
28184 ** Count the number of fullsyncs and normal syncs.  This is used to test
28185 ** that syncs and fullsyncs are occurring at the right times.
28186 */
28187 SQLITE_API int sqlite3_sync_count = 0;
28188 SQLITE_API int sqlite3_fullsync_count = 0;
28189 #endif
28190 
28191 /*
28192 ** We do not trust systems to provide a working fdatasync().  Some do.
28193 ** Others do no.  To be safe, we will stick with the (slightly slower)
28194 ** fsync(). If you know that your system does support fdatasync() correctly,
28195 ** then simply compile with -Dfdatasync=fdatasync
28196 */
28197 #if !defined(fdatasync)
28198 # define fdatasync fsync
28199 #endif
28200 
28201 /*
28202 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
28203 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
28204 ** only available on Mac OS X.  But that could change.
28205 */
28206 #ifdef F_FULLFSYNC
28207 # define HAVE_FULLFSYNC 1
28208 #else
28209 # define HAVE_FULLFSYNC 0
28210 #endif
28211 
28212 
28213 /*
28214 ** The fsync() system call does not work as advertised on many
28215 ** unix systems.  The following procedure is an attempt to make
28216 ** it work better.
28217 **
28218 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
28219 ** for testing when we want to run through the test suite quickly.
28220 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
28221 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
28222 ** or power failure will likely corrupt the database file.
28223 **
28224 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
28225 ** The idea behind dataOnly is that it should only write the file content
28226 ** to disk, not the inode.  We only set dataOnly if the file size is
28227 ** unchanged since the file size is part of the inode.  However,
28228 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
28229 ** file size has changed.  The only real difference between fdatasync()
28230 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
28231 ** inode if the mtime or owner or other inode attributes have changed.
28232 ** We only care about the file size, not the other file attributes, so
28233 ** as far as SQLite is concerned, an fdatasync() is always adequate.
28234 ** So, we always use fdatasync() if it is available, regardless of
28235 ** the value of the dataOnly flag.
28236 */
28237 static int full_fsync(int fd, int fullSync, int dataOnly){
28238   int rc;
28239 
28240   /* The following "ifdef/elif/else/" block has the same structure as
28241   ** the one below. It is replicated here solely to avoid cluttering
28242   ** up the real code with the UNUSED_PARAMETER() macros.
28243   */
28244 #ifdef SQLITE_NO_SYNC
28245   UNUSED_PARAMETER(fd);
28246   UNUSED_PARAMETER(fullSync);
28247   UNUSED_PARAMETER(dataOnly);
28248 #elif HAVE_FULLFSYNC
28249   UNUSED_PARAMETER(dataOnly);
28250 #else
28251   UNUSED_PARAMETER(fullSync);
28252   UNUSED_PARAMETER(dataOnly);
28253 #endif
28254 
28255   /* Record the number of times that we do a normal fsync() and
28256   ** FULLSYNC.  This is used during testing to verify that this procedure
28257   ** gets called with the correct arguments.
28258   */
28259 #ifdef SQLITE_TEST
28260   if( fullSync ) sqlite3_fullsync_count++;
28261   sqlite3_sync_count++;
28262 #endif
28263 
28264   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
28265   ** no-op
28266   */
28267 #ifdef SQLITE_NO_SYNC
28268   rc = SQLITE_OK;
28269 #elif HAVE_FULLFSYNC
28270   if( fullSync ){
28271     rc = osFcntl(fd, F_FULLFSYNC, 0);
28272   }else{
28273     rc = 1;
28274   }
28275   /* If the FULLFSYNC failed, fall back to attempting an fsync().
28276   ** It shouldn't be possible for fullfsync to fail on the local
28277   ** file system (on OSX), so failure indicates that FULLFSYNC
28278   ** isn't supported for this file system. So, attempt an fsync
28279   ** and (for now) ignore the overhead of a superfluous fcntl call.
28280   ** It'd be better to detect fullfsync support once and avoid
28281   ** the fcntl call every time sync is called.
28282   */
28283   if( rc ) rc = fsync(fd);
28284 
28285 #elif defined(__APPLE__)
28286   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
28287   ** so currently we default to the macro that redefines fdatasync to fsync
28288   */
28289   rc = fsync(fd);
28290 #else
28291   rc = fdatasync(fd);
28292 #if OS_VXWORKS
28293   if( rc==-1 && errno==ENOTSUP ){
28294     rc = fsync(fd);
28295   }
28296 #endif /* OS_VXWORKS */
28297 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
28298 
28299   if( OS_VXWORKS && rc!= -1 ){
28300     rc = 0;
28301   }
28302   return rc;
28303 }
28304 
28305 /*
28306 ** Open a file descriptor to the directory containing file zFilename.
28307 ** If successful, *pFd is set to the opened file descriptor and
28308 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
28309 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
28310 ** value.
28311 **
28312 ** The directory file descriptor is used for only one thing - to
28313 ** fsync() a directory to make sure file creation and deletion events
28314 ** are flushed to disk.  Such fsyncs are not needed on newer
28315 ** journaling filesystems, but are required on older filesystems.
28316 **
28317 ** This routine can be overridden using the xSetSysCall interface.
28318 ** The ability to override this routine was added in support of the
28319 ** chromium sandbox.  Opening a directory is a security risk (we are
28320 ** told) so making it overrideable allows the chromium sandbox to
28321 ** replace this routine with a harmless no-op.  To make this routine
28322 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
28323 ** *pFd set to a negative number.
28324 **
28325 ** If SQLITE_OK is returned, the caller is responsible for closing
28326 ** the file descriptor *pFd using close().
28327 */
28328 static int openDirectory(const char *zFilename, int *pFd){
28329   int ii;
28330   int fd = -1;
28331   char zDirname[MAX_PATHNAME+1];
28332 
28333   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
28334   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
28335   if( ii>0 ){
28336     zDirname[ii] = '\0';
28337     fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
28338     if( fd>=0 ){
28339       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
28340     }
28341   }
28342   *pFd = fd;
28343   return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
28344 }
28345 
28346 /*
28347 ** Make sure all writes to a particular file are committed to disk.
28348 **
28349 ** If dataOnly==0 then both the file itself and its metadata (file
28350 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
28351 ** file data is synced.
28352 **
28353 ** Under Unix, also make sure that the directory entry for the file
28354 ** has been created by fsync-ing the directory that contains the file.
28355 ** If we do not do this and we encounter a power failure, the directory
28356 ** entry for the journal might not exist after we reboot.  The next
28357 ** SQLite to access the file will not know that the journal exists (because
28358 ** the directory entry for the journal was never created) and the transaction
28359 ** will not roll back - possibly leading to database corruption.
28360 */
28361 static int unixSync(sqlite3_file *id, int flags){
28362   int rc;
28363   unixFile *pFile = (unixFile*)id;
28364 
28365   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
28366   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
28367 
28368   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
28369   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
28370       || (flags&0x0F)==SQLITE_SYNC_FULL
28371   );
28372 
28373   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
28374   ** line is to test that doing so does not cause any problems.
28375   */
28376   SimulateDiskfullError( return SQLITE_FULL );
28377 
28378   assert( pFile );
28379   OSTRACE(("SYNC    %-3d\n", pFile->h));
28380   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
28381   SimulateIOError( rc=1 );
28382   if( rc ){
28383     pFile->lastErrno = errno;
28384     return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
28385   }
28386 
28387   /* Also fsync the directory containing the file if the DIRSYNC flag
28388   ** is set.  This is a one-time occurrence.  Many systems (examples: AIX)
28389   ** are unable to fsync a directory, so ignore errors on the fsync.
28390   */
28391   if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
28392     int dirfd;
28393     OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
28394             HAVE_FULLFSYNC, isFullsync));
28395     rc = osOpenDirectory(pFile->zPath, &dirfd);
28396     if( rc==SQLITE_OK && dirfd>=0 ){
28397       full_fsync(dirfd, 0, 0);
28398       robust_close(pFile, dirfd, __LINE__);
28399     }else if( rc==SQLITE_CANTOPEN ){
28400       rc = SQLITE_OK;
28401     }
28402     pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
28403   }
28404   return rc;
28405 }
28406 
28407 /*
28408 ** Truncate an open file to a specified size
28409 */
28410 static int unixTruncate(sqlite3_file *id, i64 nByte){
28411   unixFile *pFile = (unixFile *)id;
28412   int rc;
28413   assert( pFile );
28414   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
28415 
28416   /* If the user has configured a chunk-size for this file, truncate the
28417   ** file so that it consists of an integer number of chunks (i.e. the
28418   ** actual file size after the operation may be larger than the requested
28419   ** size).
28420   */
28421   if( pFile->szChunk>0 ){
28422     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
28423   }
28424 
28425   rc = robust_ftruncate(pFile->h, nByte);
28426   if( rc ){
28427     pFile->lastErrno = errno;
28428     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
28429   }else{
28430 #ifdef SQLITE_DEBUG
28431     /* If we are doing a normal write to a database file (as opposed to
28432     ** doing a hot-journal rollback or a write to some file other than a
28433     ** normal database file) and we truncate the file to zero length,
28434     ** that effectively updates the change counter.  This might happen
28435     ** when restoring a database using the backup API from a zero-length
28436     ** source.
28437     */
28438     if( pFile->inNormalWrite && nByte==0 ){
28439       pFile->transCntrChng = 1;
28440     }
28441 #endif
28442 
28443 #if SQLITE_MAX_MMAP_SIZE>0
28444     /* If the file was just truncated to a size smaller than the currently
28445     ** mapped region, reduce the effective mapping size as well. SQLite will
28446     ** use read() and write() to access data beyond this point from now on.
28447     */
28448     if( nByte<pFile->mmapSize ){
28449       pFile->mmapSize = nByte;
28450     }
28451 #endif
28452 
28453     return SQLITE_OK;
28454   }
28455 }
28456 
28457 /*
28458 ** Determine the current size of a file in bytes
28459 */
28460 static int unixFileSize(sqlite3_file *id, i64 *pSize){
28461   int rc;
28462   struct stat buf;
28463   assert( id );
28464   rc = osFstat(((unixFile*)id)->h, &buf);
28465   SimulateIOError( rc=1 );
28466   if( rc!=0 ){
28467     ((unixFile*)id)->lastErrno = errno;
28468     return SQLITE_IOERR_FSTAT;
28469   }
28470   *pSize = buf.st_size;
28471 
28472   /* When opening a zero-size database, the findInodeInfo() procedure
28473   ** writes a single byte into that file in order to work around a bug
28474   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
28475   ** layers, we need to report this file size as zero even though it is
28476   ** really 1.   Ticket #3260.
28477   */
28478   if( *pSize==1 ) *pSize = 0;
28479 
28480 
28481   return SQLITE_OK;
28482 }
28483 
28484 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28485 /*
28486 ** Handler for proxy-locking file-control verbs.  Defined below in the
28487 ** proxying locking division.
28488 */
28489 static int proxyFileControl(sqlite3_file*,int,void*);
28490 #endif
28491 
28492 /*
28493 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
28494 ** file-control operation.  Enlarge the database to nBytes in size
28495 ** (rounded up to the next chunk-size).  If the database is already
28496 ** nBytes or larger, this routine is a no-op.
28497 */
28498 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
28499   if( pFile->szChunk>0 ){
28500     i64 nSize;                    /* Required file size */
28501     struct stat buf;              /* Used to hold return values of fstat() */
28502 
28503     if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
28504 
28505     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
28506     if( nSize>(i64)buf.st_size ){
28507 
28508 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
28509       /* The code below is handling the return value of osFallocate()
28510       ** correctly. posix_fallocate() is defined to "returns zero on success,
28511       ** or an error number on  failure". See the manpage for details. */
28512       int err;
28513       do{
28514         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
28515       }while( err==EINTR );
28516       if( err ) return SQLITE_IOERR_WRITE;
28517 #else
28518       /* If the OS does not have posix_fallocate(), fake it. First use
28519       ** ftruncate() to set the file size, then write a single byte to
28520       ** the last byte in each block within the extended region. This
28521       ** is the same technique used by glibc to implement posix_fallocate()
28522       ** on systems that do not have a real fallocate() system call.
28523       */
28524       int nBlk = buf.st_blksize;  /* File-system block size */
28525       i64 iWrite;                 /* Next offset to write to */
28526 
28527       if( robust_ftruncate(pFile->h, nSize) ){
28528         pFile->lastErrno = errno;
28529         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
28530       }
28531       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
28532       while( iWrite<nSize ){
28533         int nWrite = seekAndWrite(pFile, iWrite, "", 1);
28534         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
28535         iWrite += nBlk;
28536       }
28537 #endif
28538     }
28539   }
28540 
28541 #if SQLITE_MAX_MMAP_SIZE>0
28542   if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
28543     int rc;
28544     if( pFile->szChunk<=0 ){
28545       if( robust_ftruncate(pFile->h, nByte) ){
28546         pFile->lastErrno = errno;
28547         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
28548       }
28549     }
28550 
28551     rc = unixMapfile(pFile, nByte);
28552     return rc;
28553   }
28554 #endif
28555 
28556   return SQLITE_OK;
28557 }
28558 
28559 /*
28560 ** If *pArg is initially negative then this is a query.  Set *pArg to
28561 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
28562 **
28563 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
28564 */
28565 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
28566   if( *pArg<0 ){
28567     *pArg = (pFile->ctrlFlags & mask)!=0;
28568   }else if( (*pArg)==0 ){
28569     pFile->ctrlFlags &= ~mask;
28570   }else{
28571     pFile->ctrlFlags |= mask;
28572   }
28573 }
28574 
28575 /* Forward declaration */
28576 static int unixGetTempname(int nBuf, char *zBuf);
28577 
28578 /*
28579 ** Information and control of an open file handle.
28580 */
28581 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
28582   unixFile *pFile = (unixFile*)id;
28583   switch( op ){
28584     case SQLITE_FCNTL_LOCKSTATE: {
28585       *(int*)pArg = pFile->eFileLock;
28586       return SQLITE_OK;
28587     }
28588     case SQLITE_LAST_ERRNO: {
28589       *(int*)pArg = pFile->lastErrno;
28590       return SQLITE_OK;
28591     }
28592     case SQLITE_FCNTL_CHUNK_SIZE: {
28593       pFile->szChunk = *(int *)pArg;
28594       return SQLITE_OK;
28595     }
28596     case SQLITE_FCNTL_SIZE_HINT: {
28597       int rc;
28598       SimulateIOErrorBenign(1);
28599       rc = fcntlSizeHint(pFile, *(i64 *)pArg);
28600       SimulateIOErrorBenign(0);
28601       return rc;
28602     }
28603     case SQLITE_FCNTL_PERSIST_WAL: {
28604       unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
28605       return SQLITE_OK;
28606     }
28607     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
28608       unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
28609       return SQLITE_OK;
28610     }
28611     case SQLITE_FCNTL_VFSNAME: {
28612       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
28613       return SQLITE_OK;
28614     }
28615     case SQLITE_FCNTL_TEMPFILENAME: {
28616       char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
28617       if( zTFile ){
28618         unixGetTempname(pFile->pVfs->mxPathname, zTFile);
28619         *(char**)pArg = zTFile;
28620       }
28621       return SQLITE_OK;
28622     }
28623     case SQLITE_FCNTL_HAS_MOVED: {
28624       *(int*)pArg = fileHasMoved(pFile);
28625       return SQLITE_OK;
28626     }
28627 #if SQLITE_MAX_MMAP_SIZE>0
28628     case SQLITE_FCNTL_MMAP_SIZE: {
28629       i64 newLimit = *(i64*)pArg;
28630       int rc = SQLITE_OK;
28631       if( newLimit>sqlite3GlobalConfig.mxMmap ){
28632         newLimit = sqlite3GlobalConfig.mxMmap;
28633       }
28634       *(i64*)pArg = pFile->mmapSizeMax;
28635       if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
28636         pFile->mmapSizeMax = newLimit;
28637         if( pFile->mmapSize>0 ){
28638           unixUnmapfile(pFile);
28639           rc = unixMapfile(pFile, -1);
28640         }
28641       }
28642       return rc;
28643     }
28644 #endif
28645 #ifdef SQLITE_DEBUG
28646     /* The pager calls this method to signal that it has done
28647     ** a rollback and that the database is therefore unchanged and
28648     ** it hence it is OK for the transaction change counter to be
28649     ** unchanged.
28650     */
28651     case SQLITE_FCNTL_DB_UNCHANGED: {
28652       ((unixFile*)id)->dbUpdate = 0;
28653       return SQLITE_OK;
28654     }
28655 #endif
28656 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28657     case SQLITE_SET_LOCKPROXYFILE:
28658     case SQLITE_GET_LOCKPROXYFILE: {
28659       return proxyFileControl(id,op,pArg);
28660     }
28661 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
28662   }
28663   return SQLITE_NOTFOUND;
28664 }
28665 
28666 /*
28667 ** Return the sector size in bytes of the underlying block device for
28668 ** the specified file. This is almost always 512 bytes, but may be
28669 ** larger for some devices.
28670 **
28671 ** SQLite code assumes this function cannot fail. It also assumes that
28672 ** if two files are created in the same file-system directory (i.e.
28673 ** a database and its journal file) that the sector size will be the
28674 ** same for both.
28675 */
28676 #ifndef __QNXNTO__
28677 static int unixSectorSize(sqlite3_file *NotUsed){
28678   UNUSED_PARAMETER(NotUsed);
28679   return SQLITE_DEFAULT_SECTOR_SIZE;
28680 }
28681 #endif
28682 
28683 /*
28684 ** The following version of unixSectorSize() is optimized for QNX.
28685 */
28686 #ifdef __QNXNTO__
28687 #include <sys/dcmd_blk.h>
28688 #include <sys/statvfs.h>
28689 static int unixSectorSize(sqlite3_file *id){
28690   unixFile *pFile = (unixFile*)id;
28691   if( pFile->sectorSize == 0 ){
28692     struct statvfs fsInfo;
28693 
28694     /* Set defaults for non-supported filesystems */
28695     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
28696     pFile->deviceCharacteristics = 0;
28697     if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
28698       return pFile->sectorSize;
28699     }
28700 
28701     if( !strcmp(fsInfo.f_basetype, "tmp") ) {
28702       pFile->sectorSize = fsInfo.f_bsize;
28703       pFile->deviceCharacteristics =
28704         SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
28705         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
28706                                       ** the write succeeds */
28707         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
28708                                       ** so it is ordered */
28709         0;
28710     }else if( strstr(fsInfo.f_basetype, "etfs") ){
28711       pFile->sectorSize = fsInfo.f_bsize;
28712       pFile->deviceCharacteristics =
28713         /* etfs cluster size writes are atomic */
28714         (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
28715         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
28716                                       ** the write succeeds */
28717         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
28718                                       ** so it is ordered */
28719         0;
28720     }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
28721       pFile->sectorSize = fsInfo.f_bsize;
28722       pFile->deviceCharacteristics =
28723         SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
28724         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
28725                                       ** the write succeeds */
28726         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
28727                                       ** so it is ordered */
28728         0;
28729     }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
28730       pFile->sectorSize = fsInfo.f_bsize;
28731       pFile->deviceCharacteristics =
28732         /* full bitset of atomics from max sector size and smaller */
28733         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
28734         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
28735                                       ** so it is ordered */
28736         0;
28737     }else if( strstr(fsInfo.f_basetype, "dos") ){
28738       pFile->sectorSize = fsInfo.f_bsize;
28739       pFile->deviceCharacteristics =
28740         /* full bitset of atomics from max sector size and smaller */
28741         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
28742         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
28743                                       ** so it is ordered */
28744         0;
28745     }else{
28746       pFile->deviceCharacteristics =
28747         SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
28748         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
28749                                       ** the write succeeds */
28750         0;
28751     }
28752   }
28753   /* Last chance verification.  If the sector size isn't a multiple of 512
28754   ** then it isn't valid.*/
28755   if( pFile->sectorSize % 512 != 0 ){
28756     pFile->deviceCharacteristics = 0;
28757     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
28758   }
28759   return pFile->sectorSize;
28760 }
28761 #endif /* __QNXNTO__ */
28762 
28763 /*
28764 ** Return the device characteristics for the file.
28765 **
28766 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
28767 ** However, that choice is controversial since technically the underlying
28768 ** file system does not always provide powersafe overwrites.  (In other
28769 ** words, after a power-loss event, parts of the file that were never
28770 ** written might end up being altered.)  However, non-PSOW behavior is very,
28771 ** very rare.  And asserting PSOW makes a large reduction in the amount
28772 ** of required I/O for journaling, since a lot of padding is eliminated.
28773 **  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
28774 ** available to turn it off and URI query parameter available to turn it off.
28775 */
28776 static int unixDeviceCharacteristics(sqlite3_file *id){
28777   unixFile *p = (unixFile*)id;
28778   int rc = 0;
28779 #ifdef __QNXNTO__
28780   if( p->sectorSize==0 ) unixSectorSize(id);
28781   rc = p->deviceCharacteristics;
28782 #endif
28783   if( p->ctrlFlags & UNIXFILE_PSOW ){
28784     rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
28785   }
28786   return rc;
28787 }
28788 
28789 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
28790 
28791 /*
28792 ** Return the system page size.
28793 **
28794 ** This function should not be called directly by other code in this file.
28795 ** Instead, it should be called via macro osGetpagesize().
28796 */
28797 static int unixGetpagesize(void){
28798 #if defined(_BSD_SOURCE)
28799   return getpagesize();
28800 #else
28801   return (int)sysconf(_SC_PAGESIZE);
28802 #endif
28803 }
28804 
28805 #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
28806 
28807 #ifndef SQLITE_OMIT_WAL
28808 
28809 /*
28810 ** Object used to represent an shared memory buffer.
28811 **
28812 ** When multiple threads all reference the same wal-index, each thread
28813 ** has its own unixShm object, but they all point to a single instance
28814 ** of this unixShmNode object.  In other words, each wal-index is opened
28815 ** only once per process.
28816 **
28817 ** Each unixShmNode object is connected to a single unixInodeInfo object.
28818 ** We could coalesce this object into unixInodeInfo, but that would mean
28819 ** every open file that does not use shared memory (in other words, most
28820 ** open files) would have to carry around this extra information.  So
28821 ** the unixInodeInfo object contains a pointer to this unixShmNode object
28822 ** and the unixShmNode object is created only when needed.
28823 **
28824 ** unixMutexHeld() must be true when creating or destroying
28825 ** this object or while reading or writing the following fields:
28826 **
28827 **      nRef
28828 **
28829 ** The following fields are read-only after the object is created:
28830 **
28831 **      fid
28832 **      zFilename
28833 **
28834 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
28835 ** unixMutexHeld() is true when reading or writing any other field
28836 ** in this structure.
28837 */
28838 struct unixShmNode {
28839   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
28840   sqlite3_mutex *mutex;      /* Mutex to access this object */
28841   char *zFilename;           /* Name of the mmapped file */
28842   int h;                     /* Open file descriptor */
28843   int szRegion;              /* Size of shared-memory regions */
28844   u16 nRegion;               /* Size of array apRegion */
28845   u8 isReadonly;             /* True if read-only */
28846   char **apRegion;           /* Array of mapped shared-memory regions */
28847   int nRef;                  /* Number of unixShm objects pointing to this */
28848   unixShm *pFirst;           /* All unixShm objects pointing to this */
28849 #ifdef SQLITE_DEBUG
28850   u8 exclMask;               /* Mask of exclusive locks held */
28851   u8 sharedMask;             /* Mask of shared locks held */
28852   u8 nextShmId;              /* Next available unixShm.id value */
28853 #endif
28854 };
28855 
28856 /*
28857 ** Structure used internally by this VFS to record the state of an
28858 ** open shared memory connection.
28859 **
28860 ** The following fields are initialized when this object is created and
28861 ** are read-only thereafter:
28862 **
28863 **    unixShm.pFile
28864 **    unixShm.id
28865 **
28866 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
28867 ** while accessing any read/write fields.
28868 */
28869 struct unixShm {
28870   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
28871   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
28872   u8 hasMutex;               /* True if holding the unixShmNode mutex */
28873   u8 id;                     /* Id of this connection within its unixShmNode */
28874   u16 sharedMask;            /* Mask of shared locks held */
28875   u16 exclMask;              /* Mask of exclusive locks held */
28876 };
28877 
28878 /*
28879 ** Constants used for locking
28880 */
28881 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
28882 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
28883 
28884 /*
28885 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
28886 **
28887 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
28888 ** otherwise.
28889 */
28890 static int unixShmSystemLock(
28891   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
28892   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
28893   int ofst,              /* First byte of the locking range */
28894   int n                  /* Number of bytes to lock */
28895 ){
28896   struct flock f;       /* The posix advisory locking structure */
28897   int rc = SQLITE_OK;   /* Result code form fcntl() */
28898 
28899   /* Access to the unixShmNode object is serialized by the caller */
28900   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
28901 
28902   /* Shared locks never span more than one byte */
28903   assert( n==1 || lockType!=F_RDLCK );
28904 
28905   /* Locks are within range */
28906   assert( n>=1 && n<SQLITE_SHM_NLOCK );
28907 
28908   if( pShmNode->h>=0 ){
28909     /* Initialize the locking parameters */
28910     memset(&f, 0, sizeof(f));
28911     f.l_type = lockType;
28912     f.l_whence = SEEK_SET;
28913     f.l_start = ofst;
28914     f.l_len = n;
28915 
28916     rc = osFcntl(pShmNode->h, F_SETLK, &f);
28917     rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
28918   }
28919 
28920   /* Update the global lock state and do debug tracing */
28921 #ifdef SQLITE_DEBUG
28922   { u16 mask;
28923   OSTRACE(("SHM-LOCK "));
28924   mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
28925   if( rc==SQLITE_OK ){
28926     if( lockType==F_UNLCK ){
28927       OSTRACE(("unlock %d ok", ofst));
28928       pShmNode->exclMask &= ~mask;
28929       pShmNode->sharedMask &= ~mask;
28930     }else if( lockType==F_RDLCK ){
28931       OSTRACE(("read-lock %d ok", ofst));
28932       pShmNode->exclMask &= ~mask;
28933       pShmNode->sharedMask |= mask;
28934     }else{
28935       assert( lockType==F_WRLCK );
28936       OSTRACE(("write-lock %d ok", ofst));
28937       pShmNode->exclMask |= mask;
28938       pShmNode->sharedMask &= ~mask;
28939     }
28940   }else{
28941     if( lockType==F_UNLCK ){
28942       OSTRACE(("unlock %d failed", ofst));
28943     }else if( lockType==F_RDLCK ){
28944       OSTRACE(("read-lock failed"));
28945     }else{
28946       assert( lockType==F_WRLCK );
28947       OSTRACE(("write-lock %d failed", ofst));
28948     }
28949   }
28950   OSTRACE((" - afterwards %03x,%03x\n",
28951            pShmNode->sharedMask, pShmNode->exclMask));
28952   }
28953 #endif
28954 
28955   return rc;
28956 }
28957 
28958 /*
28959 ** Return the minimum number of 32KB shm regions that should be mapped at
28960 ** a time, assuming that each mapping must be an integer multiple of the
28961 ** current system page-size.
28962 **
28963 ** Usually, this is 1. The exception seems to be systems that are configured
28964 ** to use 64KB pages - in this case each mapping must cover at least two
28965 ** shm regions.
28966 */
28967 static int unixShmRegionPerMap(void){
28968   int shmsz = 32*1024;            /* SHM region size */
28969   int pgsz = osGetpagesize();   /* System page size */
28970   assert( ((pgsz-1)&pgsz)==0 );   /* Page size must be a power of 2 */
28971   if( pgsz<shmsz ) return 1;
28972   return pgsz/shmsz;
28973 }
28974 
28975 /*
28976 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
28977 **
28978 ** This is not a VFS shared-memory method; it is a utility function called
28979 ** by VFS shared-memory methods.
28980 */
28981 static void unixShmPurge(unixFile *pFd){
28982   unixShmNode *p = pFd->pInode->pShmNode;
28983   assert( unixMutexHeld() );
28984   if( p && p->nRef==0 ){
28985     int nShmPerMap = unixShmRegionPerMap();
28986     int i;
28987     assert( p->pInode==pFd->pInode );
28988     sqlite3_mutex_free(p->mutex);
28989     for(i=0; i<p->nRegion; i+=nShmPerMap){
28990       if( p->h>=0 ){
28991         osMunmap(p->apRegion[i], p->szRegion);
28992       }else{
28993         sqlite3_free(p->apRegion[i]);
28994       }
28995     }
28996     sqlite3_free(p->apRegion);
28997     if( p->h>=0 ){
28998       robust_close(pFd, p->h, __LINE__);
28999       p->h = -1;
29000     }
29001     p->pInode->pShmNode = 0;
29002     sqlite3_free(p);
29003   }
29004 }
29005 
29006 /*
29007 ** Open a shared-memory area associated with open database file pDbFd.
29008 ** This particular implementation uses mmapped files.
29009 **
29010 ** The file used to implement shared-memory is in the same directory
29011 ** as the open database file and has the same name as the open database
29012 ** file with the "-shm" suffix added.  For example, if the database file
29013 ** is "/home/user1/config.db" then the file that is created and mmapped
29014 ** for shared memory will be called "/home/user1/config.db-shm".
29015 **
29016 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
29017 ** some other tmpfs mount. But if a file in a different directory
29018 ** from the database file is used, then differing access permissions
29019 ** or a chroot() might cause two different processes on the same
29020 ** database to end up using different files for shared memory -
29021 ** meaning that their memory would not really be shared - resulting
29022 ** in database corruption.  Nevertheless, this tmpfs file usage
29023 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
29024 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
29025 ** option results in an incompatible build of SQLite;  builds of SQLite
29026 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
29027 ** same database file at the same time, database corruption will likely
29028 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
29029 ** "unsupported" and may go away in a future SQLite release.
29030 **
29031 ** When opening a new shared-memory file, if no other instances of that
29032 ** file are currently open, in this process or in other processes, then
29033 ** the file must be truncated to zero length or have its header cleared.
29034 **
29035 ** If the original database file (pDbFd) is using the "unix-excl" VFS
29036 ** that means that an exclusive lock is held on the database file and
29037 ** that no other processes are able to read or write the database.  In
29038 ** that case, we do not really need shared memory.  No shared memory
29039 ** file is created.  The shared memory will be simulated with heap memory.
29040 */
29041 static int unixOpenSharedMemory(unixFile *pDbFd){
29042   struct unixShm *p = 0;          /* The connection to be opened */
29043   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
29044   int rc;                         /* Result code */
29045   unixInodeInfo *pInode;          /* The inode of fd */
29046   char *zShmFilename;             /* Name of the file used for SHM */
29047   int nShmFilename;               /* Size of the SHM filename in bytes */
29048 
29049   /* Allocate space for the new unixShm object. */
29050   p = sqlite3_malloc( sizeof(*p) );
29051   if( p==0 ) return SQLITE_NOMEM;
29052   memset(p, 0, sizeof(*p));
29053   assert( pDbFd->pShm==0 );
29054 
29055   /* Check to see if a unixShmNode object already exists. Reuse an existing
29056   ** one if present. Create a new one if necessary.
29057   */
29058   unixEnterMutex();
29059   pInode = pDbFd->pInode;
29060   pShmNode = pInode->pShmNode;
29061   if( pShmNode==0 ){
29062     struct stat sStat;                 /* fstat() info for database file */
29063 
29064     /* Call fstat() to figure out the permissions on the database file. If
29065     ** a new *-shm file is created, an attempt will be made to create it
29066     ** with the same permissions.
29067     */
29068     if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
29069       rc = SQLITE_IOERR_FSTAT;
29070       goto shm_open_err;
29071     }
29072 
29073 #ifdef SQLITE_SHM_DIRECTORY
29074     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
29075 #else
29076     nShmFilename = 6 + (int)strlen(pDbFd->zPath);
29077 #endif
29078     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
29079     if( pShmNode==0 ){
29080       rc = SQLITE_NOMEM;
29081       goto shm_open_err;
29082     }
29083     memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
29084     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
29085 #ifdef SQLITE_SHM_DIRECTORY
29086     sqlite3_snprintf(nShmFilename, zShmFilename,
29087                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
29088                      (u32)sStat.st_ino, (u32)sStat.st_dev);
29089 #else
29090     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
29091     sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
29092 #endif
29093     pShmNode->h = -1;
29094     pDbFd->pInode->pShmNode = pShmNode;
29095     pShmNode->pInode = pDbFd->pInode;
29096     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
29097     if( pShmNode->mutex==0 ){
29098       rc = SQLITE_NOMEM;
29099       goto shm_open_err;
29100     }
29101 
29102     if( pInode->bProcessLock==0 ){
29103       int openFlags = O_RDWR | O_CREAT;
29104       if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
29105         openFlags = O_RDONLY;
29106         pShmNode->isReadonly = 1;
29107       }
29108       pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
29109       if( pShmNode->h<0 ){
29110         rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
29111         goto shm_open_err;
29112       }
29113 
29114       /* If this process is running as root, make sure that the SHM file
29115       ** is owned by the same user that owns the original database.  Otherwise,
29116       ** the original owner will not be able to connect.
29117       */
29118       osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
29119 
29120       /* Check to see if another process is holding the dead-man switch.
29121       ** If not, truncate the file to zero length.
29122       */
29123       rc = SQLITE_OK;
29124       if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
29125         if( robust_ftruncate(pShmNode->h, 0) ){
29126           rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
29127         }
29128       }
29129       if( rc==SQLITE_OK ){
29130         rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
29131       }
29132       if( rc ) goto shm_open_err;
29133     }
29134   }
29135 
29136   /* Make the new connection a child of the unixShmNode */
29137   p->pShmNode = pShmNode;
29138 #ifdef SQLITE_DEBUG
29139   p->id = pShmNode->nextShmId++;
29140 #endif
29141   pShmNode->nRef++;
29142   pDbFd->pShm = p;
29143   unixLeaveMutex();
29144 
29145   /* The reference count on pShmNode has already been incremented under
29146   ** the cover of the unixEnterMutex() mutex and the pointer from the
29147   ** new (struct unixShm) object to the pShmNode has been set. All that is
29148   ** left to do is to link the new object into the linked list starting
29149   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
29150   ** mutex.
29151   */
29152   sqlite3_mutex_enter(pShmNode->mutex);
29153   p->pNext = pShmNode->pFirst;
29154   pShmNode->pFirst = p;
29155   sqlite3_mutex_leave(pShmNode->mutex);
29156   return SQLITE_OK;
29157 
29158   /* Jump here on any error */
29159 shm_open_err:
29160   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
29161   sqlite3_free(p);
29162   unixLeaveMutex();
29163   return rc;
29164 }
29165 
29166 /*
29167 ** This function is called to obtain a pointer to region iRegion of the
29168 ** shared-memory associated with the database file fd. Shared-memory regions
29169 ** are numbered starting from zero. Each shared-memory region is szRegion
29170 ** bytes in size.
29171 **
29172 ** If an error occurs, an error code is returned and *pp is set to NULL.
29173 **
29174 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
29175 ** region has not been allocated (by any client, including one running in a
29176 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
29177 ** bExtend is non-zero and the requested shared-memory region has not yet
29178 ** been allocated, it is allocated by this function.
29179 **
29180 ** If the shared-memory region has already been allocated or is allocated by
29181 ** this call as described above, then it is mapped into this processes
29182 ** address space (if it is not already), *pp is set to point to the mapped
29183 ** memory and SQLITE_OK returned.
29184 */
29185 static int unixShmMap(
29186   sqlite3_file *fd,               /* Handle open on database file */
29187   int iRegion,                    /* Region to retrieve */
29188   int szRegion,                   /* Size of regions */
29189   int bExtend,                    /* True to extend file if necessary */
29190   void volatile **pp              /* OUT: Mapped memory */
29191 ){
29192   unixFile *pDbFd = (unixFile*)fd;
29193   unixShm *p;
29194   unixShmNode *pShmNode;
29195   int rc = SQLITE_OK;
29196   int nShmPerMap = unixShmRegionPerMap();
29197   int nReqRegion;
29198 
29199   /* If the shared-memory file has not yet been opened, open it now. */
29200   if( pDbFd->pShm==0 ){
29201     rc = unixOpenSharedMemory(pDbFd);
29202     if( rc!=SQLITE_OK ) return rc;
29203   }
29204 
29205   p = pDbFd->pShm;
29206   pShmNode = p->pShmNode;
29207   sqlite3_mutex_enter(pShmNode->mutex);
29208   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
29209   assert( pShmNode->pInode==pDbFd->pInode );
29210   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
29211   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
29212 
29213   /* Minimum number of regions required to be mapped. */
29214   nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
29215 
29216   if( pShmNode->nRegion<nReqRegion ){
29217     char **apNew;                      /* New apRegion[] array */
29218     int nByte = nReqRegion*szRegion;   /* Minimum required file size */
29219     struct stat sStat;                 /* Used by fstat() */
29220 
29221     pShmNode->szRegion = szRegion;
29222 
29223     if( pShmNode->h>=0 ){
29224       /* The requested region is not mapped into this processes address space.
29225       ** Check to see if it has been allocated (i.e. if the wal-index file is
29226       ** large enough to contain the requested region).
29227       */
29228       if( osFstat(pShmNode->h, &sStat) ){
29229         rc = SQLITE_IOERR_SHMSIZE;
29230         goto shmpage_out;
29231       }
29232 
29233       if( sStat.st_size<nByte ){
29234         /* The requested memory region does not exist. If bExtend is set to
29235         ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
29236         */
29237         if( !bExtend ){
29238           goto shmpage_out;
29239         }
29240 
29241         /* Alternatively, if bExtend is true, extend the file. Do this by
29242         ** writing a single byte to the end of each (OS) page being
29243         ** allocated or extended. Technically, we need only write to the
29244         ** last page in order to extend the file. But writing to all new
29245         ** pages forces the OS to allocate them immediately, which reduces
29246         ** the chances of SIGBUS while accessing the mapped region later on.
29247         */
29248         else{
29249           static const int pgsz = 4096;
29250           int iPg;
29251 
29252           /* Write to the last byte of each newly allocated or extended page */
29253           assert( (nByte % pgsz)==0 );
29254           for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
29255             if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
29256               const char *zFile = pShmNode->zFilename;
29257               rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
29258               goto shmpage_out;
29259             }
29260           }
29261         }
29262       }
29263     }
29264 
29265     /* Map the requested memory region into this processes address space. */
29266     apNew = (char **)sqlite3_realloc(
29267         pShmNode->apRegion, nReqRegion*sizeof(char *)
29268     );
29269     if( !apNew ){
29270       rc = SQLITE_IOERR_NOMEM;
29271       goto shmpage_out;
29272     }
29273     pShmNode->apRegion = apNew;
29274     while( pShmNode->nRegion<nReqRegion ){
29275       int nMap = szRegion*nShmPerMap;
29276       int i;
29277       void *pMem;
29278       if( pShmNode->h>=0 ){
29279         pMem = osMmap(0, nMap,
29280             pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
29281             MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
29282         );
29283         if( pMem==MAP_FAILED ){
29284           rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
29285           goto shmpage_out;
29286         }
29287       }else{
29288         pMem = sqlite3_malloc(szRegion);
29289         if( pMem==0 ){
29290           rc = SQLITE_NOMEM;
29291           goto shmpage_out;
29292         }
29293         memset(pMem, 0, szRegion);
29294       }
29295 
29296       for(i=0; i<nShmPerMap; i++){
29297         pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
29298       }
29299       pShmNode->nRegion += nShmPerMap;
29300     }
29301   }
29302 
29303 shmpage_out:
29304   if( pShmNode->nRegion>iRegion ){
29305     *pp = pShmNode->apRegion[iRegion];
29306   }else{
29307     *pp = 0;
29308   }
29309   if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
29310   sqlite3_mutex_leave(pShmNode->mutex);
29311   return rc;
29312 }
29313 
29314 /*
29315 ** Change the lock state for a shared-memory segment.
29316 **
29317 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
29318 ** different here than in posix.  In xShmLock(), one can go from unlocked
29319 ** to shared and back or from unlocked to exclusive and back.  But one may
29320 ** not go from shared to exclusive or from exclusive to shared.
29321 */
29322 static int unixShmLock(
29323   sqlite3_file *fd,          /* Database file holding the shared memory */
29324   int ofst,                  /* First lock to acquire or release */
29325   int n,                     /* Number of locks to acquire or release */
29326   int flags                  /* What to do with the lock */
29327 ){
29328   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
29329   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
29330   unixShm *pX;                          /* For looping over all siblings */
29331   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
29332   int rc = SQLITE_OK;                   /* Result code */
29333   u16 mask;                             /* Mask of locks to take or release */
29334 
29335   assert( pShmNode==pDbFd->pInode->pShmNode );
29336   assert( pShmNode->pInode==pDbFd->pInode );
29337   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
29338   assert( n>=1 );
29339   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
29340        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
29341        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
29342        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
29343   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
29344   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
29345   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
29346 
29347   mask = (1<<(ofst+n)) - (1<<ofst);
29348   assert( n>1 || mask==(1<<ofst) );
29349   sqlite3_mutex_enter(pShmNode->mutex);
29350   if( flags & SQLITE_SHM_UNLOCK ){
29351     u16 allMask = 0; /* Mask of locks held by siblings */
29352 
29353     /* See if any siblings hold this same lock */
29354     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
29355       if( pX==p ) continue;
29356       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
29357       allMask |= pX->sharedMask;
29358     }
29359 
29360     /* Unlock the system-level locks */
29361     if( (mask & allMask)==0 ){
29362       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
29363     }else{
29364       rc = SQLITE_OK;
29365     }
29366 
29367     /* Undo the local locks */
29368     if( rc==SQLITE_OK ){
29369       p->exclMask &= ~mask;
29370       p->sharedMask &= ~mask;
29371     }
29372   }else if( flags & SQLITE_SHM_SHARED ){
29373     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
29374 
29375     /* Find out which shared locks are already held by sibling connections.
29376     ** If any sibling already holds an exclusive lock, go ahead and return
29377     ** SQLITE_BUSY.
29378     */
29379     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
29380       if( (pX->exclMask & mask)!=0 ){
29381         rc = SQLITE_BUSY;
29382         break;
29383       }
29384       allShared |= pX->sharedMask;
29385     }
29386 
29387     /* Get shared locks at the system level, if necessary */
29388     if( rc==SQLITE_OK ){
29389       if( (allShared & mask)==0 ){
29390         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
29391       }else{
29392         rc = SQLITE_OK;
29393       }
29394     }
29395 
29396     /* Get the local shared locks */
29397     if( rc==SQLITE_OK ){
29398       p->sharedMask |= mask;
29399     }
29400   }else{
29401     /* Make sure no sibling connections hold locks that will block this
29402     ** lock.  If any do, return SQLITE_BUSY right away.
29403     */
29404     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
29405       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
29406         rc = SQLITE_BUSY;
29407         break;
29408       }
29409     }
29410 
29411     /* Get the exclusive locks at the system level.  Then if successful
29412     ** also mark the local connection as being locked.
29413     */
29414     if( rc==SQLITE_OK ){
29415       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
29416       if( rc==SQLITE_OK ){
29417         assert( (p->sharedMask & mask)==0 );
29418         p->exclMask |= mask;
29419       }
29420     }
29421   }
29422   sqlite3_mutex_leave(pShmNode->mutex);
29423   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
29424            p->id, getpid(), p->sharedMask, p->exclMask));
29425   return rc;
29426 }
29427 
29428 /*
29429 ** Implement a memory barrier or memory fence on shared memory.
29430 **
29431 ** All loads and stores begun before the barrier must complete before
29432 ** any load or store begun after the barrier.
29433 */
29434 static void unixShmBarrier(
29435   sqlite3_file *fd                /* Database file holding the shared memory */
29436 ){
29437   UNUSED_PARAMETER(fd);
29438   unixEnterMutex();
29439   unixLeaveMutex();
29440 }
29441 
29442 /*
29443 ** Close a connection to shared-memory.  Delete the underlying
29444 ** storage if deleteFlag is true.
29445 **
29446 ** If there is no shared memory associated with the connection then this
29447 ** routine is a harmless no-op.
29448 */
29449 static int unixShmUnmap(
29450   sqlite3_file *fd,               /* The underlying database file */
29451   int deleteFlag                  /* Delete shared-memory if true */
29452 ){
29453   unixShm *p;                     /* The connection to be closed */
29454   unixShmNode *pShmNode;          /* The underlying shared-memory file */
29455   unixShm **pp;                   /* For looping over sibling connections */
29456   unixFile *pDbFd;                /* The underlying database file */
29457 
29458   pDbFd = (unixFile*)fd;
29459   p = pDbFd->pShm;
29460   if( p==0 ) return SQLITE_OK;
29461   pShmNode = p->pShmNode;
29462 
29463   assert( pShmNode==pDbFd->pInode->pShmNode );
29464   assert( pShmNode->pInode==pDbFd->pInode );
29465 
29466   /* Remove connection p from the set of connections associated
29467   ** with pShmNode */
29468   sqlite3_mutex_enter(pShmNode->mutex);
29469   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
29470   *pp = p->pNext;
29471 
29472   /* Free the connection p */
29473   sqlite3_free(p);
29474   pDbFd->pShm = 0;
29475   sqlite3_mutex_leave(pShmNode->mutex);
29476 
29477   /* If pShmNode->nRef has reached 0, then close the underlying
29478   ** shared-memory file, too */
29479   unixEnterMutex();
29480   assert( pShmNode->nRef>0 );
29481   pShmNode->nRef--;
29482   if( pShmNode->nRef==0 ){
29483     if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
29484     unixShmPurge(pDbFd);
29485   }
29486   unixLeaveMutex();
29487 
29488   return SQLITE_OK;
29489 }
29490 
29491 
29492 #else
29493 # define unixShmMap     0
29494 # define unixShmLock    0
29495 # define unixShmBarrier 0
29496 # define unixShmUnmap   0
29497 #endif /* #ifndef SQLITE_OMIT_WAL */
29498 
29499 #if SQLITE_MAX_MMAP_SIZE>0
29500 /*
29501 ** If it is currently memory mapped, unmap file pFd.
29502 */
29503 static void unixUnmapfile(unixFile *pFd){
29504   assert( pFd->nFetchOut==0 );
29505   if( pFd->pMapRegion ){
29506     osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
29507     pFd->pMapRegion = 0;
29508     pFd->mmapSize = 0;
29509     pFd->mmapSizeActual = 0;
29510   }
29511 }
29512 
29513 /*
29514 ** Attempt to set the size of the memory mapping maintained by file
29515 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
29516 **
29517 ** If successful, this function sets the following variables:
29518 **
29519 **       unixFile.pMapRegion
29520 **       unixFile.mmapSize
29521 **       unixFile.mmapSizeActual
29522 **
29523 ** If unsuccessful, an error message is logged via sqlite3_log() and
29524 ** the three variables above are zeroed. In this case SQLite should
29525 ** continue accessing the database using the xRead() and xWrite()
29526 ** methods.
29527 */
29528 static void unixRemapfile(
29529   unixFile *pFd,                  /* File descriptor object */
29530   i64 nNew                        /* Required mapping size */
29531 ){
29532   const char *zErr = "mmap";
29533   int h = pFd->h;                      /* File descriptor open on db file */
29534   u8 *pOrig = (u8 *)pFd->pMapRegion;   /* Pointer to current file mapping */
29535   i64 nOrig = pFd->mmapSizeActual;     /* Size of pOrig region in bytes */
29536   u8 *pNew = 0;                        /* Location of new mapping */
29537   int flags = PROT_READ;               /* Flags to pass to mmap() */
29538 
29539   assert( pFd->nFetchOut==0 );
29540   assert( nNew>pFd->mmapSize );
29541   assert( nNew<=pFd->mmapSizeMax );
29542   assert( nNew>0 );
29543   assert( pFd->mmapSizeActual>=pFd->mmapSize );
29544   assert( MAP_FAILED!=0 );
29545 
29546   if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
29547 
29548   if( pOrig ){
29549 #if HAVE_MREMAP
29550     i64 nReuse = pFd->mmapSize;
29551 #else
29552     const int szSyspage = osGetpagesize();
29553     i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
29554 #endif
29555     u8 *pReq = &pOrig[nReuse];
29556 
29557     /* Unmap any pages of the existing mapping that cannot be reused. */
29558     if( nReuse!=nOrig ){
29559       osMunmap(pReq, nOrig-nReuse);
29560     }
29561 
29562 #if HAVE_MREMAP
29563     pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
29564     zErr = "mremap";
29565 #else
29566     pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
29567     if( pNew!=MAP_FAILED ){
29568       if( pNew!=pReq ){
29569         osMunmap(pNew, nNew - nReuse);
29570         pNew = 0;
29571       }else{
29572         pNew = pOrig;
29573       }
29574     }
29575 #endif
29576 
29577     /* The attempt to extend the existing mapping failed. Free it. */
29578     if( pNew==MAP_FAILED || pNew==0 ){
29579       osMunmap(pOrig, nReuse);
29580     }
29581   }
29582 
29583   /* If pNew is still NULL, try to create an entirely new mapping. */
29584   if( pNew==0 ){
29585     pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
29586   }
29587 
29588   if( pNew==MAP_FAILED ){
29589     pNew = 0;
29590     nNew = 0;
29591     unixLogError(SQLITE_OK, zErr, pFd->zPath);
29592 
29593     /* If the mmap() above failed, assume that all subsequent mmap() calls
29594     ** will probably fail too. Fall back to using xRead/xWrite exclusively
29595     ** in this case.  */
29596     pFd->mmapSizeMax = 0;
29597   }
29598   pFd->pMapRegion = (void *)pNew;
29599   pFd->mmapSize = pFd->mmapSizeActual = nNew;
29600 }
29601 
29602 /*
29603 ** Memory map or remap the file opened by file-descriptor pFd (if the file
29604 ** is already mapped, the existing mapping is replaced by the new). Or, if
29605 ** there already exists a mapping for this file, and there are still
29606 ** outstanding xFetch() references to it, this function is a no-op.
29607 **
29608 ** If parameter nByte is non-negative, then it is the requested size of
29609 ** the mapping to create. Otherwise, if nByte is less than zero, then the
29610 ** requested size is the size of the file on disk. The actual size of the
29611 ** created mapping is either the requested size or the value configured
29612 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
29613 **
29614 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
29615 ** recreated as a result of outstanding references) or an SQLite error
29616 ** code otherwise.
29617 */
29618 static int unixMapfile(unixFile *pFd, i64 nByte){
29619   i64 nMap = nByte;
29620   int rc;
29621 
29622   assert( nMap>=0 || pFd->nFetchOut==0 );
29623   if( pFd->nFetchOut>0 ) return SQLITE_OK;
29624 
29625   if( nMap<0 ){
29626     struct stat statbuf;          /* Low-level file information */
29627     rc = osFstat(pFd->h, &statbuf);
29628     if( rc!=SQLITE_OK ){
29629       return SQLITE_IOERR_FSTAT;
29630     }
29631     nMap = statbuf.st_size;
29632   }
29633   if( nMap>pFd->mmapSizeMax ){
29634     nMap = pFd->mmapSizeMax;
29635   }
29636 
29637   if( nMap!=pFd->mmapSize ){
29638     if( nMap>0 ){
29639       unixRemapfile(pFd, nMap);
29640     }else{
29641       unixUnmapfile(pFd);
29642     }
29643   }
29644 
29645   return SQLITE_OK;
29646 }
29647 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
29648 
29649 /*
29650 ** If possible, return a pointer to a mapping of file fd starting at offset
29651 ** iOff. The mapping must be valid for at least nAmt bytes.
29652 **
29653 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
29654 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
29655 ** Finally, if an error does occur, return an SQLite error code. The final
29656 ** value of *pp is undefined in this case.
29657 **
29658 ** If this function does return a pointer, the caller must eventually
29659 ** release the reference by calling unixUnfetch().
29660 */
29661 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
29662 #if SQLITE_MAX_MMAP_SIZE>0
29663   unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
29664 #endif
29665   *pp = 0;
29666 
29667 #if SQLITE_MAX_MMAP_SIZE>0
29668   if( pFd->mmapSizeMax>0 ){
29669     if( pFd->pMapRegion==0 ){
29670       int rc = unixMapfile(pFd, -1);
29671       if( rc!=SQLITE_OK ) return rc;
29672     }
29673     if( pFd->mmapSize >= iOff+nAmt ){
29674       *pp = &((u8 *)pFd->pMapRegion)[iOff];
29675       pFd->nFetchOut++;
29676     }
29677   }
29678 #endif
29679   return SQLITE_OK;
29680 }
29681 
29682 /*
29683 ** If the third argument is non-NULL, then this function releases a
29684 ** reference obtained by an earlier call to unixFetch(). The second
29685 ** argument passed to this function must be the same as the corresponding
29686 ** argument that was passed to the unixFetch() invocation.
29687 **
29688 ** Or, if the third argument is NULL, then this function is being called
29689 ** to inform the VFS layer that, according to POSIX, any existing mapping
29690 ** may now be invalid and should be unmapped.
29691 */
29692 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
29693 #if SQLITE_MAX_MMAP_SIZE>0
29694   unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
29695   UNUSED_PARAMETER(iOff);
29696 
29697   /* If p==0 (unmap the entire file) then there must be no outstanding
29698   ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
29699   ** then there must be at least one outstanding.  */
29700   assert( (p==0)==(pFd->nFetchOut==0) );
29701 
29702   /* If p!=0, it must match the iOff value. */
29703   assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
29704 
29705   if( p ){
29706     pFd->nFetchOut--;
29707   }else{
29708     unixUnmapfile(pFd);
29709   }
29710 
29711   assert( pFd->nFetchOut>=0 );
29712 #else
29713   UNUSED_PARAMETER(fd);
29714   UNUSED_PARAMETER(p);
29715   UNUSED_PARAMETER(iOff);
29716 #endif
29717   return SQLITE_OK;
29718 }
29719 
29720 /*
29721 ** Here ends the implementation of all sqlite3_file methods.
29722 **
29723 ********************** End sqlite3_file Methods *******************************
29724 ******************************************************************************/
29725 
29726 /*
29727 ** This division contains definitions of sqlite3_io_methods objects that
29728 ** implement various file locking strategies.  It also contains definitions
29729 ** of "finder" functions.  A finder-function is used to locate the appropriate
29730 ** sqlite3_io_methods object for a particular database file.  The pAppData
29731 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
29732 ** the correct finder-function for that VFS.
29733 **
29734 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
29735 ** object.  The only interesting finder-function is autolockIoFinder, which
29736 ** looks at the filesystem type and tries to guess the best locking
29737 ** strategy from that.
29738 **
29739 ** For finder-function F, two objects are created:
29740 **
29741 **    (1) The real finder-function named "FImpt()".
29742 **
29743 **    (2) A constant pointer to this function named just "F".
29744 **
29745 **
29746 ** A pointer to the F pointer is used as the pAppData value for VFS
29747 ** objects.  We have to do this instead of letting pAppData point
29748 ** directly at the finder-function since C90 rules prevent a void*
29749 ** from be cast into a function pointer.
29750 **
29751 **
29752 ** Each instance of this macro generates two objects:
29753 **
29754 **   *  A constant sqlite3_io_methods object call METHOD that has locking
29755 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
29756 **
29757 **   *  An I/O method finder function called FINDER that returns a pointer
29758 **      to the METHOD object in the previous bullet.
29759 */
29760 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK, SHMMAP) \
29761 static const sqlite3_io_methods METHOD = {                                   \
29762    VERSION,                    /* iVersion */                                \
29763    CLOSE,                      /* xClose */                                  \
29764    unixRead,                   /* xRead */                                   \
29765    unixWrite,                  /* xWrite */                                  \
29766    unixTruncate,               /* xTruncate */                               \
29767    unixSync,                   /* xSync */                                   \
29768    unixFileSize,               /* xFileSize */                               \
29769    LOCK,                       /* xLock */                                   \
29770    UNLOCK,                     /* xUnlock */                                 \
29771    CKLOCK,                     /* xCheckReservedLock */                      \
29772    unixFileControl,            /* xFileControl */                            \
29773    unixSectorSize,             /* xSectorSize */                             \
29774    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
29775    SHMMAP,                     /* xShmMap */                                 \
29776    unixShmLock,                /* xShmLock */                                \
29777    unixShmBarrier,             /* xShmBarrier */                             \
29778    unixShmUnmap,               /* xShmUnmap */                               \
29779    unixFetch,                  /* xFetch */                                  \
29780    unixUnfetch,                /* xUnfetch */                                \
29781 };                                                                           \
29782 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
29783   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
29784   return &METHOD;                                                            \
29785 }                                                                            \
29786 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
29787     = FINDER##Impl;
29788 
29789 /*
29790 ** Here are all of the sqlite3_io_methods objects for each of the
29791 ** locking strategies.  Functions that return pointers to these methods
29792 ** are also created.
29793 */
29794 IOMETHODS(
29795   posixIoFinder,            /* Finder function name */
29796   posixIoMethods,           /* sqlite3_io_methods object name */
29797   3,                        /* shared memory and mmap are enabled */
29798   unixClose,                /* xClose method */
29799   unixLock,                 /* xLock method */
29800   unixUnlock,               /* xUnlock method */
29801   unixCheckReservedLock,    /* xCheckReservedLock method */
29802   unixShmMap                /* xShmMap method */
29803 )
29804 IOMETHODS(
29805   nolockIoFinder,           /* Finder function name */
29806   nolockIoMethods,          /* sqlite3_io_methods object name */
29807   3,                        /* shared memory is disabled */
29808   nolockClose,              /* xClose method */
29809   nolockLock,               /* xLock method */
29810   nolockUnlock,             /* xUnlock method */
29811   nolockCheckReservedLock,  /* xCheckReservedLock method */
29812   0                         /* xShmMap method */
29813 )
29814 IOMETHODS(
29815   dotlockIoFinder,          /* Finder function name */
29816   dotlockIoMethods,         /* sqlite3_io_methods object name */
29817   1,                        /* shared memory is disabled */
29818   dotlockClose,             /* xClose method */
29819   dotlockLock,              /* xLock method */
29820   dotlockUnlock,            /* xUnlock method */
29821   dotlockCheckReservedLock, /* xCheckReservedLock method */
29822   0                         /* xShmMap method */
29823 )
29824 
29825 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
29826 IOMETHODS(
29827   flockIoFinder,            /* Finder function name */
29828   flockIoMethods,           /* sqlite3_io_methods object name */
29829   1,                        /* shared memory is disabled */
29830   flockClose,               /* xClose method */
29831   flockLock,                /* xLock method */
29832   flockUnlock,              /* xUnlock method */
29833   flockCheckReservedLock,   /* xCheckReservedLock method */
29834   0                         /* xShmMap method */
29835 )
29836 #endif
29837 
29838 #if OS_VXWORKS
29839 IOMETHODS(
29840   semIoFinder,              /* Finder function name */
29841   semIoMethods,             /* sqlite3_io_methods object name */
29842   1,                        /* shared memory is disabled */
29843   semClose,                 /* xClose method */
29844   semLock,                  /* xLock method */
29845   semUnlock,                /* xUnlock method */
29846   semCheckReservedLock,     /* xCheckReservedLock method */
29847   0                         /* xShmMap method */
29848 )
29849 #endif
29850 
29851 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29852 IOMETHODS(
29853   afpIoFinder,              /* Finder function name */
29854   afpIoMethods,             /* sqlite3_io_methods object name */
29855   1,                        /* shared memory is disabled */
29856   afpClose,                 /* xClose method */
29857   afpLock,                  /* xLock method */
29858   afpUnlock,                /* xUnlock method */
29859   afpCheckReservedLock,     /* xCheckReservedLock method */
29860   0                         /* xShmMap method */
29861 )
29862 #endif
29863 
29864 /*
29865 ** The proxy locking method is a "super-method" in the sense that it
29866 ** opens secondary file descriptors for the conch and lock files and
29867 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
29868 ** secondary files.  For this reason, the division that implements
29869 ** proxy locking is located much further down in the file.  But we need
29870 ** to go ahead and define the sqlite3_io_methods and finder function
29871 ** for proxy locking here.  So we forward declare the I/O methods.
29872 */
29873 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29874 static int proxyClose(sqlite3_file*);
29875 static int proxyLock(sqlite3_file*, int);
29876 static int proxyUnlock(sqlite3_file*, int);
29877 static int proxyCheckReservedLock(sqlite3_file*, int*);
29878 IOMETHODS(
29879   proxyIoFinder,            /* Finder function name */
29880   proxyIoMethods,           /* sqlite3_io_methods object name */
29881   1,                        /* shared memory is disabled */
29882   proxyClose,               /* xClose method */
29883   proxyLock,                /* xLock method */
29884   proxyUnlock,              /* xUnlock method */
29885   proxyCheckReservedLock,   /* xCheckReservedLock method */
29886   0                         /* xShmMap method */
29887 )
29888 #endif
29889 
29890 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
29891 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29892 IOMETHODS(
29893   nfsIoFinder,               /* Finder function name */
29894   nfsIoMethods,              /* sqlite3_io_methods object name */
29895   1,                         /* shared memory is disabled */
29896   unixClose,                 /* xClose method */
29897   unixLock,                  /* xLock method */
29898   nfsUnlock,                 /* xUnlock method */
29899   unixCheckReservedLock,     /* xCheckReservedLock method */
29900   0                          /* xShmMap method */
29901 )
29902 #endif
29903 
29904 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29905 /*
29906 ** This "finder" function attempts to determine the best locking strategy
29907 ** for the database file "filePath".  It then returns the sqlite3_io_methods
29908 ** object that implements that strategy.
29909 **
29910 ** This is for MacOSX only.
29911 */
29912 static const sqlite3_io_methods *autolockIoFinderImpl(
29913   const char *filePath,    /* name of the database file */
29914   unixFile *pNew           /* open file object for the database file */
29915 ){
29916   static const struct Mapping {
29917     const char *zFilesystem;              /* Filesystem type name */
29918     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
29919   } aMap[] = {
29920     { "hfs",    &posixIoMethods },
29921     { "ufs",    &posixIoMethods },
29922     { "afpfs",  &afpIoMethods },
29923     { "smbfs",  &afpIoMethods },
29924     { "webdav", &nolockIoMethods },
29925     { 0, 0 }
29926   };
29927   int i;
29928   struct statfs fsInfo;
29929   struct flock lockInfo;
29930 
29931   if( !filePath ){
29932     /* If filePath==NULL that means we are dealing with a transient file
29933     ** that does not need to be locked. */
29934     return &nolockIoMethods;
29935   }
29936   if( statfs(filePath, &fsInfo) != -1 ){
29937     if( fsInfo.f_flags & MNT_RDONLY ){
29938       return &nolockIoMethods;
29939     }
29940     for(i=0; aMap[i].zFilesystem; i++){
29941       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
29942         return aMap[i].pMethods;
29943       }
29944     }
29945   }
29946 
29947   /* Default case. Handles, amongst others, "nfs".
29948   ** Test byte-range lock using fcntl(). If the call succeeds,
29949   ** assume that the file-system supports POSIX style locks.
29950   */
29951   lockInfo.l_len = 1;
29952   lockInfo.l_start = 0;
29953   lockInfo.l_whence = SEEK_SET;
29954   lockInfo.l_type = F_RDLCK;
29955   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
29956     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
29957       return &nfsIoMethods;
29958     } else {
29959       return &posixIoMethods;
29960     }
29961   }else{
29962     return &dotlockIoMethods;
29963   }
29964 }
29965 static const sqlite3_io_methods
29966   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
29967 
29968 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
29969 
29970 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
29971 /*
29972 ** This "finder" function attempts to determine the best locking strategy
29973 ** for the database file "filePath".  It then returns the sqlite3_io_methods
29974 ** object that implements that strategy.
29975 **
29976 ** This is for VXWorks only.
29977 */
29978 static const sqlite3_io_methods *autolockIoFinderImpl(
29979   const char *filePath,    /* name of the database file */
29980   unixFile *pNew           /* the open file object */
29981 ){
29982   struct flock lockInfo;
29983 
29984   if( !filePath ){
29985     /* If filePath==NULL that means we are dealing with a transient file
29986     ** that does not need to be locked. */
29987     return &nolockIoMethods;
29988   }
29989 
29990   /* Test if fcntl() is supported and use POSIX style locks.
29991   ** Otherwise fall back to the named semaphore method.
29992   */
29993   lockInfo.l_len = 1;
29994   lockInfo.l_start = 0;
29995   lockInfo.l_whence = SEEK_SET;
29996   lockInfo.l_type = F_RDLCK;
29997   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
29998     return &posixIoMethods;
29999   }else{
30000     return &semIoMethods;
30001   }
30002 }
30003 static const sqlite3_io_methods
30004   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
30005 
30006 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
30007 
30008 /*
30009 ** An abstract type for a pointer to an IO method finder function:
30010 */
30011 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
30012 
30013 
30014 /****************************************************************************
30015 **************************** sqlite3_vfs methods ****************************
30016 **
30017 ** This division contains the implementation of methods on the
30018 ** sqlite3_vfs object.
30019 */
30020 
30021 /*
30022 ** Initialize the contents of the unixFile structure pointed to by pId.
30023 */
30024 static int fillInUnixFile(
30025   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
30026   int h,                  /* Open file descriptor of file being opened */
30027   sqlite3_file *pId,      /* Write to the unixFile structure here */
30028   const char *zFilename,  /* Name of the file being opened */
30029   int ctrlFlags           /* Zero or more UNIXFILE_* values */
30030 ){
30031   const sqlite3_io_methods *pLockingStyle;
30032   unixFile *pNew = (unixFile *)pId;
30033   int rc = SQLITE_OK;
30034 
30035   assert( pNew->pInode==NULL );
30036 
30037   /* Usually the path zFilename should not be a relative pathname. The
30038   ** exception is when opening the proxy "conch" file in builds that
30039   ** include the special Apple locking styles.
30040   */
30041 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30042   assert( zFilename==0 || zFilename[0]=='/'
30043     || pVfs->pAppData==(void*)&autolockIoFinder );
30044 #else
30045   assert( zFilename==0 || zFilename[0]=='/' );
30046 #endif
30047 
30048   /* No locking occurs in temporary files */
30049   assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
30050 
30051   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
30052   pNew->h = h;
30053   pNew->pVfs = pVfs;
30054   pNew->zPath = zFilename;
30055   pNew->ctrlFlags = (u8)ctrlFlags;
30056 #if SQLITE_MAX_MMAP_SIZE>0
30057   pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
30058 #endif
30059   if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
30060                            "psow", SQLITE_POWERSAFE_OVERWRITE) ){
30061     pNew->ctrlFlags |= UNIXFILE_PSOW;
30062   }
30063   if( strcmp(pVfs->zName,"unix-excl")==0 ){
30064     pNew->ctrlFlags |= UNIXFILE_EXCL;
30065   }
30066 
30067 #if OS_VXWORKS
30068   pNew->pId = vxworksFindFileId(zFilename);
30069   if( pNew->pId==0 ){
30070     ctrlFlags |= UNIXFILE_NOLOCK;
30071     rc = SQLITE_NOMEM;
30072   }
30073 #endif
30074 
30075   if( ctrlFlags & UNIXFILE_NOLOCK ){
30076     pLockingStyle = &nolockIoMethods;
30077   }else{
30078     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
30079 #if SQLITE_ENABLE_LOCKING_STYLE
30080     /* Cache zFilename in the locking context (AFP and dotlock override) for
30081     ** proxyLock activation is possible (remote proxy is based on db name)
30082     ** zFilename remains valid until file is closed, to support */
30083     pNew->lockingContext = (void*)zFilename;
30084 #endif
30085   }
30086 
30087   if( pLockingStyle == &posixIoMethods
30088 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30089     || pLockingStyle == &nfsIoMethods
30090 #endif
30091   ){
30092     unixEnterMutex();
30093     rc = findInodeInfo(pNew, &pNew->pInode);
30094     if( rc!=SQLITE_OK ){
30095       /* If an error occurred in findInodeInfo(), close the file descriptor
30096       ** immediately, before releasing the mutex. findInodeInfo() may fail
30097       ** in two scenarios:
30098       **
30099       **   (a) A call to fstat() failed.
30100       **   (b) A malloc failed.
30101       **
30102       ** Scenario (b) may only occur if the process is holding no other
30103       ** file descriptors open on the same file. If there were other file
30104       ** descriptors on this file, then no malloc would be required by
30105       ** findInodeInfo(). If this is the case, it is quite safe to close
30106       ** handle h - as it is guaranteed that no posix locks will be released
30107       ** by doing so.
30108       **
30109       ** If scenario (a) caused the error then things are not so safe. The
30110       ** implicit assumption here is that if fstat() fails, things are in
30111       ** such bad shape that dropping a lock or two doesn't matter much.
30112       */
30113       robust_close(pNew, h, __LINE__);
30114       h = -1;
30115     }
30116     unixLeaveMutex();
30117   }
30118 
30119 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30120   else if( pLockingStyle == &afpIoMethods ){
30121     /* AFP locking uses the file path so it needs to be included in
30122     ** the afpLockingContext.
30123     */
30124     afpLockingContext *pCtx;
30125     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
30126     if( pCtx==0 ){
30127       rc = SQLITE_NOMEM;
30128     }else{
30129       /* NB: zFilename exists and remains valid until the file is closed
30130       ** according to requirement F11141.  So we do not need to make a
30131       ** copy of the filename. */
30132       pCtx->dbPath = zFilename;
30133       pCtx->reserved = 0;
30134       srandomdev();
30135       unixEnterMutex();
30136       rc = findInodeInfo(pNew, &pNew->pInode);
30137       if( rc!=SQLITE_OK ){
30138         sqlite3_free(pNew->lockingContext);
30139         robust_close(pNew, h, __LINE__);
30140         h = -1;
30141       }
30142       unixLeaveMutex();
30143     }
30144   }
30145 #endif
30146 
30147   else if( pLockingStyle == &dotlockIoMethods ){
30148     /* Dotfile locking uses the file path so it needs to be included in
30149     ** the dotlockLockingContext
30150     */
30151     char *zLockFile;
30152     int nFilename;
30153     assert( zFilename!=0 );
30154     nFilename = (int)strlen(zFilename) + 6;
30155     zLockFile = (char *)sqlite3_malloc(nFilename);
30156     if( zLockFile==0 ){
30157       rc = SQLITE_NOMEM;
30158     }else{
30159       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
30160     }
30161     pNew->lockingContext = zLockFile;
30162   }
30163 
30164 #if OS_VXWORKS
30165   else if( pLockingStyle == &semIoMethods ){
30166     /* Named semaphore locking uses the file path so it needs to be
30167     ** included in the semLockingContext
30168     */
30169     unixEnterMutex();
30170     rc = findInodeInfo(pNew, &pNew->pInode);
30171     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
30172       char *zSemName = pNew->pInode->aSemName;
30173       int n;
30174       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
30175                        pNew->pId->zCanonicalName);
30176       for( n=1; zSemName[n]; n++ )
30177         if( zSemName[n]=='/' ) zSemName[n] = '_';
30178       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
30179       if( pNew->pInode->pSem == SEM_FAILED ){
30180         rc = SQLITE_NOMEM;
30181         pNew->pInode->aSemName[0] = '\0';
30182       }
30183     }
30184     unixLeaveMutex();
30185   }
30186 #endif
30187 
30188   pNew->lastErrno = 0;
30189 #if OS_VXWORKS
30190   if( rc!=SQLITE_OK ){
30191     if( h>=0 ) robust_close(pNew, h, __LINE__);
30192     h = -1;
30193     osUnlink(zFilename);
30194     pNew->ctrlFlags |= UNIXFILE_DELETE;
30195   }
30196 #endif
30197   if( rc!=SQLITE_OK ){
30198     if( h>=0 ) robust_close(pNew, h, __LINE__);
30199   }else{
30200     pNew->pMethod = pLockingStyle;
30201     OpenCounter(+1);
30202     verifyDbFile(pNew);
30203   }
30204   return rc;
30205 }
30206 
30207 /*
30208 ** Return the name of a directory in which to put temporary files.
30209 ** If no suitable temporary file directory can be found, return NULL.
30210 */
30211 static const char *unixTempFileDir(void){
30212   static const char *azDirs[] = {
30213      0,
30214      0,
30215      0,
30216      "/var/tmp",
30217      "/usr/tmp",
30218      "/tmp",
30219      0        /* List terminator */
30220   };
30221   unsigned int i;
30222   struct stat buf;
30223   const char *zDir = 0;
30224 
30225   azDirs[0] = sqlite3_temp_directory;
30226   if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
30227   if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
30228   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
30229     if( zDir==0 ) continue;
30230     if( osStat(zDir, &buf) ) continue;
30231     if( !S_ISDIR(buf.st_mode) ) continue;
30232     if( osAccess(zDir, 07) ) continue;
30233     break;
30234   }
30235   return zDir;
30236 }
30237 
30238 /*
30239 ** Create a temporary file name in zBuf.  zBuf must be allocated
30240 ** by the calling process and must be big enough to hold at least
30241 ** pVfs->mxPathname bytes.
30242 */
30243 static int unixGetTempname(int nBuf, char *zBuf){
30244   static const unsigned char zChars[] =
30245     "abcdefghijklmnopqrstuvwxyz"
30246     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
30247     "0123456789";
30248   unsigned int i, j;
30249   const char *zDir;
30250 
30251   /* It's odd to simulate an io-error here, but really this is just
30252   ** using the io-error infrastructure to test that SQLite handles this
30253   ** function failing.
30254   */
30255   SimulateIOError( return SQLITE_IOERR );
30256 
30257   zDir = unixTempFileDir();
30258   if( zDir==0 ) zDir = ".";
30259 
30260   /* Check that the output buffer is large enough for the temporary file
30261   ** name. If it is not, return SQLITE_ERROR.
30262   */
30263   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
30264     return SQLITE_ERROR;
30265   }
30266 
30267   do{
30268     sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
30269     j = (int)strlen(zBuf);
30270     sqlite3_randomness(15, &zBuf[j]);
30271     for(i=0; i<15; i++, j++){
30272       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
30273     }
30274     zBuf[j] = 0;
30275     zBuf[j+1] = 0;
30276   }while( osAccess(zBuf,0)==0 );
30277   return SQLITE_OK;
30278 }
30279 
30280 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30281 /*
30282 ** Routine to transform a unixFile into a proxy-locking unixFile.
30283 ** Implementation in the proxy-lock division, but used by unixOpen()
30284 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
30285 */
30286 static int proxyTransformUnixFile(unixFile*, const char*);
30287 #endif
30288 
30289 /*
30290 ** Search for an unused file descriptor that was opened on the database
30291 ** file (not a journal or master-journal file) identified by pathname
30292 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
30293 ** argument to this function.
30294 **
30295 ** Such a file descriptor may exist if a database connection was closed
30296 ** but the associated file descriptor could not be closed because some
30297 ** other file descriptor open on the same file is holding a file-lock.
30298 ** Refer to comments in the unixClose() function and the lengthy comment
30299 ** describing "Posix Advisory Locking" at the start of this file for
30300 ** further details. Also, ticket #4018.
30301 **
30302 ** If a suitable file descriptor is found, then it is returned. If no
30303 ** such file descriptor is located, -1 is returned.
30304 */
30305 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
30306   UnixUnusedFd *pUnused = 0;
30307 
30308   /* Do not search for an unused file descriptor on vxworks. Not because
30309   ** vxworks would not benefit from the change (it might, we're not sure),
30310   ** but because no way to test it is currently available. It is better
30311   ** not to risk breaking vxworks support for the sake of such an obscure
30312   ** feature.  */
30313 #if !OS_VXWORKS
30314   struct stat sStat;                   /* Results of stat() call */
30315 
30316   /* A stat() call may fail for various reasons. If this happens, it is
30317   ** almost certain that an open() call on the same path will also fail.
30318   ** For this reason, if an error occurs in the stat() call here, it is
30319   ** ignored and -1 is returned. The caller will try to open a new file
30320   ** descriptor on the same path, fail, and return an error to SQLite.
30321   **
30322   ** Even if a subsequent open() call does succeed, the consequences of
30323   ** not searching for a reusable file descriptor are not dire.  */
30324   if( 0==osStat(zPath, &sStat) ){
30325     unixInodeInfo *pInode;
30326 
30327     unixEnterMutex();
30328     pInode = inodeList;
30329     while( pInode && (pInode->fileId.dev!=sStat.st_dev
30330                      || pInode->fileId.ino!=sStat.st_ino) ){
30331        pInode = pInode->pNext;
30332     }
30333     if( pInode ){
30334       UnixUnusedFd **pp;
30335       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
30336       pUnused = *pp;
30337       if( pUnused ){
30338         *pp = pUnused->pNext;
30339       }
30340     }
30341     unixLeaveMutex();
30342   }
30343 #endif    /* if !OS_VXWORKS */
30344   return pUnused;
30345 }
30346 
30347 /*
30348 ** This function is called by unixOpen() to determine the unix permissions
30349 ** to create new files with. If no error occurs, then SQLITE_OK is returned
30350 ** and a value suitable for passing as the third argument to open(2) is
30351 ** written to *pMode. If an IO error occurs, an SQLite error code is
30352 ** returned and the value of *pMode is not modified.
30353 **
30354 ** In most cases, this routine sets *pMode to 0, which will become
30355 ** an indication to robust_open() to create the file using
30356 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
30357 ** But if the file being opened is a WAL or regular journal file, then
30358 ** this function queries the file-system for the permissions on the
30359 ** corresponding database file and sets *pMode to this value. Whenever
30360 ** possible, WAL and journal files are created using the same permissions
30361 ** as the associated database file.
30362 **
30363 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
30364 ** original filename is unavailable.  But 8_3_NAMES is only used for
30365 ** FAT filesystems and permissions do not matter there, so just use
30366 ** the default permissions.
30367 */
30368 static int findCreateFileMode(
30369   const char *zPath,              /* Path of file (possibly) being created */
30370   int flags,                      /* Flags passed as 4th argument to xOpen() */
30371   mode_t *pMode,                  /* OUT: Permissions to open file with */
30372   uid_t *pUid,                    /* OUT: uid to set on the file */
30373   gid_t *pGid                     /* OUT: gid to set on the file */
30374 ){
30375   int rc = SQLITE_OK;             /* Return Code */
30376   *pMode = 0;
30377   *pUid = 0;
30378   *pGid = 0;
30379   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
30380     char zDb[MAX_PATHNAME+1];     /* Database file path */
30381     int nDb;                      /* Number of valid bytes in zDb */
30382     struct stat sStat;            /* Output of stat() on database file */
30383 
30384     /* zPath is a path to a WAL or journal file. The following block derives
30385     ** the path to the associated database file from zPath. This block handles
30386     ** the following naming conventions:
30387     **
30388     **   "<path to db>-journal"
30389     **   "<path to db>-wal"
30390     **   "<path to db>-journalNN"
30391     **   "<path to db>-walNN"
30392     **
30393     ** where NN is a decimal number. The NN naming schemes are
30394     ** used by the test_multiplex.c module.
30395     */
30396     nDb = sqlite3Strlen30(zPath) - 1;
30397 #ifdef SQLITE_ENABLE_8_3_NAMES
30398     while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
30399     if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
30400 #else
30401     while( zPath[nDb]!='-' ){
30402       assert( nDb>0 );
30403       assert( zPath[nDb]!='\n' );
30404       nDb--;
30405     }
30406 #endif
30407     memcpy(zDb, zPath, nDb);
30408     zDb[nDb] = '\0';
30409 
30410     if( 0==osStat(zDb, &sStat) ){
30411       *pMode = sStat.st_mode & 0777;
30412       *pUid = sStat.st_uid;
30413       *pGid = sStat.st_gid;
30414     }else{
30415       rc = SQLITE_IOERR_FSTAT;
30416     }
30417   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
30418     *pMode = 0600;
30419   }
30420   return rc;
30421 }
30422 
30423 /*
30424 ** Open the file zPath.
30425 **
30426 ** Previously, the SQLite OS layer used three functions in place of this
30427 ** one:
30428 **
30429 **     sqlite3OsOpenReadWrite();
30430 **     sqlite3OsOpenReadOnly();
30431 **     sqlite3OsOpenExclusive();
30432 **
30433 ** These calls correspond to the following combinations of flags:
30434 **
30435 **     ReadWrite() ->     (READWRITE | CREATE)
30436 **     ReadOnly()  ->     (READONLY)
30437 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
30438 **
30439 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
30440 ** true, the file was configured to be automatically deleted when the
30441 ** file handle closed. To achieve the same effect using this new
30442 ** interface, add the DELETEONCLOSE flag to those specified above for
30443 ** OpenExclusive().
30444 */
30445 static int unixOpen(
30446   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
30447   const char *zPath,           /* Pathname of file to be opened */
30448   sqlite3_file *pFile,         /* The file descriptor to be filled in */
30449   int flags,                   /* Input flags to control the opening */
30450   int *pOutFlags               /* Output flags returned to SQLite core */
30451 ){
30452   unixFile *p = (unixFile *)pFile;
30453   int fd = -1;                   /* File descriptor returned by open() */
30454   int openFlags = 0;             /* Flags to pass to open() */
30455   int eType = flags&0xFFFFFF00;  /* Type of file to open */
30456   int noLock;                    /* True to omit locking primitives */
30457   int rc = SQLITE_OK;            /* Function Return Code */
30458   int ctrlFlags = 0;             /* UNIXFILE_* flags */
30459 
30460   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
30461   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
30462   int isCreate     = (flags & SQLITE_OPEN_CREATE);
30463   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
30464   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
30465 #if SQLITE_ENABLE_LOCKING_STYLE
30466   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
30467 #endif
30468 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
30469   struct statfs fsInfo;
30470 #endif
30471 
30472   /* If creating a master or main-file journal, this function will open
30473   ** a file-descriptor on the directory too. The first time unixSync()
30474   ** is called the directory file descriptor will be fsync()ed and close()d.
30475   */
30476   int syncDir = (isCreate && (
30477         eType==SQLITE_OPEN_MASTER_JOURNAL
30478      || eType==SQLITE_OPEN_MAIN_JOURNAL
30479      || eType==SQLITE_OPEN_WAL
30480   ));
30481 
30482   /* If argument zPath is a NULL pointer, this function is required to open
30483   ** a temporary file. Use this buffer to store the file name in.
30484   */
30485   char zTmpname[MAX_PATHNAME+2];
30486   const char *zName = zPath;
30487 
30488   /* Check the following statements are true:
30489   **
30490   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
30491   **   (b) if CREATE is set, then READWRITE must also be set, and
30492   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
30493   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
30494   */
30495   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
30496   assert(isCreate==0 || isReadWrite);
30497   assert(isExclusive==0 || isCreate);
30498   assert(isDelete==0 || isCreate);
30499 
30500   /* The main DB, main journal, WAL file and master journal are never
30501   ** automatically deleted. Nor are they ever temporary files.  */
30502   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
30503   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
30504   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
30505   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
30506 
30507   /* Assert that the upper layer has set one of the "file-type" flags. */
30508   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
30509        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
30510        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
30511        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
30512   );
30513 
30514   /* Detect a pid change and reset the PRNG.  There is a race condition
30515   ** here such that two or more threads all trying to open databases at
30516   ** the same instant might all reset the PRNG.  But multiple resets
30517   ** are harmless.
30518   */
30519   if( randomnessPid!=getpid() ){
30520     randomnessPid = getpid();
30521     sqlite3_randomness(0,0);
30522   }
30523 
30524   memset(p, 0, sizeof(unixFile));
30525 
30526   if( eType==SQLITE_OPEN_MAIN_DB ){
30527     UnixUnusedFd *pUnused;
30528     pUnused = findReusableFd(zName, flags);
30529     if( pUnused ){
30530       fd = pUnused->fd;
30531     }else{
30532       pUnused = sqlite3_malloc(sizeof(*pUnused));
30533       if( !pUnused ){
30534         return SQLITE_NOMEM;
30535       }
30536     }
30537     p->pUnused = pUnused;
30538 
30539     /* Database filenames are double-zero terminated if they are not
30540     ** URIs with parameters.  Hence, they can always be passed into
30541     ** sqlite3_uri_parameter(). */
30542     assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
30543 
30544   }else if( !zName ){
30545     /* If zName is NULL, the upper layer is requesting a temp file. */
30546     assert(isDelete && !syncDir);
30547     rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
30548     if( rc!=SQLITE_OK ){
30549       return rc;
30550     }
30551     zName = zTmpname;
30552 
30553     /* Generated temporary filenames are always double-zero terminated
30554     ** for use by sqlite3_uri_parameter(). */
30555     assert( zName[strlen(zName)+1]==0 );
30556   }
30557 
30558   /* Determine the value of the flags parameter passed to POSIX function
30559   ** open(). These must be calculated even if open() is not called, as
30560   ** they may be stored as part of the file handle and used by the
30561   ** 'conch file' locking functions later on.  */
30562   if( isReadonly )  openFlags |= O_RDONLY;
30563   if( isReadWrite ) openFlags |= O_RDWR;
30564   if( isCreate )    openFlags |= O_CREAT;
30565   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
30566   openFlags |= (O_LARGEFILE|O_BINARY);
30567 
30568   if( fd<0 ){
30569     mode_t openMode;              /* Permissions to create file with */
30570     uid_t uid;                    /* Userid for the file */
30571     gid_t gid;                    /* Groupid for the file */
30572     rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
30573     if( rc!=SQLITE_OK ){
30574       assert( !p->pUnused );
30575       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
30576       return rc;
30577     }
30578     fd = robust_open(zName, openFlags, openMode);
30579     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
30580     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
30581       /* Failed to open the file for read/write access. Try read-only. */
30582       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
30583       openFlags &= ~(O_RDWR|O_CREAT);
30584       flags |= SQLITE_OPEN_READONLY;
30585       openFlags |= O_RDONLY;
30586       isReadonly = 1;
30587       fd = robust_open(zName, openFlags, openMode);
30588     }
30589     if( fd<0 ){
30590       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
30591       goto open_finished;
30592     }
30593 
30594     /* If this process is running as root and if creating a new rollback
30595     ** journal or WAL file, set the ownership of the journal or WAL to be
30596     ** the same as the original database.
30597     */
30598     if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
30599       osFchown(fd, uid, gid);
30600     }
30601   }
30602   assert( fd>=0 );
30603   if( pOutFlags ){
30604     *pOutFlags = flags;
30605   }
30606 
30607   if( p->pUnused ){
30608     p->pUnused->fd = fd;
30609     p->pUnused->flags = flags;
30610   }
30611 
30612   if( isDelete ){
30613 #if OS_VXWORKS
30614     zPath = zName;
30615 #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
30616     zPath = sqlite3_mprintf("%s", zName);
30617     if( zPath==0 ){
30618       robust_close(p, fd, __LINE__);
30619       return SQLITE_NOMEM;
30620     }
30621 #else
30622     osUnlink(zName);
30623 #endif
30624   }
30625 #if SQLITE_ENABLE_LOCKING_STYLE
30626   else{
30627     p->openFlags = openFlags;
30628   }
30629 #endif
30630 
30631   noLock = eType!=SQLITE_OPEN_MAIN_DB;
30632 
30633 
30634 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
30635   if( fstatfs(fd, &fsInfo) == -1 ){
30636     ((unixFile*)pFile)->lastErrno = errno;
30637     robust_close(p, fd, __LINE__);
30638     return SQLITE_IOERR_ACCESS;
30639   }
30640   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
30641     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
30642   }
30643 #endif
30644 
30645   /* Set up appropriate ctrlFlags */
30646   if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
30647   if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
30648   if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
30649   if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
30650   if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
30651 
30652 #if SQLITE_ENABLE_LOCKING_STYLE
30653 #if SQLITE_PREFER_PROXY_LOCKING
30654   isAutoProxy = 1;
30655 #endif
30656   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
30657     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
30658     int useProxy = 0;
30659 
30660     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
30661     ** never use proxy, NULL means use proxy for non-local files only.  */
30662     if( envforce!=NULL ){
30663       useProxy = atoi(envforce)>0;
30664     }else{
30665       if( statfs(zPath, &fsInfo) == -1 ){
30666         /* In theory, the close(fd) call is sub-optimal. If the file opened
30667         ** with fd is a database file, and there are other connections open
30668         ** on that file that are currently holding advisory locks on it,
30669         ** then the call to close() will cancel those locks. In practice,
30670         ** we're assuming that statfs() doesn't fail very often. At least
30671         ** not while other file descriptors opened by the same process on
30672         ** the same file are working.  */
30673         p->lastErrno = errno;
30674         robust_close(p, fd, __LINE__);
30675         rc = SQLITE_IOERR_ACCESS;
30676         goto open_finished;
30677       }
30678       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
30679     }
30680     if( useProxy ){
30681       rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
30682       if( rc==SQLITE_OK ){
30683         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
30684         if( rc!=SQLITE_OK ){
30685           /* Use unixClose to clean up the resources added in fillInUnixFile
30686           ** and clear all the structure's references.  Specifically,
30687           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
30688           */
30689           unixClose(pFile);
30690           return rc;
30691         }
30692       }
30693       goto open_finished;
30694     }
30695   }
30696 #endif
30697 
30698   rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
30699 
30700 open_finished:
30701   if( rc!=SQLITE_OK ){
30702     sqlite3_free(p->pUnused);
30703   }
30704   return rc;
30705 }
30706 
30707 
30708 /*
30709 ** Delete the file at zPath. If the dirSync argument is true, fsync()
30710 ** the directory after deleting the file.
30711 */
30712 static int unixDelete(
30713   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
30714   const char *zPath,        /* Name of file to be deleted */
30715   int dirSync               /* If true, fsync() directory after deleting file */
30716 ){
30717   int rc = SQLITE_OK;
30718   UNUSED_PARAMETER(NotUsed);
30719   SimulateIOError(return SQLITE_IOERR_DELETE);
30720   if( osUnlink(zPath)==(-1) ){
30721     if( errno==ENOENT
30722 #if OS_VXWORKS
30723         || osAccess(zPath,0)!=0
30724 #endif
30725     ){
30726       rc = SQLITE_IOERR_DELETE_NOENT;
30727     }else{
30728       rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
30729     }
30730     return rc;
30731   }
30732 #ifndef SQLITE_DISABLE_DIRSYNC
30733   if( (dirSync & 1)!=0 ){
30734     int fd;
30735     rc = osOpenDirectory(zPath, &fd);
30736     if( rc==SQLITE_OK ){
30737 #if OS_VXWORKS
30738       if( fsync(fd)==-1 )
30739 #else
30740       if( fsync(fd) )
30741 #endif
30742       {
30743         rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
30744       }
30745       robust_close(0, fd, __LINE__);
30746     }else if( rc==SQLITE_CANTOPEN ){
30747       rc = SQLITE_OK;
30748     }
30749   }
30750 #endif
30751   return rc;
30752 }
30753 
30754 /*
30755 ** Test the existence of or access permissions of file zPath. The
30756 ** test performed depends on the value of flags:
30757 **
30758 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
30759 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
30760 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
30761 **
30762 ** Otherwise return 0.
30763 */
30764 static int unixAccess(
30765   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
30766   const char *zPath,      /* Path of the file to examine */
30767   int flags,              /* What do we want to learn about the zPath file? */
30768   int *pResOut            /* Write result boolean here */
30769 ){
30770   int amode = 0;
30771   UNUSED_PARAMETER(NotUsed);
30772   SimulateIOError( return SQLITE_IOERR_ACCESS; );
30773   switch( flags ){
30774     case SQLITE_ACCESS_EXISTS:
30775       amode = F_OK;
30776       break;
30777     case SQLITE_ACCESS_READWRITE:
30778       amode = W_OK|R_OK;
30779       break;
30780     case SQLITE_ACCESS_READ:
30781       amode = R_OK;
30782       break;
30783 
30784     default:
30785       assert(!"Invalid flags argument");
30786   }
30787   *pResOut = (osAccess(zPath, amode)==0);
30788   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
30789     struct stat buf;
30790     if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
30791       *pResOut = 0;
30792     }
30793   }
30794   return SQLITE_OK;
30795 }
30796 
30797 
30798 /*
30799 ** Turn a relative pathname into a full pathname. The relative path
30800 ** is stored as a nul-terminated string in the buffer pointed to by
30801 ** zPath.
30802 **
30803 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
30804 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
30805 ** this buffer before returning.
30806 */
30807 static int unixFullPathname(
30808   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
30809   const char *zPath,            /* Possibly relative input path */
30810   int nOut,                     /* Size of output buffer in bytes */
30811   char *zOut                    /* Output buffer */
30812 ){
30813 
30814   /* It's odd to simulate an io-error here, but really this is just
30815   ** using the io-error infrastructure to test that SQLite handles this
30816   ** function failing. This function could fail if, for example, the
30817   ** current working directory has been unlinked.
30818   */
30819   SimulateIOError( return SQLITE_ERROR );
30820 
30821   assert( pVfs->mxPathname==MAX_PATHNAME );
30822   UNUSED_PARAMETER(pVfs);
30823 
30824   zOut[nOut-1] = '\0';
30825   if( zPath[0]=='/' ){
30826     sqlite3_snprintf(nOut, zOut, "%s", zPath);
30827   }else{
30828     int nCwd;
30829     if( osGetcwd(zOut, nOut-1)==0 ){
30830       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
30831     }
30832     nCwd = (int)strlen(zOut);
30833     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
30834   }
30835   return SQLITE_OK;
30836 }
30837 
30838 
30839 #ifndef SQLITE_OMIT_LOAD_EXTENSION
30840 /*
30841 ** Interfaces for opening a shared library, finding entry points
30842 ** within the shared library, and closing the shared library.
30843 */
30844 #include <dlfcn.h>
30845 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
30846   UNUSED_PARAMETER(NotUsed);
30847   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
30848 }
30849 
30850 /*
30851 ** SQLite calls this function immediately after a call to unixDlSym() or
30852 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
30853 ** message is available, it is written to zBufOut. If no error message
30854 ** is available, zBufOut is left unmodified and SQLite uses a default
30855 ** error message.
30856 */
30857 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
30858   const char *zErr;
30859   UNUSED_PARAMETER(NotUsed);
30860   unixEnterMutex();
30861   zErr = dlerror();
30862   if( zErr ){
30863     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
30864   }
30865   unixLeaveMutex();
30866 }
30867 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
30868   /*
30869   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
30870   ** cast into a pointer to a function.  And yet the library dlsym() routine
30871   ** returns a void* which is really a pointer to a function.  So how do we
30872   ** use dlsym() with -pedantic-errors?
30873   **
30874   ** Variable x below is defined to be a pointer to a function taking
30875   ** parameters void* and const char* and returning a pointer to a function.
30876   ** We initialize x by assigning it a pointer to the dlsym() function.
30877   ** (That assignment requires a cast.)  Then we call the function that
30878   ** x points to.
30879   **
30880   ** This work-around is unlikely to work correctly on any system where
30881   ** you really cannot cast a function pointer into void*.  But then, on the
30882   ** other hand, dlsym() will not work on such a system either, so we have
30883   ** not really lost anything.
30884   */
30885   void (*(*x)(void*,const char*))(void);
30886   UNUSED_PARAMETER(NotUsed);
30887   x = (void(*(*)(void*,const char*))(void))dlsym;
30888   return (*x)(p, zSym);
30889 }
30890 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
30891   UNUSED_PARAMETER(NotUsed);
30892   dlclose(pHandle);
30893 }
30894 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
30895   #define unixDlOpen  0
30896   #define unixDlError 0
30897   #define unixDlSym   0
30898   #define unixDlClose 0
30899 #endif
30900 
30901 /*
30902 ** Write nBuf bytes of random data to the supplied buffer zBuf.
30903 */
30904 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
30905   UNUSED_PARAMETER(NotUsed);
30906   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
30907 
30908   /* We have to initialize zBuf to prevent valgrind from reporting
30909   ** errors.  The reports issued by valgrind are incorrect - we would
30910   ** prefer that the randomness be increased by making use of the
30911   ** uninitialized space in zBuf - but valgrind errors tend to worry
30912   ** some users.  Rather than argue, it seems easier just to initialize
30913   ** the whole array and silence valgrind, even if that means less randomness
30914   ** in the random seed.
30915   **
30916   ** When testing, initializing zBuf[] to zero is all we do.  That means
30917   ** that we always use the same random number sequence.  This makes the
30918   ** tests repeatable.
30919   */
30920   memset(zBuf, 0, nBuf);
30921   randomnessPid = getpid();
30922 #if !defined(SQLITE_TEST)
30923   {
30924     int fd, got;
30925     fd = robust_open("/dev/urandom", O_RDONLY, 0);
30926     if( fd<0 ){
30927       time_t t;
30928       time(&t);
30929       memcpy(zBuf, &t, sizeof(t));
30930       memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
30931       assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
30932       nBuf = sizeof(t) + sizeof(randomnessPid);
30933     }else{
30934       do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
30935       robust_close(0, fd, __LINE__);
30936     }
30937   }
30938 #endif
30939   return nBuf;
30940 }
30941 
30942 
30943 /*
30944 ** Sleep for a little while.  Return the amount of time slept.
30945 ** The argument is the number of microseconds we want to sleep.
30946 ** The return value is the number of microseconds of sleep actually
30947 ** requested from the underlying operating system, a number which
30948 ** might be greater than or equal to the argument, but not less
30949 ** than the argument.
30950 */
30951 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
30952 #if OS_VXWORKS
30953   struct timespec sp;
30954 
30955   sp.tv_sec = microseconds / 1000000;
30956   sp.tv_nsec = (microseconds % 1000000) * 1000;
30957   nanosleep(&sp, NULL);
30958   UNUSED_PARAMETER(NotUsed);
30959   return microseconds;
30960 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
30961   usleep(microseconds);
30962   UNUSED_PARAMETER(NotUsed);
30963   return microseconds;
30964 #else
30965   int seconds = (microseconds+999999)/1000000;
30966   sleep(seconds);
30967   UNUSED_PARAMETER(NotUsed);
30968   return seconds*1000000;
30969 #endif
30970 }
30971 
30972 /*
30973 ** The following variable, if set to a non-zero value, is interpreted as
30974 ** the number of seconds since 1970 and is used to set the result of
30975 ** sqlite3OsCurrentTime() during testing.
30976 */
30977 #ifdef SQLITE_TEST
30978 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
30979 #endif
30980 
30981 /*
30982 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
30983 ** the current time and date as a Julian Day number times 86_400_000.  In
30984 ** other words, write into *piNow the number of milliseconds since the Julian
30985 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
30986 ** proleptic Gregorian calendar.
30987 **
30988 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
30989 ** cannot be found.
30990 */
30991 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
30992   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
30993   int rc = SQLITE_OK;
30994 #if defined(NO_GETTOD)
30995   time_t t;
30996   time(&t);
30997   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
30998 #elif OS_VXWORKS
30999   struct timespec sNow;
31000   clock_gettime(CLOCK_REALTIME, &sNow);
31001   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
31002 #else
31003   struct timeval sNow;
31004   if( gettimeofday(&sNow, 0)==0 ){
31005     *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
31006   }else{
31007     rc = SQLITE_ERROR;
31008   }
31009 #endif
31010 
31011 #ifdef SQLITE_TEST
31012   if( sqlite3_current_time ){
31013     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
31014   }
31015 #endif
31016   UNUSED_PARAMETER(NotUsed);
31017   return rc;
31018 }
31019 
31020 /*
31021 ** Find the current time (in Universal Coordinated Time).  Write the
31022 ** current time and date as a Julian Day number into *prNow and
31023 ** return 0.  Return 1 if the time and date cannot be found.
31024 */
31025 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
31026   sqlite3_int64 i = 0;
31027   int rc;
31028   UNUSED_PARAMETER(NotUsed);
31029   rc = unixCurrentTimeInt64(0, &i);
31030   *prNow = i/86400000.0;
31031   return rc;
31032 }
31033 
31034 /*
31035 ** We added the xGetLastError() method with the intention of providing
31036 ** better low-level error messages when operating-system problems come up
31037 ** during SQLite operation.  But so far, none of that has been implemented
31038 ** in the core.  So this routine is never called.  For now, it is merely
31039 ** a place-holder.
31040 */
31041 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
31042   UNUSED_PARAMETER(NotUsed);
31043   UNUSED_PARAMETER(NotUsed2);
31044   UNUSED_PARAMETER(NotUsed3);
31045   return 0;
31046 }
31047 
31048 
31049 /*
31050 ************************ End of sqlite3_vfs methods ***************************
31051 ******************************************************************************/
31052 
31053 /******************************************************************************
31054 ************************** Begin Proxy Locking ********************************
31055 **
31056 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
31057 ** other locking methods on secondary lock files.  Proxy locking is a
31058 ** meta-layer over top of the primitive locking implemented above.  For
31059 ** this reason, the division that implements of proxy locking is deferred
31060 ** until late in the file (here) after all of the other I/O methods have
31061 ** been defined - so that the primitive locking methods are available
31062 ** as services to help with the implementation of proxy locking.
31063 **
31064 ****
31065 **
31066 ** The default locking schemes in SQLite use byte-range locks on the
31067 ** database file to coordinate safe, concurrent access by multiple readers
31068 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
31069 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
31070 ** as POSIX read & write locks over fixed set of locations (via fsctl),
31071 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
31072 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
31073 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
31074 ** address in the shared range is taken for a SHARED lock, the entire
31075 ** shared range is taken for an EXCLUSIVE lock):
31076 **
31077 **      PENDING_BYTE        0x40000000
31078 **      RESERVED_BYTE       0x40000001
31079 **      SHARED_RANGE        0x40000002 -> 0x40000200
31080 **
31081 ** This works well on the local file system, but shows a nearly 100x
31082 ** slowdown in read performance on AFP because the AFP client disables
31083 ** the read cache when byte-range locks are present.  Enabling the read
31084 ** cache exposes a cache coherency problem that is present on all OS X
31085 ** supported network file systems.  NFS and AFP both observe the
31086 ** close-to-open semantics for ensuring cache coherency
31087 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
31088 ** address the requirements for concurrent database access by multiple
31089 ** readers and writers
31090 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
31091 **
31092 ** To address the performance and cache coherency issues, proxy file locking
31093 ** changes the way database access is controlled by limiting access to a
31094 ** single host at a time and moving file locks off of the database file
31095 ** and onto a proxy file on the local file system.
31096 **
31097 **
31098 ** Using proxy locks
31099 ** -----------------
31100 **
31101 ** C APIs
31102 **
31103 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
31104 **                       <proxy_path> | ":auto:");
31105 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
31106 **
31107 **
31108 ** SQL pragmas
31109 **
31110 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
31111 **  PRAGMA [database.]lock_proxy_file
31112 **
31113 ** Specifying ":auto:" means that if there is a conch file with a matching
31114 ** host ID in it, the proxy path in the conch file will be used, otherwise
31115 ** a proxy path based on the user's temp dir
31116 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
31117 ** actual proxy file name is generated from the name and path of the
31118 ** database file.  For example:
31119 **
31120 **       For database path "/Users/me/foo.db"
31121 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
31122 **
31123 ** Once a lock proxy is configured for a database connection, it can not
31124 ** be removed, however it may be switched to a different proxy path via
31125 ** the above APIs (assuming the conch file is not being held by another
31126 ** connection or process).
31127 **
31128 **
31129 ** How proxy locking works
31130 ** -----------------------
31131 **
31132 ** Proxy file locking relies primarily on two new supporting files:
31133 **
31134 **   *  conch file to limit access to the database file to a single host
31135 **      at a time
31136 **
31137 **   *  proxy file to act as a proxy for the advisory locks normally
31138 **      taken on the database
31139 **
31140 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
31141 ** by taking an sqlite-style shared lock on the conch file, reading the
31142 ** contents and comparing the host's unique host ID (see below) and lock
31143 ** proxy path against the values stored in the conch.  The conch file is
31144 ** stored in the same directory as the database file and the file name
31145 ** is patterned after the database file name as ".<databasename>-conch".
31146 ** If the conch file does not exist, or its contents do not match the
31147 ** host ID and/or proxy path, then the lock is escalated to an exclusive
31148 ** lock and the conch file contents is updated with the host ID and proxy
31149 ** path and the lock is downgraded to a shared lock again.  If the conch
31150 ** is held by another process (with a shared lock), the exclusive lock
31151 ** will fail and SQLITE_BUSY is returned.
31152 **
31153 ** The proxy file - a single-byte file used for all advisory file locks
31154 ** normally taken on the database file.   This allows for safe sharing
31155 ** of the database file for multiple readers and writers on the same
31156 ** host (the conch ensures that they all use the same local lock file).
31157 **
31158 ** Requesting the lock proxy does not immediately take the conch, it is
31159 ** only taken when the first request to lock database file is made.
31160 ** This matches the semantics of the traditional locking behavior, where
31161 ** opening a connection to a database file does not take a lock on it.
31162 ** The shared lock and an open file descriptor are maintained until
31163 ** the connection to the database is closed.
31164 **
31165 ** The proxy file and the lock file are never deleted so they only need
31166 ** to be created the first time they are used.
31167 **
31168 ** Configuration options
31169 ** ---------------------
31170 **
31171 **  SQLITE_PREFER_PROXY_LOCKING
31172 **
31173 **       Database files accessed on non-local file systems are
31174 **       automatically configured for proxy locking, lock files are
31175 **       named automatically using the same logic as
31176 **       PRAGMA lock_proxy_file=":auto:"
31177 **
31178 **  SQLITE_PROXY_DEBUG
31179 **
31180 **       Enables the logging of error messages during host id file
31181 **       retrieval and creation
31182 **
31183 **  LOCKPROXYDIR
31184 **
31185 **       Overrides the default directory used for lock proxy files that
31186 **       are named automatically via the ":auto:" setting
31187 **
31188 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
31189 **
31190 **       Permissions to use when creating a directory for storing the
31191 **       lock proxy files, only used when LOCKPROXYDIR is not set.
31192 **
31193 **
31194 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
31195 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
31196 ** force proxy locking to be used for every database file opened, and 0
31197 ** will force automatic proxy locking to be disabled for all database
31198 ** files (explicitly calling the SQLITE_SET_LOCKPROXYFILE pragma or
31199 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
31200 */
31201 
31202 /*
31203 ** Proxy locking is only available on MacOSX
31204 */
31205 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31206 
31207 /*
31208 ** The proxyLockingContext has the path and file structures for the remote
31209 ** and local proxy files in it
31210 */
31211 typedef struct proxyLockingContext proxyLockingContext;
31212 struct proxyLockingContext {
31213   unixFile *conchFile;         /* Open conch file */
31214   char *conchFilePath;         /* Name of the conch file */
31215   unixFile *lockProxy;         /* Open proxy lock file */
31216   char *lockProxyPath;         /* Name of the proxy lock file */
31217   char *dbPath;                /* Name of the open file */
31218   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
31219   void *oldLockingContext;     /* Original lockingcontext to restore on close */
31220   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
31221 };
31222 
31223 /*
31224 ** The proxy lock file path for the database at dbPath is written into lPath,
31225 ** which must point to valid, writable memory large enough for a maxLen length
31226 ** file path.
31227 */
31228 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
31229   int len;
31230   int dbLen;
31231   int i;
31232 
31233 #ifdef LOCKPROXYDIR
31234   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
31235 #else
31236 # ifdef _CS_DARWIN_USER_TEMP_DIR
31237   {
31238     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
31239       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
31240                lPath, errno, getpid()));
31241       return SQLITE_IOERR_LOCK;
31242     }
31243     len = strlcat(lPath, "sqliteplocks", maxLen);
31244   }
31245 # else
31246   len = strlcpy(lPath, "/tmp/", maxLen);
31247 # endif
31248 #endif
31249 
31250   if( lPath[len-1]!='/' ){
31251     len = strlcat(lPath, "/", maxLen);
31252   }
31253 
31254   /* transform the db path to a unique cache name */
31255   dbLen = (int)strlen(dbPath);
31256   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
31257     char c = dbPath[i];
31258     lPath[i+len] = (c=='/')?'_':c;
31259   }
31260   lPath[i+len]='\0';
31261   strlcat(lPath, ":auto:", maxLen);
31262   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
31263   return SQLITE_OK;
31264 }
31265 
31266 /*
31267  ** Creates the lock file and any missing directories in lockPath
31268  */
31269 static int proxyCreateLockPath(const char *lockPath){
31270   int i, len;
31271   char buf[MAXPATHLEN];
31272   int start = 0;
31273 
31274   assert(lockPath!=NULL);
31275   /* try to create all the intermediate directories */
31276   len = (int)strlen(lockPath);
31277   buf[0] = lockPath[0];
31278   for( i=1; i<len; i++ ){
31279     if( lockPath[i] == '/' && (i - start > 0) ){
31280       /* only mkdir if leaf dir != "." or "/" or ".." */
31281       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
31282          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
31283         buf[i]='\0';
31284         if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
31285           int err=errno;
31286           if( err!=EEXIST ) {
31287             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
31288                      "'%s' proxy lock path=%s pid=%d\n",
31289                      buf, strerror(err), lockPath, getpid()));
31290             return err;
31291           }
31292         }
31293       }
31294       start=i+1;
31295     }
31296     buf[i] = lockPath[i];
31297   }
31298   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
31299   return 0;
31300 }
31301 
31302 /*
31303 ** Create a new VFS file descriptor (stored in memory obtained from
31304 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
31305 **
31306 ** The caller is responsible not only for closing the file descriptor
31307 ** but also for freeing the memory associated with the file descriptor.
31308 */
31309 static int proxyCreateUnixFile(
31310     const char *path,        /* path for the new unixFile */
31311     unixFile **ppFile,       /* unixFile created and returned by ref */
31312     int islockfile           /* if non zero missing dirs will be created */
31313 ) {
31314   int fd = -1;
31315   unixFile *pNew;
31316   int rc = SQLITE_OK;
31317   int openFlags = O_RDWR | O_CREAT;
31318   sqlite3_vfs dummyVfs;
31319   int terrno = 0;
31320   UnixUnusedFd *pUnused = NULL;
31321 
31322   /* 1. first try to open/create the file
31323   ** 2. if that fails, and this is a lock file (not-conch), try creating
31324   ** the parent directories and then try again.
31325   ** 3. if that fails, try to open the file read-only
31326   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
31327   */
31328   pUnused = findReusableFd(path, openFlags);
31329   if( pUnused ){
31330     fd = pUnused->fd;
31331   }else{
31332     pUnused = sqlite3_malloc(sizeof(*pUnused));
31333     if( !pUnused ){
31334       return SQLITE_NOMEM;
31335     }
31336   }
31337   if( fd<0 ){
31338     fd = robust_open(path, openFlags, 0);
31339     terrno = errno;
31340     if( fd<0 && errno==ENOENT && islockfile ){
31341       if( proxyCreateLockPath(path) == SQLITE_OK ){
31342         fd = robust_open(path, openFlags, 0);
31343       }
31344     }
31345   }
31346   if( fd<0 ){
31347     openFlags = O_RDONLY;
31348     fd = robust_open(path, openFlags, 0);
31349     terrno = errno;
31350   }
31351   if( fd<0 ){
31352     if( islockfile ){
31353       return SQLITE_BUSY;
31354     }
31355     switch (terrno) {
31356       case EACCES:
31357         return SQLITE_PERM;
31358       case EIO:
31359         return SQLITE_IOERR_LOCK; /* even though it is the conch */
31360       default:
31361         return SQLITE_CANTOPEN_BKPT;
31362     }
31363   }
31364 
31365   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
31366   if( pNew==NULL ){
31367     rc = SQLITE_NOMEM;
31368     goto end_create_proxy;
31369   }
31370   memset(pNew, 0, sizeof(unixFile));
31371   pNew->openFlags = openFlags;
31372   memset(&dummyVfs, 0, sizeof(dummyVfs));
31373   dummyVfs.pAppData = (void*)&autolockIoFinder;
31374   dummyVfs.zName = "dummy";
31375   pUnused->fd = fd;
31376   pUnused->flags = openFlags;
31377   pNew->pUnused = pUnused;
31378 
31379   rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
31380   if( rc==SQLITE_OK ){
31381     *ppFile = pNew;
31382     return SQLITE_OK;
31383   }
31384 end_create_proxy:
31385   robust_close(pNew, fd, __LINE__);
31386   sqlite3_free(pNew);
31387   sqlite3_free(pUnused);
31388   return rc;
31389 }
31390 
31391 #ifdef SQLITE_TEST
31392 /* simulate multiple hosts by creating unique hostid file paths */
31393 SQLITE_API int sqlite3_hostid_num = 0;
31394 #endif
31395 
31396 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
31397 
31398 /* Not always defined in the headers as it ought to be */
31399 extern int gethostuuid(uuid_t id, const struct timespec *wait);
31400 
31401 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
31402 ** bytes of writable memory.
31403 */
31404 static int proxyGetHostID(unsigned char *pHostID, int *pError){
31405   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
31406   memset(pHostID, 0, PROXY_HOSTIDLEN);
31407 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
31408                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
31409   {
31410     static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
31411     if( gethostuuid(pHostID, &timeout) ){
31412       int err = errno;
31413       if( pError ){
31414         *pError = err;
31415       }
31416       return SQLITE_IOERR;
31417     }
31418   }
31419 #else
31420   UNUSED_PARAMETER(pError);
31421 #endif
31422 #ifdef SQLITE_TEST
31423   /* simulate multiple hosts by creating unique hostid file paths */
31424   if( sqlite3_hostid_num != 0){
31425     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
31426   }
31427 #endif
31428 
31429   return SQLITE_OK;
31430 }
31431 
31432 /* The conch file contains the header, host id and lock file path
31433  */
31434 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
31435 #define PROXY_HEADERLEN    1   /* conch file header length */
31436 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
31437 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
31438 
31439 /*
31440 ** Takes an open conch file, copies the contents to a new path and then moves
31441 ** it back.  The newly created file's file descriptor is assigned to the
31442 ** conch file structure and finally the original conch file descriptor is
31443 ** closed.  Returns zero if successful.
31444 */
31445 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
31446   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31447   unixFile *conchFile = pCtx->conchFile;
31448   char tPath[MAXPATHLEN];
31449   char buf[PROXY_MAXCONCHLEN];
31450   char *cPath = pCtx->conchFilePath;
31451   size_t readLen = 0;
31452   size_t pathLen = 0;
31453   char errmsg[64] = "";
31454   int fd = -1;
31455   int rc = -1;
31456   UNUSED_PARAMETER(myHostID);
31457 
31458   /* create a new path by replace the trailing '-conch' with '-break' */
31459   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
31460   if( pathLen>MAXPATHLEN || pathLen<6 ||
31461      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
31462     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
31463     goto end_breaklock;
31464   }
31465   /* read the conch content */
31466   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
31467   if( readLen<PROXY_PATHINDEX ){
31468     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
31469     goto end_breaklock;
31470   }
31471   /* write it out to the temporary break file */
31472   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
31473   if( fd<0 ){
31474     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
31475     goto end_breaklock;
31476   }
31477   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
31478     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
31479     goto end_breaklock;
31480   }
31481   if( rename(tPath, cPath) ){
31482     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
31483     goto end_breaklock;
31484   }
31485   rc = 0;
31486   fprintf(stderr, "broke stale lock on %s\n", cPath);
31487   robust_close(pFile, conchFile->h, __LINE__);
31488   conchFile->h = fd;
31489   conchFile->openFlags = O_RDWR | O_CREAT;
31490 
31491 end_breaklock:
31492   if( rc ){
31493     if( fd>=0 ){
31494       osUnlink(tPath);
31495       robust_close(pFile, fd, __LINE__);
31496     }
31497     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
31498   }
31499   return rc;
31500 }
31501 
31502 /* Take the requested lock on the conch file and break a stale lock if the
31503 ** host id matches.
31504 */
31505 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
31506   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31507   unixFile *conchFile = pCtx->conchFile;
31508   int rc = SQLITE_OK;
31509   int nTries = 0;
31510   struct timespec conchModTime;
31511 
31512   memset(&conchModTime, 0, sizeof(conchModTime));
31513   do {
31514     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
31515     nTries ++;
31516     if( rc==SQLITE_BUSY ){
31517       /* If the lock failed (busy):
31518        * 1st try: get the mod time of the conch, wait 0.5s and try again.
31519        * 2nd try: fail if the mod time changed or host id is different, wait
31520        *           10 sec and try again
31521        * 3rd try: break the lock unless the mod time has changed.
31522        */
31523       struct stat buf;
31524       if( osFstat(conchFile->h, &buf) ){
31525         pFile->lastErrno = errno;
31526         return SQLITE_IOERR_LOCK;
31527       }
31528 
31529       if( nTries==1 ){
31530         conchModTime = buf.st_mtimespec;
31531         usleep(500000); /* wait 0.5 sec and try the lock again*/
31532         continue;
31533       }
31534 
31535       assert( nTries>1 );
31536       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
31537          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
31538         return SQLITE_BUSY;
31539       }
31540 
31541       if( nTries==2 ){
31542         char tBuf[PROXY_MAXCONCHLEN];
31543         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
31544         if( len<0 ){
31545           pFile->lastErrno = errno;
31546           return SQLITE_IOERR_LOCK;
31547         }
31548         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
31549           /* don't break the lock if the host id doesn't match */
31550           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
31551             return SQLITE_BUSY;
31552           }
31553         }else{
31554           /* don't break the lock on short read or a version mismatch */
31555           return SQLITE_BUSY;
31556         }
31557         usleep(10000000); /* wait 10 sec and try the lock again */
31558         continue;
31559       }
31560 
31561       assert( nTries==3 );
31562       if( 0==proxyBreakConchLock(pFile, myHostID) ){
31563         rc = SQLITE_OK;
31564         if( lockType==EXCLUSIVE_LOCK ){
31565           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
31566         }
31567         if( !rc ){
31568           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
31569         }
31570       }
31571     }
31572   } while( rc==SQLITE_BUSY && nTries<3 );
31573 
31574   return rc;
31575 }
31576 
31577 /* Takes the conch by taking a shared lock and read the contents conch, if
31578 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
31579 ** lockPath means that the lockPath in the conch file will be used if the
31580 ** host IDs match, or a new lock path will be generated automatically
31581 ** and written to the conch file.
31582 */
31583 static int proxyTakeConch(unixFile *pFile){
31584   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31585 
31586   if( pCtx->conchHeld!=0 ){
31587     return SQLITE_OK;
31588   }else{
31589     unixFile *conchFile = pCtx->conchFile;
31590     uuid_t myHostID;
31591     int pError = 0;
31592     char readBuf[PROXY_MAXCONCHLEN];
31593     char lockPath[MAXPATHLEN];
31594     char *tempLockPath = NULL;
31595     int rc = SQLITE_OK;
31596     int createConch = 0;
31597     int hostIdMatch = 0;
31598     int readLen = 0;
31599     int tryOldLockPath = 0;
31600     int forceNewLockPath = 0;
31601 
31602     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
31603              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
31604 
31605     rc = proxyGetHostID(myHostID, &pError);
31606     if( (rc&0xff)==SQLITE_IOERR ){
31607       pFile->lastErrno = pError;
31608       goto end_takeconch;
31609     }
31610     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
31611     if( rc!=SQLITE_OK ){
31612       goto end_takeconch;
31613     }
31614     /* read the existing conch file */
31615     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
31616     if( readLen<0 ){
31617       /* I/O error: lastErrno set by seekAndRead */
31618       pFile->lastErrno = conchFile->lastErrno;
31619       rc = SQLITE_IOERR_READ;
31620       goto end_takeconch;
31621     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
31622              readBuf[0]!=(char)PROXY_CONCHVERSION ){
31623       /* a short read or version format mismatch means we need to create a new
31624       ** conch file.
31625       */
31626       createConch = 1;
31627     }
31628     /* if the host id matches and the lock path already exists in the conch
31629     ** we'll try to use the path there, if we can't open that path, we'll
31630     ** retry with a new auto-generated path
31631     */
31632     do { /* in case we need to try again for an :auto: named lock file */
31633 
31634       if( !createConch && !forceNewLockPath ){
31635         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
31636                                   PROXY_HOSTIDLEN);
31637         /* if the conch has data compare the contents */
31638         if( !pCtx->lockProxyPath ){
31639           /* for auto-named local lock file, just check the host ID and we'll
31640            ** use the local lock file path that's already in there
31641            */
31642           if( hostIdMatch ){
31643             size_t pathLen = (readLen - PROXY_PATHINDEX);
31644 
31645             if( pathLen>=MAXPATHLEN ){
31646               pathLen=MAXPATHLEN-1;
31647             }
31648             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
31649             lockPath[pathLen] = 0;
31650             tempLockPath = lockPath;
31651             tryOldLockPath = 1;
31652             /* create a copy of the lock path if the conch is taken */
31653             goto end_takeconch;
31654           }
31655         }else if( hostIdMatch
31656                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
31657                            readLen-PROXY_PATHINDEX)
31658         ){
31659           /* conch host and lock path match */
31660           goto end_takeconch;
31661         }
31662       }
31663 
31664       /* if the conch isn't writable and doesn't match, we can't take it */
31665       if( (conchFile->openFlags&O_RDWR) == 0 ){
31666         rc = SQLITE_BUSY;
31667         goto end_takeconch;
31668       }
31669 
31670       /* either the conch didn't match or we need to create a new one */
31671       if( !pCtx->lockProxyPath ){
31672         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
31673         tempLockPath = lockPath;
31674         /* create a copy of the lock path _only_ if the conch is taken */
31675       }
31676 
31677       /* update conch with host and path (this will fail if other process
31678       ** has a shared lock already), if the host id matches, use the big
31679       ** stick.
31680       */
31681       futimes(conchFile->h, NULL);
31682       if( hostIdMatch && !createConch ){
31683         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
31684           /* We are trying for an exclusive lock but another thread in this
31685            ** same process is still holding a shared lock. */
31686           rc = SQLITE_BUSY;
31687         } else {
31688           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
31689         }
31690       }else{
31691         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
31692       }
31693       if( rc==SQLITE_OK ){
31694         char writeBuffer[PROXY_MAXCONCHLEN];
31695         int writeSize = 0;
31696 
31697         writeBuffer[0] = (char)PROXY_CONCHVERSION;
31698         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
31699         if( pCtx->lockProxyPath!=NULL ){
31700           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
31701         }else{
31702           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
31703         }
31704         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
31705         robust_ftruncate(conchFile->h, writeSize);
31706         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
31707         fsync(conchFile->h);
31708         /* If we created a new conch file (not just updated the contents of a
31709          ** valid conch file), try to match the permissions of the database
31710          */
31711         if( rc==SQLITE_OK && createConch ){
31712           struct stat buf;
31713           int err = osFstat(pFile->h, &buf);
31714           if( err==0 ){
31715             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
31716                                         S_IROTH|S_IWOTH);
31717             /* try to match the database file R/W permissions, ignore failure */
31718 #ifndef SQLITE_PROXY_DEBUG
31719             osFchmod(conchFile->h, cmode);
31720 #else
31721             do{
31722               rc = osFchmod(conchFile->h, cmode);
31723             }while( rc==(-1) && errno==EINTR );
31724             if( rc!=0 ){
31725               int code = errno;
31726               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
31727                       cmode, code, strerror(code));
31728             } else {
31729               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
31730             }
31731           }else{
31732             int code = errno;
31733             fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
31734                     err, code, strerror(code));
31735 #endif
31736           }
31737         }
31738       }
31739       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
31740 
31741     end_takeconch:
31742       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
31743       if( rc==SQLITE_OK && pFile->openFlags ){
31744         int fd;
31745         if( pFile->h>=0 ){
31746           robust_close(pFile, pFile->h, __LINE__);
31747         }
31748         pFile->h = -1;
31749         fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
31750         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
31751         if( fd>=0 ){
31752           pFile->h = fd;
31753         }else{
31754           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
31755            during locking */
31756         }
31757       }
31758       if( rc==SQLITE_OK && !pCtx->lockProxy ){
31759         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
31760         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
31761         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
31762           /* we couldn't create the proxy lock file with the old lock file path
31763            ** so try again via auto-naming
31764            */
31765           forceNewLockPath = 1;
31766           tryOldLockPath = 0;
31767           continue; /* go back to the do {} while start point, try again */
31768         }
31769       }
31770       if( rc==SQLITE_OK ){
31771         /* Need to make a copy of path if we extracted the value
31772          ** from the conch file or the path was allocated on the stack
31773          */
31774         if( tempLockPath ){
31775           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
31776           if( !pCtx->lockProxyPath ){
31777             rc = SQLITE_NOMEM;
31778           }
31779         }
31780       }
31781       if( rc==SQLITE_OK ){
31782         pCtx->conchHeld = 1;
31783 
31784         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
31785           afpLockingContext *afpCtx;
31786           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
31787           afpCtx->dbPath = pCtx->lockProxyPath;
31788         }
31789       } else {
31790         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
31791       }
31792       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
31793                rc==SQLITE_OK?"ok":"failed"));
31794       return rc;
31795     } while (1); /* in case we need to retry the :auto: lock file -
31796                  ** we should never get here except via the 'continue' call. */
31797   }
31798 }
31799 
31800 /*
31801 ** If pFile holds a lock on a conch file, then release that lock.
31802 */
31803 static int proxyReleaseConch(unixFile *pFile){
31804   int rc = SQLITE_OK;         /* Subroutine return code */
31805   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
31806   unixFile *conchFile;        /* Name of the conch file */
31807 
31808   pCtx = (proxyLockingContext *)pFile->lockingContext;
31809   conchFile = pCtx->conchFile;
31810   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
31811            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
31812            getpid()));
31813   if( pCtx->conchHeld>0 ){
31814     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
31815   }
31816   pCtx->conchHeld = 0;
31817   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
31818            (rc==SQLITE_OK ? "ok" : "failed")));
31819   return rc;
31820 }
31821 
31822 /*
31823 ** Given the name of a database file, compute the name of its conch file.
31824 ** Store the conch filename in memory obtained from sqlite3_malloc().
31825 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
31826 ** or SQLITE_NOMEM if unable to obtain memory.
31827 **
31828 ** The caller is responsible for ensuring that the allocated memory
31829 ** space is eventually freed.
31830 **
31831 ** *pConchPath is set to NULL if a memory allocation error occurs.
31832 */
31833 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
31834   int i;                        /* Loop counter */
31835   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
31836   char *conchPath;              /* buffer in which to construct conch name */
31837 
31838   /* Allocate space for the conch filename and initialize the name to
31839   ** the name of the original database file. */
31840   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
31841   if( conchPath==0 ){
31842     return SQLITE_NOMEM;
31843   }
31844   memcpy(conchPath, dbPath, len+1);
31845 
31846   /* now insert a "." before the last / character */
31847   for( i=(len-1); i>=0; i-- ){
31848     if( conchPath[i]=='/' ){
31849       i++;
31850       break;
31851     }
31852   }
31853   conchPath[i]='.';
31854   while ( i<len ){
31855     conchPath[i+1]=dbPath[i];
31856     i++;
31857   }
31858 
31859   /* append the "-conch" suffix to the file */
31860   memcpy(&conchPath[i+1], "-conch", 7);
31861   assert( (int)strlen(conchPath) == len+7 );
31862 
31863   return SQLITE_OK;
31864 }
31865 
31866 
31867 /* Takes a fully configured proxy locking-style unix file and switches
31868 ** the local lock file path
31869 */
31870 static int switchLockProxyPath(unixFile *pFile, const char *path) {
31871   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
31872   char *oldPath = pCtx->lockProxyPath;
31873   int rc = SQLITE_OK;
31874 
31875   if( pFile->eFileLock!=NO_LOCK ){
31876     return SQLITE_BUSY;
31877   }
31878 
31879   /* nothing to do if the path is NULL, :auto: or matches the existing path */
31880   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
31881     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
31882     return SQLITE_OK;
31883   }else{
31884     unixFile *lockProxy = pCtx->lockProxy;
31885     pCtx->lockProxy=NULL;
31886     pCtx->conchHeld = 0;
31887     if( lockProxy!=NULL ){
31888       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
31889       if( rc ) return rc;
31890       sqlite3_free(lockProxy);
31891     }
31892     sqlite3_free(oldPath);
31893     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
31894   }
31895 
31896   return rc;
31897 }
31898 
31899 /*
31900 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
31901 ** is a string buffer at least MAXPATHLEN+1 characters in size.
31902 **
31903 ** This routine find the filename associated with pFile and writes it
31904 ** int dbPath.
31905 */
31906 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
31907 #if defined(__APPLE__)
31908   if( pFile->pMethod == &afpIoMethods ){
31909     /* afp style keeps a reference to the db path in the filePath field
31910     ** of the struct */
31911     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
31912     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
31913   } else
31914 #endif
31915   if( pFile->pMethod == &dotlockIoMethods ){
31916     /* dot lock style uses the locking context to store the dot lock
31917     ** file path */
31918     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
31919     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
31920   }else{
31921     /* all other styles use the locking context to store the db file path */
31922     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
31923     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
31924   }
31925   return SQLITE_OK;
31926 }
31927 
31928 /*
31929 ** Takes an already filled in unix file and alters it so all file locking
31930 ** will be performed on the local proxy lock file.  The following fields
31931 ** are preserved in the locking context so that they can be restored and
31932 ** the unix structure properly cleaned up at close time:
31933 **  ->lockingContext
31934 **  ->pMethod
31935 */
31936 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
31937   proxyLockingContext *pCtx;
31938   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
31939   char *lockPath=NULL;
31940   int rc = SQLITE_OK;
31941 
31942   if( pFile->eFileLock!=NO_LOCK ){
31943     return SQLITE_BUSY;
31944   }
31945   proxyGetDbPathForUnixFile(pFile, dbPath);
31946   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
31947     lockPath=NULL;
31948   }else{
31949     lockPath=(char *)path;
31950   }
31951 
31952   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
31953            (lockPath ? lockPath : ":auto:"), getpid()));
31954 
31955   pCtx = sqlite3_malloc( sizeof(*pCtx) );
31956   if( pCtx==0 ){
31957     return SQLITE_NOMEM;
31958   }
31959   memset(pCtx, 0, sizeof(*pCtx));
31960 
31961   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
31962   if( rc==SQLITE_OK ){
31963     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
31964     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
31965       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
31966       ** (c) the file system is read-only, then enable no-locking access.
31967       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
31968       ** that openFlags will have only one of O_RDONLY or O_RDWR.
31969       */
31970       struct statfs fsInfo;
31971       struct stat conchInfo;
31972       int goLockless = 0;
31973 
31974       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
31975         int err = errno;
31976         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
31977           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
31978         }
31979       }
31980       if( goLockless ){
31981         pCtx->conchHeld = -1; /* read only FS/ lockless */
31982         rc = SQLITE_OK;
31983       }
31984     }
31985   }
31986   if( rc==SQLITE_OK && lockPath ){
31987     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
31988   }
31989 
31990   if( rc==SQLITE_OK ){
31991     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
31992     if( pCtx->dbPath==NULL ){
31993       rc = SQLITE_NOMEM;
31994     }
31995   }
31996   if( rc==SQLITE_OK ){
31997     /* all memory is allocated, proxys are created and assigned,
31998     ** switch the locking context and pMethod then return.
31999     */
32000     pCtx->oldLockingContext = pFile->lockingContext;
32001     pFile->lockingContext = pCtx;
32002     pCtx->pOldMethod = pFile->pMethod;
32003     pFile->pMethod = &proxyIoMethods;
32004   }else{
32005     if( pCtx->conchFile ){
32006       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
32007       sqlite3_free(pCtx->conchFile);
32008     }
32009     sqlite3DbFree(0, pCtx->lockProxyPath);
32010     sqlite3_free(pCtx->conchFilePath);
32011     sqlite3_free(pCtx);
32012   }
32013   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
32014            (rc==SQLITE_OK ? "ok" : "failed")));
32015   return rc;
32016 }
32017 
32018 
32019 /*
32020 ** This routine handles sqlite3_file_control() calls that are specific
32021 ** to proxy locking.
32022 */
32023 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
32024   switch( op ){
32025     case SQLITE_GET_LOCKPROXYFILE: {
32026       unixFile *pFile = (unixFile*)id;
32027       if( pFile->pMethod == &proxyIoMethods ){
32028         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
32029         proxyTakeConch(pFile);
32030         if( pCtx->lockProxyPath ){
32031           *(const char **)pArg = pCtx->lockProxyPath;
32032         }else{
32033           *(const char **)pArg = ":auto: (not held)";
32034         }
32035       } else {
32036         *(const char **)pArg = NULL;
32037       }
32038       return SQLITE_OK;
32039     }
32040     case SQLITE_SET_LOCKPROXYFILE: {
32041       unixFile *pFile = (unixFile*)id;
32042       int rc = SQLITE_OK;
32043       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
32044       if( pArg==NULL || (const char *)pArg==0 ){
32045         if( isProxyStyle ){
32046           /* turn off proxy locking - not supported */
32047           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
32048         }else{
32049           /* turn off proxy locking - already off - NOOP */
32050           rc = SQLITE_OK;
32051         }
32052       }else{
32053         const char *proxyPath = (const char *)pArg;
32054         if( isProxyStyle ){
32055           proxyLockingContext *pCtx =
32056             (proxyLockingContext*)pFile->lockingContext;
32057           if( !strcmp(pArg, ":auto:")
32058            || (pCtx->lockProxyPath &&
32059                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
32060           ){
32061             rc = SQLITE_OK;
32062           }else{
32063             rc = switchLockProxyPath(pFile, proxyPath);
32064           }
32065         }else{
32066           /* turn on proxy file locking */
32067           rc = proxyTransformUnixFile(pFile, proxyPath);
32068         }
32069       }
32070       return rc;
32071     }
32072     default: {
32073       assert( 0 );  /* The call assures that only valid opcodes are sent */
32074     }
32075   }
32076   /*NOTREACHED*/
32077   return SQLITE_ERROR;
32078 }
32079 
32080 /*
32081 ** Within this division (the proxying locking implementation) the procedures
32082 ** above this point are all utilities.  The lock-related methods of the
32083 ** proxy-locking sqlite3_io_method object follow.
32084 */
32085 
32086 
32087 /*
32088 ** This routine checks if there is a RESERVED lock held on the specified
32089 ** file by this or any other process. If such a lock is held, set *pResOut
32090 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
32091 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
32092 */
32093 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
32094   unixFile *pFile = (unixFile*)id;
32095   int rc = proxyTakeConch(pFile);
32096   if( rc==SQLITE_OK ){
32097     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32098     if( pCtx->conchHeld>0 ){
32099       unixFile *proxy = pCtx->lockProxy;
32100       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
32101     }else{ /* conchHeld < 0 is lockless */
32102       pResOut=0;
32103     }
32104   }
32105   return rc;
32106 }
32107 
32108 /*
32109 ** Lock the file with the lock specified by parameter eFileLock - one
32110 ** of the following:
32111 **
32112 **     (1) SHARED_LOCK
32113 **     (2) RESERVED_LOCK
32114 **     (3) PENDING_LOCK
32115 **     (4) EXCLUSIVE_LOCK
32116 **
32117 ** Sometimes when requesting one lock state, additional lock states
32118 ** are inserted in between.  The locking might fail on one of the later
32119 ** transitions leaving the lock state different from what it started but
32120 ** still short of its goal.  The following chart shows the allowed
32121 ** transitions and the inserted intermediate states:
32122 **
32123 **    UNLOCKED -> SHARED
32124 **    SHARED -> RESERVED
32125 **    SHARED -> (PENDING) -> EXCLUSIVE
32126 **    RESERVED -> (PENDING) -> EXCLUSIVE
32127 **    PENDING -> EXCLUSIVE
32128 **
32129 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
32130 ** routine to lower a locking level.
32131 */
32132 static int proxyLock(sqlite3_file *id, int eFileLock) {
32133   unixFile *pFile = (unixFile*)id;
32134   int rc = proxyTakeConch(pFile);
32135   if( rc==SQLITE_OK ){
32136     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32137     if( pCtx->conchHeld>0 ){
32138       unixFile *proxy = pCtx->lockProxy;
32139       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
32140       pFile->eFileLock = proxy->eFileLock;
32141     }else{
32142       /* conchHeld < 0 is lockless */
32143     }
32144   }
32145   return rc;
32146 }
32147 
32148 
32149 /*
32150 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
32151 ** must be either NO_LOCK or SHARED_LOCK.
32152 **
32153 ** If the locking level of the file descriptor is already at or below
32154 ** the requested locking level, this routine is a no-op.
32155 */
32156 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
32157   unixFile *pFile = (unixFile*)id;
32158   int rc = proxyTakeConch(pFile);
32159   if( rc==SQLITE_OK ){
32160     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32161     if( pCtx->conchHeld>0 ){
32162       unixFile *proxy = pCtx->lockProxy;
32163       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
32164       pFile->eFileLock = proxy->eFileLock;
32165     }else{
32166       /* conchHeld < 0 is lockless */
32167     }
32168   }
32169   return rc;
32170 }
32171 
32172 /*
32173 ** Close a file that uses proxy locks.
32174 */
32175 static int proxyClose(sqlite3_file *id) {
32176   if( id ){
32177     unixFile *pFile = (unixFile*)id;
32178     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32179     unixFile *lockProxy = pCtx->lockProxy;
32180     unixFile *conchFile = pCtx->conchFile;
32181     int rc = SQLITE_OK;
32182 
32183     if( lockProxy ){
32184       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
32185       if( rc ) return rc;
32186       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
32187       if( rc ) return rc;
32188       sqlite3_free(lockProxy);
32189       pCtx->lockProxy = 0;
32190     }
32191     if( conchFile ){
32192       if( pCtx->conchHeld ){
32193         rc = proxyReleaseConch(pFile);
32194         if( rc ) return rc;
32195       }
32196       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
32197       if( rc ) return rc;
32198       sqlite3_free(conchFile);
32199     }
32200     sqlite3DbFree(0, pCtx->lockProxyPath);
32201     sqlite3_free(pCtx->conchFilePath);
32202     sqlite3DbFree(0, pCtx->dbPath);
32203     /* restore the original locking context and pMethod then close it */
32204     pFile->lockingContext = pCtx->oldLockingContext;
32205     pFile->pMethod = pCtx->pOldMethod;
32206     sqlite3_free(pCtx);
32207     return pFile->pMethod->xClose(id);
32208   }
32209   return SQLITE_OK;
32210 }
32211 
32212 
32213 
32214 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
32215 /*
32216 ** The proxy locking style is intended for use with AFP filesystems.
32217 ** And since AFP is only supported on MacOSX, the proxy locking is also
32218 ** restricted to MacOSX.
32219 **
32220 **
32221 ******************* End of the proxy lock implementation **********************
32222 ******************************************************************************/
32223 
32224 /*
32225 ** Initialize the operating system interface.
32226 **
32227 ** This routine registers all VFS implementations for unix-like operating
32228 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
32229 ** should be the only routines in this file that are visible from other
32230 ** files.
32231 **
32232 ** This routine is called once during SQLite initialization and by a
32233 ** single thread.  The memory allocation and mutex subsystems have not
32234 ** necessarily been initialized when this routine is called, and so they
32235 ** should not be used.
32236 */
32237 SQLITE_API int sqlite3_os_init(void){
32238   /*
32239   ** The following macro defines an initializer for an sqlite3_vfs object.
32240   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
32241   ** to the "finder" function.  (pAppData is a pointer to a pointer because
32242   ** silly C90 rules prohibit a void* from being cast to a function pointer
32243   ** and so we have to go through the intermediate pointer to avoid problems
32244   ** when compiling with -pedantic-errors on GCC.)
32245   **
32246   ** The FINDER parameter to this macro is the name of the pointer to the
32247   ** finder-function.  The finder-function returns a pointer to the
32248   ** sqlite_io_methods object that implements the desired locking
32249   ** behaviors.  See the division above that contains the IOMETHODS
32250   ** macro for addition information on finder-functions.
32251   **
32252   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
32253   ** object.  But the "autolockIoFinder" available on MacOSX does a little
32254   ** more than that; it looks at the filesystem type that hosts the
32255   ** database file and tries to choose an locking method appropriate for
32256   ** that filesystem time.
32257   */
32258   #define UNIXVFS(VFSNAME, FINDER) {                        \
32259     3,                    /* iVersion */                    \
32260     sizeof(unixFile),     /* szOsFile */                    \
32261     MAX_PATHNAME,         /* mxPathname */                  \
32262     0,                    /* pNext */                       \
32263     VFSNAME,              /* zName */                       \
32264     (void*)&FINDER,       /* pAppData */                    \
32265     unixOpen,             /* xOpen */                       \
32266     unixDelete,           /* xDelete */                     \
32267     unixAccess,           /* xAccess */                     \
32268     unixFullPathname,     /* xFullPathname */               \
32269     unixDlOpen,           /* xDlOpen */                     \
32270     unixDlError,          /* xDlError */                    \
32271     unixDlSym,            /* xDlSym */                      \
32272     unixDlClose,          /* xDlClose */                    \
32273     unixRandomness,       /* xRandomness */                 \
32274     unixSleep,            /* xSleep */                      \
32275     unixCurrentTime,      /* xCurrentTime */                \
32276     unixGetLastError,     /* xGetLastError */               \
32277     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
32278     unixSetSystemCall,    /* xSetSystemCall */              \
32279     unixGetSystemCall,    /* xGetSystemCall */              \
32280     unixNextSystemCall,   /* xNextSystemCall */             \
32281   }
32282 
32283   /*
32284   ** All default VFSes for unix are contained in the following array.
32285   **
32286   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
32287   ** by the SQLite core when the VFS is registered.  So the following
32288   ** array cannot be const.
32289   */
32290   static sqlite3_vfs aVfs[] = {
32291 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
32292     UNIXVFS("unix",          autolockIoFinder ),
32293 #else
32294     UNIXVFS("unix",          posixIoFinder ),
32295 #endif
32296     UNIXVFS("unix-none",     nolockIoFinder ),
32297     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
32298     UNIXVFS("unix-excl",     posixIoFinder ),
32299 #if OS_VXWORKS
32300     UNIXVFS("unix-namedsem", semIoFinder ),
32301 #endif
32302 #if SQLITE_ENABLE_LOCKING_STYLE
32303     UNIXVFS("unix-posix",    posixIoFinder ),
32304 #if !OS_VXWORKS
32305     UNIXVFS("unix-flock",    flockIoFinder ),
32306 #endif
32307 #endif
32308 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
32309     UNIXVFS("unix-afp",      afpIoFinder ),
32310     UNIXVFS("unix-nfs",      nfsIoFinder ),
32311     UNIXVFS("unix-proxy",    proxyIoFinder ),
32312 #endif
32313   };
32314   unsigned int i;          /* Loop counter */
32315 
32316   /* Double-check that the aSyscall[] array has been constructed
32317   ** correctly.  See ticket [bb3a86e890c8e96ab] */
32318   assert( ArraySize(aSyscall)==25 );
32319 
32320   /* Register all VFSes defined in the aVfs[] array */
32321   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
32322     sqlite3_vfs_register(&aVfs[i], i==0);
32323   }
32324   return SQLITE_OK;
32325 }
32326 
32327 /*
32328 ** Shutdown the operating system interface.
32329 **
32330 ** Some operating systems might need to do some cleanup in this routine,
32331 ** to release dynamically allocated objects.  But not on unix.
32332 ** This routine is a no-op for unix.
32333 */
32334 SQLITE_API int sqlite3_os_end(void){
32335   return SQLITE_OK;
32336 }
32337 
32338 #endif /* SQLITE_OS_UNIX */
32339 
32340 /************** End of os_unix.c *********************************************/
32341 /************** Begin file os_win.c ******************************************/
32342 /*
32343 ** 2004 May 22
32344 **
32345 ** The author disclaims copyright to this source code.  In place of
32346 ** a legal notice, here is a blessing:
32347 **
32348 **    May you do good and not evil.
32349 **    May you find forgiveness for yourself and forgive others.
32350 **    May you share freely, never taking more than you give.
32351 **
32352 ******************************************************************************
32353 **
32354 ** This file contains code that is specific to Windows.
32355 */
32356 #if SQLITE_OS_WIN               /* This file is used for Windows only */
32357 
32358 /*
32359 ** Include code that is common to all os_*.c files
32360 */
32361 /************** Include os_common.h in the middle of os_win.c ****************/
32362 /************** Begin file os_common.h ***************************************/
32363 /*
32364 ** 2004 May 22
32365 **
32366 ** The author disclaims copyright to this source code.  In place of
32367 ** a legal notice, here is a blessing:
32368 **
32369 **    May you do good and not evil.
32370 **    May you find forgiveness for yourself and forgive others.
32371 **    May you share freely, never taking more than you give.
32372 **
32373 ******************************************************************************
32374 **
32375 ** This file contains macros and a little bit of code that is common to
32376 ** all of the platform-specific files (os_*.c) and is #included into those
32377 ** files.
32378 **
32379 ** This file should be #included by the os_*.c files only.  It is not a
32380 ** general purpose header file.
32381 */
32382 #ifndef _OS_COMMON_H_
32383 #define _OS_COMMON_H_
32384 
32385 /*
32386 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
32387 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
32388 ** switch.  The following code should catch this problem at compile-time.
32389 */
32390 #ifdef MEMORY_DEBUG
32391 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
32392 #endif
32393 
32394 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
32395 # ifndef SQLITE_DEBUG_OS_TRACE
32396 #   define SQLITE_DEBUG_OS_TRACE 0
32397 # endif
32398   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
32399 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
32400 #else
32401 # define OSTRACE(X)
32402 #endif
32403 
32404 /*
32405 ** Macros for performance tracing.  Normally turned off.  Only works
32406 ** on i486 hardware.
32407 */
32408 #ifdef SQLITE_PERFORMANCE_TRACE
32409 
32410 /*
32411 ** hwtime.h contains inline assembler code for implementing
32412 ** high-performance timing routines.
32413 */
32414 /************** Include hwtime.h in the middle of os_common.h ****************/
32415 /************** Begin file hwtime.h ******************************************/
32416 /*
32417 ** 2008 May 27
32418 **
32419 ** The author disclaims copyright to this source code.  In place of
32420 ** a legal notice, here is a blessing:
32421 **
32422 **    May you do good and not evil.
32423 **    May you find forgiveness for yourself and forgive others.
32424 **    May you share freely, never taking more than you give.
32425 **
32426 ******************************************************************************
32427 **
32428 ** This file contains inline asm code for retrieving "high-performance"
32429 ** counters for x86 class CPUs.
32430 */
32431 #ifndef _HWTIME_H_
32432 #define _HWTIME_H_
32433 
32434 /*
32435 ** The following routine only works on pentium-class (or newer) processors.
32436 ** It uses the RDTSC opcode to read the cycle count value out of the
32437 ** processor and returns that value.  This can be used for high-res
32438 ** profiling.
32439 */
32440 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
32441       (defined(i386) || defined(__i386__) || defined(_M_IX86))
32442 
32443   #if defined(__GNUC__)
32444 
32445   __inline__ sqlite_uint64 sqlite3Hwtime(void){
32446      unsigned int lo, hi;
32447      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
32448      return (sqlite_uint64)hi << 32 | lo;
32449   }
32450 
32451   #elif defined(_MSC_VER)
32452 
32453   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
32454      __asm {
32455         rdtsc
32456         ret       ; return value at EDX:EAX
32457      }
32458   }
32459 
32460   #endif
32461 
32462 #elif (defined(__GNUC__) && defined(__x86_64__))
32463 
32464   __inline__ sqlite_uint64 sqlite3Hwtime(void){
32465       unsigned long val;
32466       __asm__ __volatile__ ("rdtsc" : "=A" (val));
32467       return val;
32468   }
32469 
32470 #elif (defined(__GNUC__) && defined(__ppc__))
32471 
32472   __inline__ sqlite_uint64 sqlite3Hwtime(void){
32473       unsigned long long retval;
32474       unsigned long junk;
32475       __asm__ __volatile__ ("\n\
32476           1:      mftbu   %1\n\
32477                   mftb    %L0\n\
32478                   mftbu   %0\n\
32479                   cmpw    %0,%1\n\
32480                   bne     1b"
32481                   : "=r" (retval), "=r" (junk));
32482       return retval;
32483   }
32484 
32485 #else
32486 
32487   #error Need implementation of sqlite3Hwtime() for your platform.
32488 
32489   /*
32490   ** To compile without implementing sqlite3Hwtime() for your platform,
32491   ** you can remove the above #error and use the following
32492   ** stub function.  You will lose timing support for many
32493   ** of the debugging and testing utilities, but it should at
32494   ** least compile and run.
32495   */
32496 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
32497 
32498 #endif
32499 
32500 #endif /* !defined(_HWTIME_H_) */
32501 
32502 /************** End of hwtime.h **********************************************/
32503 /************** Continuing where we left off in os_common.h ******************/
32504 
32505 static sqlite_uint64 g_start;
32506 static sqlite_uint64 g_elapsed;
32507 #define TIMER_START       g_start=sqlite3Hwtime()
32508 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
32509 #define TIMER_ELAPSED     g_elapsed
32510 #else
32511 #define TIMER_START
32512 #define TIMER_END
32513 #define TIMER_ELAPSED     ((sqlite_uint64)0)
32514 #endif
32515 
32516 /*
32517 ** If we compile with the SQLITE_TEST macro set, then the following block
32518 ** of code will give us the ability to simulate a disk I/O error.  This
32519 ** is used for testing the I/O recovery logic.
32520 */
32521 #ifdef SQLITE_TEST
32522 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
32523 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
32524 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
32525 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
32526 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
32527 SQLITE_API int sqlite3_diskfull_pending = 0;
32528 SQLITE_API int sqlite3_diskfull = 0;
32529 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
32530 #define SimulateIOError(CODE)  \
32531   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
32532        || sqlite3_io_error_pending-- == 1 )  \
32533               { local_ioerr(); CODE; }
32534 static void local_ioerr(){
32535   IOTRACE(("IOERR\n"));
32536   sqlite3_io_error_hit++;
32537   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
32538 }
32539 #define SimulateDiskfullError(CODE) \
32540    if( sqlite3_diskfull_pending ){ \
32541      if( sqlite3_diskfull_pending == 1 ){ \
32542        local_ioerr(); \
32543        sqlite3_diskfull = 1; \
32544        sqlite3_io_error_hit = 1; \
32545        CODE; \
32546      }else{ \
32547        sqlite3_diskfull_pending--; \
32548      } \
32549    }
32550 #else
32551 #define SimulateIOErrorBenign(X)
32552 #define SimulateIOError(A)
32553 #define SimulateDiskfullError(A)
32554 #endif
32555 
32556 /*
32557 ** When testing, keep a count of the number of open files.
32558 */
32559 #ifdef SQLITE_TEST
32560 SQLITE_API int sqlite3_open_file_count = 0;
32561 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
32562 #else
32563 #define OpenCounter(X)
32564 #endif
32565 
32566 #endif /* !defined(_OS_COMMON_H_) */
32567 
32568 /************** End of os_common.h *******************************************/
32569 /************** Continuing where we left off in os_win.c *********************/
32570 
32571 /*
32572 ** Include the header file for the Windows VFS.
32573 */
32574 
32575 /*
32576 ** Compiling and using WAL mode requires several APIs that are only
32577 ** available in Windows platforms based on the NT kernel.
32578 */
32579 #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
32580 #  error "WAL mode requires support from the Windows NT kernel, compile\
32581  with SQLITE_OMIT_WAL."
32582 #endif
32583 
32584 /*
32585 ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
32586 ** based on the sub-platform)?
32587 */
32588 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
32589 #  define SQLITE_WIN32_HAS_ANSI
32590 #endif
32591 
32592 /*
32593 ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
32594 ** based on the sub-platform)?
32595 */
32596 #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
32597     !defined(SQLITE_WIN32_NO_WIDE)
32598 #  define SQLITE_WIN32_HAS_WIDE
32599 #endif
32600 
32601 /*
32602 ** Make sure at least one set of Win32 APIs is available.
32603 */
32604 #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
32605 #  error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
32606  must be defined."
32607 #endif
32608 
32609 /*
32610 ** Define the required Windows SDK version constants if they are not
32611 ** already available.
32612 */
32613 #ifndef NTDDI_WIN8
32614 #  define NTDDI_WIN8                        0x06020000
32615 #endif
32616 
32617 #ifndef NTDDI_WINBLUE
32618 #  define NTDDI_WINBLUE                     0x06030000
32619 #endif
32620 
32621 /*
32622 ** Check to see if the GetVersionEx[AW] functions are deprecated on the
32623 ** target system.  GetVersionEx was first deprecated in Win8.1.
32624 */
32625 #ifndef SQLITE_WIN32_GETVERSIONEX
32626 #  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
32627 #    define SQLITE_WIN32_GETVERSIONEX   0   /* GetVersionEx() is deprecated */
32628 #  else
32629 #    define SQLITE_WIN32_GETVERSIONEX   1   /* GetVersionEx() is current */
32630 #  endif
32631 #endif
32632 
32633 /*
32634 ** This constant should already be defined (in the "WinDef.h" SDK file).
32635 */
32636 #ifndef MAX_PATH
32637 #  define MAX_PATH                      (260)
32638 #endif
32639 
32640 /*
32641 ** Maximum pathname length (in chars) for Win32.  This should normally be
32642 ** MAX_PATH.
32643 */
32644 #ifndef SQLITE_WIN32_MAX_PATH_CHARS
32645 #  define SQLITE_WIN32_MAX_PATH_CHARS   (MAX_PATH)
32646 #endif
32647 
32648 /*
32649 ** This constant should already be defined (in the "WinNT.h" SDK file).
32650 */
32651 #ifndef UNICODE_STRING_MAX_CHARS
32652 #  define UNICODE_STRING_MAX_CHARS      (32767)
32653 #endif
32654 
32655 /*
32656 ** Maximum pathname length (in chars) for WinNT.  This should normally be
32657 ** UNICODE_STRING_MAX_CHARS.
32658 */
32659 #ifndef SQLITE_WINNT_MAX_PATH_CHARS
32660 #  define SQLITE_WINNT_MAX_PATH_CHARS   (UNICODE_STRING_MAX_CHARS)
32661 #endif
32662 
32663 /*
32664 ** Maximum pathname length (in bytes) for Win32.  The MAX_PATH macro is in
32665 ** characters, so we allocate 4 bytes per character assuming worst-case of
32666 ** 4-bytes-per-character for UTF8.
32667 */
32668 #ifndef SQLITE_WIN32_MAX_PATH_BYTES
32669 #  define SQLITE_WIN32_MAX_PATH_BYTES   (SQLITE_WIN32_MAX_PATH_CHARS*4)
32670 #endif
32671 
32672 /*
32673 ** Maximum pathname length (in bytes) for WinNT.  This should normally be
32674 ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
32675 */
32676 #ifndef SQLITE_WINNT_MAX_PATH_BYTES
32677 #  define SQLITE_WINNT_MAX_PATH_BYTES   \
32678                             (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
32679 #endif
32680 
32681 /*
32682 ** Maximum error message length (in chars) for WinRT.
32683 */
32684 #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
32685 #  define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
32686 #endif
32687 
32688 /*
32689 ** Returns non-zero if the character should be treated as a directory
32690 ** separator.
32691 */
32692 #ifndef winIsDirSep
32693 #  define winIsDirSep(a)                (((a) == '/') || ((a) == '\\'))
32694 #endif
32695 
32696 /*
32697 ** This macro is used when a local variable is set to a value that is
32698 ** [sometimes] not used by the code (e.g. via conditional compilation).
32699 */
32700 #ifndef UNUSED_VARIABLE_VALUE
32701 #  define UNUSED_VARIABLE_VALUE(x)      (void)(x)
32702 #endif
32703 
32704 /*
32705 ** Returns the character that should be used as the directory separator.
32706 */
32707 #ifndef winGetDirSep
32708 #  define winGetDirSep()                '\\'
32709 #endif
32710 
32711 /*
32712 ** Do we need to manually define the Win32 file mapping APIs for use with WAL
32713 ** mode (e.g. these APIs are available in the Windows CE SDK; however, they
32714 ** are not present in the header file)?
32715 */
32716 #if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
32717 /*
32718 ** Two of the file mapping APIs are different under WinRT.  Figure out which
32719 ** set we need.
32720 */
32721 #if SQLITE_OS_WINRT
32722 WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
32723         LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
32724 
32725 WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
32726 #else
32727 #if defined(SQLITE_WIN32_HAS_ANSI)
32728 WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
32729         DWORD, DWORD, DWORD, LPCSTR);
32730 #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
32731 
32732 #if defined(SQLITE_WIN32_HAS_WIDE)
32733 WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
32734         DWORD, DWORD, DWORD, LPCWSTR);
32735 #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
32736 
32737 WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
32738 #endif /* SQLITE_OS_WINRT */
32739 
32740 /*
32741 ** This file mapping API is common to both Win32 and WinRT.
32742 */
32743 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
32744 #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
32745 
32746 /*
32747 ** Some Microsoft compilers lack this definition.
32748 */
32749 #ifndef INVALID_FILE_ATTRIBUTES
32750 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
32751 #endif
32752 
32753 #ifndef FILE_FLAG_MASK
32754 # define FILE_FLAG_MASK          (0xFF3C0000)
32755 #endif
32756 
32757 #ifndef FILE_ATTRIBUTE_MASK
32758 # define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
32759 #endif
32760 
32761 #ifndef SQLITE_OMIT_WAL
32762 /* Forward references to structures used for WAL */
32763 typedef struct winShm winShm;           /* A connection to shared-memory */
32764 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
32765 #endif
32766 
32767 /*
32768 ** WinCE lacks native support for file locking so we have to fake it
32769 ** with some code of our own.
32770 */
32771 #if SQLITE_OS_WINCE
32772 typedef struct winceLock {
32773   int nReaders;       /* Number of reader locks obtained */
32774   BOOL bPending;      /* Indicates a pending lock has been obtained */
32775   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
32776   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
32777 } winceLock;
32778 #endif
32779 
32780 /*
32781 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
32782 ** portability layer.
32783 */
32784 typedef struct winFile winFile;
32785 struct winFile {
32786   const sqlite3_io_methods *pMethod; /*** Must be first ***/
32787   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
32788   HANDLE h;               /* Handle for accessing the file */
32789   u8 locktype;            /* Type of lock currently held on this file */
32790   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
32791   u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
32792   DWORD lastErrno;        /* The Windows errno from the last I/O error */
32793 #ifndef SQLITE_OMIT_WAL
32794   winShm *pShm;           /* Instance of shared memory on this file */
32795 #endif
32796   const char *zPath;      /* Full pathname of this file */
32797   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
32798 #if SQLITE_OS_WINCE
32799   LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
32800   HANDLE hMutex;          /* Mutex used to control access to shared lock */
32801   HANDLE hShared;         /* Shared memory segment used for locking */
32802   winceLock local;        /* Locks obtained by this instance of winFile */
32803   winceLock *shared;      /* Global shared lock memory for the file  */
32804 #endif
32805 #if SQLITE_MAX_MMAP_SIZE>0
32806   int nFetchOut;                /* Number of outstanding xFetch references */
32807   HANDLE hMap;                  /* Handle for accessing memory mapping */
32808   void *pMapRegion;             /* Area memory mapped */
32809   sqlite3_int64 mmapSize;       /* Usable size of mapped region */
32810   sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
32811   sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */
32812 #endif
32813 };
32814 
32815 /*
32816 ** Allowed values for winFile.ctrlFlags
32817 */
32818 #define WINFILE_RDONLY          0x02   /* Connection is read only */
32819 #define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
32820 #define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
32821 
32822 /*
32823  * The size of the buffer used by sqlite3_win32_write_debug().
32824  */
32825 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
32826 #  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
32827 #endif
32828 
32829 /*
32830  * The value used with sqlite3_win32_set_directory() to specify that
32831  * the data directory should be changed.
32832  */
32833 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
32834 #  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
32835 #endif
32836 
32837 /*
32838  * The value used with sqlite3_win32_set_directory() to specify that
32839  * the temporary directory should be changed.
32840  */
32841 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
32842 #  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
32843 #endif
32844 
32845 /*
32846  * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
32847  * various Win32 API heap functions instead of our own.
32848  */
32849 #ifdef SQLITE_WIN32_MALLOC
32850 
32851 /*
32852  * If this is non-zero, an isolated heap will be created by the native Win32
32853  * allocator subsystem; otherwise, the default process heap will be used.  This
32854  * setting has no effect when compiling for WinRT.  By default, this is enabled
32855  * and an isolated heap will be created to store all allocated data.
32856  *
32857  ******************************************************************************
32858  * WARNING: It is important to note that when this setting is non-zero and the
32859  *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
32860  *          function), all data that was allocated using the isolated heap will
32861  *          be freed immediately and any attempt to access any of that freed
32862  *          data will almost certainly result in an immediate access violation.
32863  ******************************************************************************
32864  */
32865 #ifndef SQLITE_WIN32_HEAP_CREATE
32866 #  define SQLITE_WIN32_HEAP_CREATE    (TRUE)
32867 #endif
32868 
32869 /*
32870  * The initial size of the Win32-specific heap.  This value may be zero.
32871  */
32872 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
32873 #  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
32874                                        (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
32875 #endif
32876 
32877 /*
32878  * The maximum size of the Win32-specific heap.  This value may be zero.
32879  */
32880 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
32881 #  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
32882 #endif
32883 
32884 /*
32885  * The extra flags to use in calls to the Win32 heap APIs.  This value may be
32886  * zero for the default behavior.
32887  */
32888 #ifndef SQLITE_WIN32_HEAP_FLAGS
32889 #  define SQLITE_WIN32_HEAP_FLAGS     (0)
32890 #endif
32891 
32892 
32893 /*
32894 ** The winMemData structure stores information required by the Win32-specific
32895 ** sqlite3_mem_methods implementation.
32896 */
32897 typedef struct winMemData winMemData;
32898 struct winMemData {
32899 #ifndef NDEBUG
32900   u32 magic1;   /* Magic number to detect structure corruption. */
32901 #endif
32902   HANDLE hHeap; /* The handle to our heap. */
32903   BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
32904 #ifndef NDEBUG
32905   u32 magic2;   /* Magic number to detect structure corruption. */
32906 #endif
32907 };
32908 
32909 #ifndef NDEBUG
32910 #define WINMEM_MAGIC1     0x42b2830b
32911 #define WINMEM_MAGIC2     0xbd4d7cf4
32912 #endif
32913 
32914 static struct winMemData win_mem_data = {
32915 #ifndef NDEBUG
32916   WINMEM_MAGIC1,
32917 #endif
32918   NULL, FALSE
32919 #ifndef NDEBUG
32920   ,WINMEM_MAGIC2
32921 #endif
32922 };
32923 
32924 #ifndef NDEBUG
32925 #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
32926 #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
32927 #define winMemAssertMagic()  winMemAssertMagic1(); winMemAssertMagic2();
32928 #else
32929 #define winMemAssertMagic()
32930 #endif
32931 
32932 #define winMemGetDataPtr()  &win_mem_data
32933 #define winMemGetHeap()     win_mem_data.hHeap
32934 #define winMemGetOwned()    win_mem_data.bOwned
32935 
32936 static void *winMemMalloc(int nBytes);
32937 static void winMemFree(void *pPrior);
32938 static void *winMemRealloc(void *pPrior, int nBytes);
32939 static int winMemSize(void *p);
32940 static int winMemRoundup(int n);
32941 static int winMemInit(void *pAppData);
32942 static void winMemShutdown(void *pAppData);
32943 
32944 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
32945 #endif /* SQLITE_WIN32_MALLOC */
32946 
32947 /*
32948 ** The following variable is (normally) set once and never changes
32949 ** thereafter.  It records whether the operating system is Win9x
32950 ** or WinNT.
32951 **
32952 ** 0:   Operating system unknown.
32953 ** 1:   Operating system is Win9x.
32954 ** 2:   Operating system is WinNT.
32955 **
32956 ** In order to facilitate testing on a WinNT system, the test fixture
32957 ** can manually set this value to 1 to emulate Win98 behavior.
32958 */
32959 #ifdef SQLITE_TEST
32960 SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
32961 #else
32962 static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
32963 #endif
32964 
32965 #ifndef SYSCALL
32966 #  define SYSCALL sqlite3_syscall_ptr
32967 #endif
32968 
32969 /*
32970 ** This function is not available on Windows CE or WinRT.
32971  */
32972 
32973 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
32974 #  define osAreFileApisANSI()       1
32975 #endif
32976 
32977 /*
32978 ** Many system calls are accessed through pointer-to-functions so that
32979 ** they may be overridden at runtime to facilitate fault injection during
32980 ** testing and sandboxing.  The following array holds the names and pointers
32981 ** to all overrideable system calls.
32982 */
32983 static struct win_syscall {
32984   const char *zName;            /* Name of the system call */
32985   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
32986   sqlite3_syscall_ptr pDefault; /* Default value */
32987 } aSyscall[] = {
32988 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
32989   { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
32990 #else
32991   { "AreFileApisANSI",         (SYSCALL)0,                       0 },
32992 #endif
32993 
32994 #ifndef osAreFileApisANSI
32995 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
32996 #endif
32997 
32998 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
32999   { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
33000 #else
33001   { "CharLowerW",              (SYSCALL)0,                       0 },
33002 #endif
33003 
33004 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
33005 
33006 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
33007   { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
33008 #else
33009   { "CharUpperW",              (SYSCALL)0,                       0 },
33010 #endif
33011 
33012 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
33013 
33014   { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
33015 
33016 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
33017 
33018 #if defined(SQLITE_WIN32_HAS_ANSI)
33019   { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
33020 #else
33021   { "CreateFileA",             (SYSCALL)0,                       0 },
33022 #endif
33023 
33024 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
33025         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
33026 
33027 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33028   { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
33029 #else
33030   { "CreateFileW",             (SYSCALL)0,                       0 },
33031 #endif
33032 
33033 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
33034         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
33035 
33036 #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
33037         !defined(SQLITE_OMIT_WAL))
33038   { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
33039 #else
33040   { "CreateFileMappingA",      (SYSCALL)0,                       0 },
33041 #endif
33042 
33043 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
33044         DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
33045 
33046 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
33047         !defined(SQLITE_OMIT_WAL))
33048   { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
33049 #else
33050   { "CreateFileMappingW",      (SYSCALL)0,                       0 },
33051 #endif
33052 
33053 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
33054         DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
33055 
33056 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33057   { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
33058 #else
33059   { "CreateMutexW",            (SYSCALL)0,                       0 },
33060 #endif
33061 
33062 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
33063         LPCWSTR))aSyscall[8].pCurrent)
33064 
33065 #if defined(SQLITE_WIN32_HAS_ANSI)
33066   { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
33067 #else
33068   { "DeleteFileA",             (SYSCALL)0,                       0 },
33069 #endif
33070 
33071 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
33072 
33073 #if defined(SQLITE_WIN32_HAS_WIDE)
33074   { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
33075 #else
33076   { "DeleteFileW",             (SYSCALL)0,                       0 },
33077 #endif
33078 
33079 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
33080 
33081 #if SQLITE_OS_WINCE
33082   { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
33083 #else
33084   { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
33085 #endif
33086 
33087 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
33088         LPFILETIME))aSyscall[11].pCurrent)
33089 
33090 #if SQLITE_OS_WINCE
33091   { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
33092 #else
33093   { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
33094 #endif
33095 
33096 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
33097         LPSYSTEMTIME))aSyscall[12].pCurrent)
33098 
33099   { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
33100 
33101 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
33102 
33103 #if defined(SQLITE_WIN32_HAS_ANSI)
33104   { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
33105 #else
33106   { "FormatMessageA",          (SYSCALL)0,                       0 },
33107 #endif
33108 
33109 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
33110         DWORD,va_list*))aSyscall[14].pCurrent)
33111 
33112 #if defined(SQLITE_WIN32_HAS_WIDE)
33113   { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
33114 #else
33115   { "FormatMessageW",          (SYSCALL)0,                       0 },
33116 #endif
33117 
33118 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
33119         DWORD,va_list*))aSyscall[15].pCurrent)
33120 
33121 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
33122   { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
33123 #else
33124   { "FreeLibrary",             (SYSCALL)0,                       0 },
33125 #endif
33126 
33127 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
33128 
33129   { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
33130 
33131 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
33132 
33133 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
33134   { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
33135 #else
33136   { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
33137 #endif
33138 
33139 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
33140         LPDWORD))aSyscall[18].pCurrent)
33141 
33142 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33143   { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
33144 #else
33145   { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
33146 #endif
33147 
33148 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
33149         LPDWORD))aSyscall[19].pCurrent)
33150 
33151 #if defined(SQLITE_WIN32_HAS_ANSI)
33152   { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
33153 #else
33154   { "GetFileAttributesA",      (SYSCALL)0,                       0 },
33155 #endif
33156 
33157 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
33158 
33159 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33160   { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
33161 #else
33162   { "GetFileAttributesW",      (SYSCALL)0,                       0 },
33163 #endif
33164 
33165 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
33166 
33167 #if defined(SQLITE_WIN32_HAS_WIDE)
33168   { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
33169 #else
33170   { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
33171 #endif
33172 
33173 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
33174         LPVOID))aSyscall[22].pCurrent)
33175 
33176 #if !SQLITE_OS_WINRT
33177   { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
33178 #else
33179   { "GetFileSize",             (SYSCALL)0,                       0 },
33180 #endif
33181 
33182 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
33183 
33184 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
33185   { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
33186 #else
33187   { "GetFullPathNameA",        (SYSCALL)0,                       0 },
33188 #endif
33189 
33190 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
33191         LPSTR*))aSyscall[24].pCurrent)
33192 
33193 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33194   { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
33195 #else
33196   { "GetFullPathNameW",        (SYSCALL)0,                       0 },
33197 #endif
33198 
33199 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
33200         LPWSTR*))aSyscall[25].pCurrent)
33201 
33202   { "GetLastError",            (SYSCALL)GetLastError,            0 },
33203 
33204 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
33205 
33206 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
33207 #if SQLITE_OS_WINCE
33208   /* The GetProcAddressA() routine is only available on Windows CE. */
33209   { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
33210 #else
33211   /* All other Windows platforms expect GetProcAddress() to take
33212   ** an ANSI string regardless of the _UNICODE setting */
33213   { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
33214 #endif
33215 #else
33216   { "GetProcAddressA",         (SYSCALL)0,                       0 },
33217 #endif
33218 
33219 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
33220         LPCSTR))aSyscall[27].pCurrent)
33221 
33222 #if !SQLITE_OS_WINRT
33223   { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
33224 #else
33225   { "GetSystemInfo",           (SYSCALL)0,                       0 },
33226 #endif
33227 
33228 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
33229 
33230   { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
33231 
33232 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
33233 
33234 #if !SQLITE_OS_WINCE
33235   { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
33236 #else
33237   { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
33238 #endif
33239 
33240 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
33241         LPFILETIME))aSyscall[30].pCurrent)
33242 
33243 #if defined(SQLITE_WIN32_HAS_ANSI)
33244   { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
33245 #else
33246   { "GetTempPathA",            (SYSCALL)0,                       0 },
33247 #endif
33248 
33249 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
33250 
33251 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33252   { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
33253 #else
33254   { "GetTempPathW",            (SYSCALL)0,                       0 },
33255 #endif
33256 
33257 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
33258 
33259 #if !SQLITE_OS_WINRT
33260   { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
33261 #else
33262   { "GetTickCount",            (SYSCALL)0,                       0 },
33263 #endif
33264 
33265 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
33266 
33267 #if defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_GETVERSIONEX) && \
33268         SQLITE_WIN32_GETVERSIONEX
33269   { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
33270 #else
33271   { "GetVersionExA",           (SYSCALL)0,                       0 },
33272 #endif
33273 
33274 #define osGetVersionExA ((BOOL(WINAPI*)( \
33275         LPOSVERSIONINFOA))aSyscall[34].pCurrent)
33276 
33277 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
33278         defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
33279   { "GetVersionExW",           (SYSCALL)GetVersionExW,           0 },
33280 #else
33281   { "GetVersionExW",           (SYSCALL)0,                       0 },
33282 #endif
33283 
33284 #define osGetVersionExW ((BOOL(WINAPI*)( \
33285         LPOSVERSIONINFOW))aSyscall[35].pCurrent)
33286 
33287   { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
33288 
33289 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
33290         SIZE_T))aSyscall[36].pCurrent)
33291 
33292 #if !SQLITE_OS_WINRT
33293   { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
33294 #else
33295   { "HeapCreate",              (SYSCALL)0,                       0 },
33296 #endif
33297 
33298 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
33299         SIZE_T))aSyscall[37].pCurrent)
33300 
33301 #if !SQLITE_OS_WINRT
33302   { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
33303 #else
33304   { "HeapDestroy",             (SYSCALL)0,                       0 },
33305 #endif
33306 
33307 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
33308 
33309   { "HeapFree",                (SYSCALL)HeapFree,                0 },
33310 
33311 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
33312 
33313   { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
33314 
33315 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
33316         SIZE_T))aSyscall[40].pCurrent)
33317 
33318   { "HeapSize",                (SYSCALL)HeapSize,                0 },
33319 
33320 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
33321         LPCVOID))aSyscall[41].pCurrent)
33322 
33323 #if !SQLITE_OS_WINRT
33324   { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
33325 #else
33326   { "HeapValidate",            (SYSCALL)0,                       0 },
33327 #endif
33328 
33329 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
33330         LPCVOID))aSyscall[42].pCurrent)
33331 
33332 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
33333   { "HeapCompact",             (SYSCALL)HeapCompact,             0 },
33334 #else
33335   { "HeapCompact",             (SYSCALL)0,                       0 },
33336 #endif
33337 
33338 #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
33339 
33340 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
33341   { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
33342 #else
33343   { "LoadLibraryA",            (SYSCALL)0,                       0 },
33344 #endif
33345 
33346 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
33347 
33348 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
33349         !defined(SQLITE_OMIT_LOAD_EXTENSION)
33350   { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
33351 #else
33352   { "LoadLibraryW",            (SYSCALL)0,                       0 },
33353 #endif
33354 
33355 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
33356 
33357 #if !SQLITE_OS_WINRT
33358   { "LocalFree",               (SYSCALL)LocalFree,               0 },
33359 #else
33360   { "LocalFree",               (SYSCALL)0,                       0 },
33361 #endif
33362 
33363 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
33364 
33365 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
33366   { "LockFile",                (SYSCALL)LockFile,                0 },
33367 #else
33368   { "LockFile",                (SYSCALL)0,                       0 },
33369 #endif
33370 
33371 #ifndef osLockFile
33372 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
33373         DWORD))aSyscall[47].pCurrent)
33374 #endif
33375 
33376 #if !SQLITE_OS_WINCE
33377   { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
33378 #else
33379   { "LockFileEx",              (SYSCALL)0,                       0 },
33380 #endif
33381 
33382 #ifndef osLockFileEx
33383 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
33384         LPOVERLAPPED))aSyscall[48].pCurrent)
33385 #endif
33386 
33387 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
33388   { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
33389 #else
33390   { "MapViewOfFile",           (SYSCALL)0,                       0 },
33391 #endif
33392 
33393 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
33394         SIZE_T))aSyscall[49].pCurrent)
33395 
33396   { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
33397 
33398 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
33399         int))aSyscall[50].pCurrent)
33400 
33401   { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
33402 
33403 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
33404         LARGE_INTEGER*))aSyscall[51].pCurrent)
33405 
33406   { "ReadFile",                (SYSCALL)ReadFile,                0 },
33407 
33408 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
33409         LPOVERLAPPED))aSyscall[52].pCurrent)
33410 
33411   { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
33412 
33413 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
33414 
33415 #if !SQLITE_OS_WINRT
33416   { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
33417 #else
33418   { "SetFilePointer",          (SYSCALL)0,                       0 },
33419 #endif
33420 
33421 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
33422         DWORD))aSyscall[54].pCurrent)
33423 
33424 #if !SQLITE_OS_WINRT
33425   { "Sleep",                   (SYSCALL)Sleep,                   0 },
33426 #else
33427   { "Sleep",                   (SYSCALL)0,                       0 },
33428 #endif
33429 
33430 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
33431 
33432   { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
33433 
33434 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
33435         LPFILETIME))aSyscall[56].pCurrent)
33436 
33437 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
33438   { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
33439 #else
33440   { "UnlockFile",              (SYSCALL)0,                       0 },
33441 #endif
33442 
33443 #ifndef osUnlockFile
33444 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
33445         DWORD))aSyscall[57].pCurrent)
33446 #endif
33447 
33448 #if !SQLITE_OS_WINCE
33449   { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
33450 #else
33451   { "UnlockFileEx",            (SYSCALL)0,                       0 },
33452 #endif
33453 
33454 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
33455         LPOVERLAPPED))aSyscall[58].pCurrent)
33456 
33457 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
33458   { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
33459 #else
33460   { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
33461 #endif
33462 
33463 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
33464 
33465   { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
33466 
33467 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
33468         LPCSTR,LPBOOL))aSyscall[60].pCurrent)
33469 
33470   { "WriteFile",               (SYSCALL)WriteFile,               0 },
33471 
33472 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
33473         LPOVERLAPPED))aSyscall[61].pCurrent)
33474 
33475 #if SQLITE_OS_WINRT
33476   { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
33477 #else
33478   { "CreateEventExW",          (SYSCALL)0,                       0 },
33479 #endif
33480 
33481 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
33482         DWORD,DWORD))aSyscall[62].pCurrent)
33483 
33484 #if !SQLITE_OS_WINRT
33485   { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
33486 #else
33487   { "WaitForSingleObject",     (SYSCALL)0,                       0 },
33488 #endif
33489 
33490 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
33491         DWORD))aSyscall[63].pCurrent)
33492 
33493 #if !SQLITE_OS_WINCE
33494   { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
33495 #else
33496   { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
33497 #endif
33498 
33499 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
33500         BOOL))aSyscall[64].pCurrent)
33501 
33502 #if SQLITE_OS_WINRT
33503   { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
33504 #else
33505   { "SetFilePointerEx",        (SYSCALL)0,                       0 },
33506 #endif
33507 
33508 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
33509         PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
33510 
33511 #if SQLITE_OS_WINRT
33512   { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
33513 #else
33514   { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
33515 #endif
33516 
33517 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
33518         FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
33519 
33520 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
33521   { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
33522 #else
33523   { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
33524 #endif
33525 
33526 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
33527         SIZE_T))aSyscall[67].pCurrent)
33528 
33529 #if SQLITE_OS_WINRT
33530   { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
33531 #else
33532   { "CreateFile2",             (SYSCALL)0,                       0 },
33533 #endif
33534 
33535 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
33536         LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
33537 
33538 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
33539   { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
33540 #else
33541   { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
33542 #endif
33543 
33544 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
33545         DWORD))aSyscall[69].pCurrent)
33546 
33547 #if SQLITE_OS_WINRT
33548   { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
33549 #else
33550   { "GetTickCount64",          (SYSCALL)0,                       0 },
33551 #endif
33552 
33553 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
33554 
33555 #if SQLITE_OS_WINRT
33556   { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
33557 #else
33558   { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
33559 #endif
33560 
33561 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
33562         LPSYSTEM_INFO))aSyscall[71].pCurrent)
33563 
33564 #if defined(SQLITE_WIN32_HAS_ANSI)
33565   { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
33566 #else
33567   { "OutputDebugStringA",      (SYSCALL)0,                       0 },
33568 #endif
33569 
33570 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
33571 
33572 #if defined(SQLITE_WIN32_HAS_WIDE)
33573   { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
33574 #else
33575   { "OutputDebugStringW",      (SYSCALL)0,                       0 },
33576 #endif
33577 
33578 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
33579 
33580   { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
33581 
33582 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
33583 
33584 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
33585   { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
33586 #else
33587   { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
33588 #endif
33589 
33590 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
33591         LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
33592 
33593 /*
33594 ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
33595 **       is really just a macro that uses a compiler intrinsic (e.g. x64).
33596 **       So do not try to make this is into a redefinable interface.
33597 */
33598 #if defined(InterlockedCompareExchange)
33599   { "InterlockedCompareExchange", (SYSCALL)0,                    0 },
33600 
33601 #define osInterlockedCompareExchange InterlockedCompareExchange
33602 #else
33603   { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
33604 
33605 #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
33606         SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
33607 #endif /* defined(InterlockedCompareExchange) */
33608 
33609 }; /* End of the overrideable system calls */
33610 
33611 /*
33612 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
33613 ** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
33614 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
33615 ** system call named zName.
33616 */
33617 static int winSetSystemCall(
33618   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
33619   const char *zName,            /* Name of system call to override */
33620   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
33621 ){
33622   unsigned int i;
33623   int rc = SQLITE_NOTFOUND;
33624 
33625   UNUSED_PARAMETER(pNotUsed);
33626   if( zName==0 ){
33627     /* If no zName is given, restore all system calls to their default
33628     ** settings and return NULL
33629     */
33630     rc = SQLITE_OK;
33631     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
33632       if( aSyscall[i].pDefault ){
33633         aSyscall[i].pCurrent = aSyscall[i].pDefault;
33634       }
33635     }
33636   }else{
33637     /* If zName is specified, operate on only the one system call
33638     ** specified.
33639     */
33640     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
33641       if( strcmp(zName, aSyscall[i].zName)==0 ){
33642         if( aSyscall[i].pDefault==0 ){
33643           aSyscall[i].pDefault = aSyscall[i].pCurrent;
33644         }
33645         rc = SQLITE_OK;
33646         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
33647         aSyscall[i].pCurrent = pNewFunc;
33648         break;
33649       }
33650     }
33651   }
33652   return rc;
33653 }
33654 
33655 /*
33656 ** Return the value of a system call.  Return NULL if zName is not a
33657 ** recognized system call name.  NULL is also returned if the system call
33658 ** is currently undefined.
33659 */
33660 static sqlite3_syscall_ptr winGetSystemCall(
33661   sqlite3_vfs *pNotUsed,
33662   const char *zName
33663 ){
33664   unsigned int i;
33665 
33666   UNUSED_PARAMETER(pNotUsed);
33667   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
33668     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
33669   }
33670   return 0;
33671 }
33672 
33673 /*
33674 ** Return the name of the first system call after zName.  If zName==NULL
33675 ** then return the name of the first system call.  Return NULL if zName
33676 ** is the last system call or if zName is not the name of a valid
33677 ** system call.
33678 */
33679 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
33680   int i = -1;
33681 
33682   UNUSED_PARAMETER(p);
33683   if( zName ){
33684     for(i=0; i<ArraySize(aSyscall)-1; i++){
33685       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
33686     }
33687   }
33688   for(i++; i<ArraySize(aSyscall); i++){
33689     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
33690   }
33691   return 0;
33692 }
33693 
33694 #ifdef SQLITE_WIN32_MALLOC
33695 /*
33696 ** If a Win32 native heap has been configured, this function will attempt to
33697 ** compact it.  Upon success, SQLITE_OK will be returned.  Upon failure, one
33698 ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned.  The
33699 ** "pnLargest" argument, if non-zero, will be used to return the size of the
33700 ** largest committed free block in the heap, in bytes.
33701 */
33702 SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
33703   int rc = SQLITE_OK;
33704   UINT nLargest = 0;
33705   HANDLE hHeap;
33706 
33707   winMemAssertMagic();
33708   hHeap = winMemGetHeap();
33709   assert( hHeap!=0 );
33710   assert( hHeap!=INVALID_HANDLE_VALUE );
33711 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
33712   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
33713 #endif
33714 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
33715   if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
33716     DWORD lastErrno = osGetLastError();
33717     if( lastErrno==NO_ERROR ){
33718       sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
33719                   (void*)hHeap);
33720       rc = SQLITE_NOMEM;
33721     }else{
33722       sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
33723                   osGetLastError(), (void*)hHeap);
33724       rc = SQLITE_ERROR;
33725     }
33726   }
33727 #else
33728   sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
33729               (void*)hHeap);
33730   rc = SQLITE_NOTFOUND;
33731 #endif
33732   if( pnLargest ) *pnLargest = nLargest;
33733   return rc;
33734 }
33735 
33736 /*
33737 ** If a Win32 native heap has been configured, this function will attempt to
33738 ** destroy and recreate it.  If the Win32 native heap is not isolated and/or
33739 ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
33740 ** be returned and no changes will be made to the Win32 native heap.
33741 */
33742 SQLITE_API int sqlite3_win32_reset_heap(){
33743   int rc;
33744   MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
33745   MUTEX_LOGIC( sqlite3_mutex *pMem; )    /* The memsys static mutex */
33746   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
33747   MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
33748   sqlite3_mutex_enter(pMaster);
33749   sqlite3_mutex_enter(pMem);
33750   winMemAssertMagic();
33751   if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
33752     /*
33753     ** At this point, there should be no outstanding memory allocations on
33754     ** the heap.  Also, since both the master and memsys locks are currently
33755     ** being held by us, no other function (i.e. from another thread) should
33756     ** be able to even access the heap.  Attempt to destroy and recreate our
33757     ** isolated Win32 native heap now.
33758     */
33759     assert( winMemGetHeap()!=NULL );
33760     assert( winMemGetOwned() );
33761     assert( sqlite3_memory_used()==0 );
33762     winMemShutdown(winMemGetDataPtr());
33763     assert( winMemGetHeap()==NULL );
33764     assert( !winMemGetOwned() );
33765     assert( sqlite3_memory_used()==0 );
33766     rc = winMemInit(winMemGetDataPtr());
33767     assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
33768     assert( rc!=SQLITE_OK || winMemGetOwned() );
33769     assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
33770   }else{
33771     /*
33772     ** The Win32 native heap cannot be modified because it may be in use.
33773     */
33774     rc = SQLITE_BUSY;
33775   }
33776   sqlite3_mutex_leave(pMem);
33777   sqlite3_mutex_leave(pMaster);
33778   return rc;
33779 }
33780 #endif /* SQLITE_WIN32_MALLOC */
33781 
33782 /*
33783 ** This function outputs the specified (ANSI) string to the Win32 debugger
33784 ** (if available).
33785 */
33786 
33787 SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
33788   char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
33789   int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
33790   if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
33791   assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
33792 #if defined(SQLITE_WIN32_HAS_ANSI)
33793   if( nMin>0 ){
33794     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
33795     memcpy(zDbgBuf, zBuf, nMin);
33796     osOutputDebugStringA(zDbgBuf);
33797   }else{
33798     osOutputDebugStringA(zBuf);
33799   }
33800 #elif defined(SQLITE_WIN32_HAS_WIDE)
33801   memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
33802   if ( osMultiByteToWideChar(
33803           osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
33804           nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
33805     return;
33806   }
33807   osOutputDebugStringW((LPCWSTR)zDbgBuf);
33808 #else
33809   if( nMin>0 ){
33810     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
33811     memcpy(zDbgBuf, zBuf, nMin);
33812     fprintf(stderr, "%s", zDbgBuf);
33813   }else{
33814     fprintf(stderr, "%s", zBuf);
33815   }
33816 #endif
33817 }
33818 
33819 /*
33820 ** The following routine suspends the current thread for at least ms
33821 ** milliseconds.  This is equivalent to the Win32 Sleep() interface.
33822 */
33823 #if SQLITE_OS_WINRT
33824 static HANDLE sleepObj = NULL;
33825 #endif
33826 
33827 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
33828 #if SQLITE_OS_WINRT
33829   if ( sleepObj==NULL ){
33830     sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
33831                                 SYNCHRONIZE);
33832   }
33833   assert( sleepObj!=NULL );
33834   osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
33835 #else
33836   osSleep(milliseconds);
33837 #endif
33838 }
33839 
33840 #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
33841         SQLITE_THREADSAFE>0
33842 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
33843   DWORD rc;
33844   while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
33845                                        TRUE))==WAIT_IO_COMPLETION ){}
33846   return rc;
33847 }
33848 #endif
33849 
33850 /*
33851 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
33852 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
33853 **
33854 ** Here is an interesting observation:  Win95, Win98, and WinME lack
33855 ** the LockFileEx() API.  But we can still statically link against that
33856 ** API as long as we don't call it when running Win95/98/ME.  A call to
33857 ** this routine is used to determine if the host is Win95/98/ME or
33858 ** WinNT/2K/XP so that we will know whether or not we can safely call
33859 ** the LockFileEx() API.
33860 */
33861 
33862 #if !defined(SQLITE_WIN32_GETVERSIONEX) || !SQLITE_WIN32_GETVERSIONEX
33863 # define osIsNT()  (1)
33864 #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
33865 # define osIsNT()  (1)
33866 #elif !defined(SQLITE_WIN32_HAS_WIDE)
33867 # define osIsNT()  (0)
33868 #else
33869 # define osIsNT()  ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
33870 #endif
33871 
33872 /*
33873 ** This function determines if the machine is running a version of Windows
33874 ** based on the NT kernel.
33875 */
33876 SQLITE_API int sqlite3_win32_is_nt(void){
33877 #if SQLITE_OS_WINRT
33878   /*
33879   ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
33880   **       kernel.
33881   */
33882   return 1;
33883 #elif defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
33884   if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
33885 #if defined(SQLITE_WIN32_HAS_ANSI)
33886     OSVERSIONINFOA sInfo;
33887     sInfo.dwOSVersionInfoSize = sizeof(sInfo);
33888     osGetVersionExA(&sInfo);
33889     osInterlockedCompareExchange(&sqlite3_os_type,
33890         (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
33891 #elif defined(SQLITE_WIN32_HAS_WIDE)
33892     OSVERSIONINFOW sInfo;
33893     sInfo.dwOSVersionInfoSize = sizeof(sInfo);
33894     osGetVersionExW(&sInfo);
33895     osInterlockedCompareExchange(&sqlite3_os_type,
33896         (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
33897 #endif
33898   }
33899   return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
33900 #elif SQLITE_TEST
33901   return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
33902 #else
33903   /*
33904   ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
33905   **       deprecated are always assumed to be based on the NT kernel.
33906   */
33907   return 1;
33908 #endif
33909 }
33910 
33911 #ifdef SQLITE_WIN32_MALLOC
33912 /*
33913 ** Allocate nBytes of memory.
33914 */
33915 static void *winMemMalloc(int nBytes){
33916   HANDLE hHeap;
33917   void *p;
33918 
33919   winMemAssertMagic();
33920   hHeap = winMemGetHeap();
33921   assert( hHeap!=0 );
33922   assert( hHeap!=INVALID_HANDLE_VALUE );
33923 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
33924   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
33925 #endif
33926   assert( nBytes>=0 );
33927   p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
33928   if( !p ){
33929     sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
33930                 nBytes, osGetLastError(), (void*)hHeap);
33931   }
33932   return p;
33933 }
33934 
33935 /*
33936 ** Free memory.
33937 */
33938 static void winMemFree(void *pPrior){
33939   HANDLE hHeap;
33940 
33941   winMemAssertMagic();
33942   hHeap = winMemGetHeap();
33943   assert( hHeap!=0 );
33944   assert( hHeap!=INVALID_HANDLE_VALUE );
33945 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
33946   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
33947 #endif
33948   if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
33949   if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
33950     sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
33951                 pPrior, osGetLastError(), (void*)hHeap);
33952   }
33953 }
33954 
33955 /*
33956 ** Change the size of an existing memory allocation
33957 */
33958 static void *winMemRealloc(void *pPrior, int nBytes){
33959   HANDLE hHeap;
33960   void *p;
33961 
33962   winMemAssertMagic();
33963   hHeap = winMemGetHeap();
33964   assert( hHeap!=0 );
33965   assert( hHeap!=INVALID_HANDLE_VALUE );
33966 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
33967   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
33968 #endif
33969   assert( nBytes>=0 );
33970   if( !pPrior ){
33971     p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
33972   }else{
33973     p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
33974   }
33975   if( !p ){
33976     sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
33977                 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
33978                 (void*)hHeap);
33979   }
33980   return p;
33981 }
33982 
33983 /*
33984 ** Return the size of an outstanding allocation, in bytes.
33985 */
33986 static int winMemSize(void *p){
33987   HANDLE hHeap;
33988   SIZE_T n;
33989 
33990   winMemAssertMagic();
33991   hHeap = winMemGetHeap();
33992   assert( hHeap!=0 );
33993   assert( hHeap!=INVALID_HANDLE_VALUE );
33994 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
33995   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
33996 #endif
33997   if( !p ) return 0;
33998   n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
33999   if( n==(SIZE_T)-1 ){
34000     sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
34001                 p, osGetLastError(), (void*)hHeap);
34002     return 0;
34003   }
34004   return (int)n;
34005 }
34006 
34007 /*
34008 ** Round up a request size to the next valid allocation size.
34009 */
34010 static int winMemRoundup(int n){
34011   return n;
34012 }
34013 
34014 /*
34015 ** Initialize this module.
34016 */
34017 static int winMemInit(void *pAppData){
34018   winMemData *pWinMemData = (winMemData *)pAppData;
34019 
34020   if( !pWinMemData ) return SQLITE_ERROR;
34021   assert( pWinMemData->magic1==WINMEM_MAGIC1 );
34022   assert( pWinMemData->magic2==WINMEM_MAGIC2 );
34023 
34024 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
34025   if( !pWinMemData->hHeap ){
34026     DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
34027     DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
34028     if( dwMaximumSize==0 ){
34029       dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
34030     }else if( dwInitialSize>dwMaximumSize ){
34031       dwInitialSize = dwMaximumSize;
34032     }
34033     pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
34034                                       dwInitialSize, dwMaximumSize);
34035     if( !pWinMemData->hHeap ){
34036       sqlite3_log(SQLITE_NOMEM,
34037           "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
34038           osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
34039           dwMaximumSize);
34040       return SQLITE_NOMEM;
34041     }
34042     pWinMemData->bOwned = TRUE;
34043     assert( pWinMemData->bOwned );
34044   }
34045 #else
34046   pWinMemData->hHeap = osGetProcessHeap();
34047   if( !pWinMemData->hHeap ){
34048     sqlite3_log(SQLITE_NOMEM,
34049         "failed to GetProcessHeap (%lu)", osGetLastError());
34050     return SQLITE_NOMEM;
34051   }
34052   pWinMemData->bOwned = FALSE;
34053   assert( !pWinMemData->bOwned );
34054 #endif
34055   assert( pWinMemData->hHeap!=0 );
34056   assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
34057 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34058   assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
34059 #endif
34060   return SQLITE_OK;
34061 }
34062 
34063 /*
34064 ** Deinitialize this module.
34065 */
34066 static void winMemShutdown(void *pAppData){
34067   winMemData *pWinMemData = (winMemData *)pAppData;
34068 
34069   if( !pWinMemData ) return;
34070   assert( pWinMemData->magic1==WINMEM_MAGIC1 );
34071   assert( pWinMemData->magic2==WINMEM_MAGIC2 );
34072 
34073   if( pWinMemData->hHeap ){
34074     assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
34075 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34076     assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
34077 #endif
34078     if( pWinMemData->bOwned ){
34079       if( !osHeapDestroy(pWinMemData->hHeap) ){
34080         sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
34081                     osGetLastError(), (void*)pWinMemData->hHeap);
34082       }
34083       pWinMemData->bOwned = FALSE;
34084     }
34085     pWinMemData->hHeap = NULL;
34086   }
34087 }
34088 
34089 /*
34090 ** Populate the low-level memory allocation function pointers in
34091 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
34092 ** arguments specify the block of memory to manage.
34093 **
34094 ** This routine is only called by sqlite3_config(), and therefore
34095 ** is not required to be threadsafe (it is not).
34096 */
34097 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
34098   static const sqlite3_mem_methods winMemMethods = {
34099     winMemMalloc,
34100     winMemFree,
34101     winMemRealloc,
34102     winMemSize,
34103     winMemRoundup,
34104     winMemInit,
34105     winMemShutdown,
34106     &win_mem_data
34107   };
34108   return &winMemMethods;
34109 }
34110 
34111 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
34112   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
34113 }
34114 #endif /* SQLITE_WIN32_MALLOC */
34115 
34116 /*
34117 ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
34118 **
34119 ** Space to hold the returned string is obtained from malloc.
34120 */
34121 static LPWSTR winUtf8ToUnicode(const char *zFilename){
34122   int nChar;
34123   LPWSTR zWideFilename;
34124 
34125   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
34126   if( nChar==0 ){
34127     return 0;
34128   }
34129   zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
34130   if( zWideFilename==0 ){
34131     return 0;
34132   }
34133   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
34134                                 nChar);
34135   if( nChar==0 ){
34136     sqlite3_free(zWideFilename);
34137     zWideFilename = 0;
34138   }
34139   return zWideFilename;
34140 }
34141 
34142 /*
34143 ** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
34144 ** obtained from sqlite3_malloc().
34145 */
34146 static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
34147   int nByte;
34148   char *zFilename;
34149 
34150   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
34151   if( nByte == 0 ){
34152     return 0;
34153   }
34154   zFilename = sqlite3MallocZero( nByte );
34155   if( zFilename==0 ){
34156     return 0;
34157   }
34158   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
34159                                 0, 0);
34160   if( nByte == 0 ){
34161     sqlite3_free(zFilename);
34162     zFilename = 0;
34163   }
34164   return zFilename;
34165 }
34166 
34167 /*
34168 ** Convert an ANSI string to Microsoft Unicode, based on the
34169 ** current codepage settings for file apis.
34170 **
34171 ** Space to hold the returned string is obtained
34172 ** from sqlite3_malloc.
34173 */
34174 static LPWSTR winMbcsToUnicode(const char *zFilename){
34175   int nByte;
34176   LPWSTR zMbcsFilename;
34177   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
34178 
34179   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
34180                                 0)*sizeof(WCHAR);
34181   if( nByte==0 ){
34182     return 0;
34183   }
34184   zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
34185   if( zMbcsFilename==0 ){
34186     return 0;
34187   }
34188   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
34189                                 nByte);
34190   if( nByte==0 ){
34191     sqlite3_free(zMbcsFilename);
34192     zMbcsFilename = 0;
34193   }
34194   return zMbcsFilename;
34195 }
34196 
34197 /*
34198 ** Convert Microsoft Unicode to multi-byte character string, based on the
34199 ** user's ANSI codepage.
34200 **
34201 ** Space to hold the returned string is obtained from
34202 ** sqlite3_malloc().
34203 */
34204 static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
34205   int nByte;
34206   char *zFilename;
34207   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
34208 
34209   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
34210   if( nByte == 0 ){
34211     return 0;
34212   }
34213   zFilename = sqlite3MallocZero( nByte );
34214   if( zFilename==0 ){
34215     return 0;
34216   }
34217   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
34218                                 nByte, 0, 0);
34219   if( nByte == 0 ){
34220     sqlite3_free(zFilename);
34221     zFilename = 0;
34222   }
34223   return zFilename;
34224 }
34225 
34226 /*
34227 ** Convert multibyte character string to UTF-8.  Space to hold the
34228 ** returned string is obtained from sqlite3_malloc().
34229 */
34230 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
34231   char *zFilenameUtf8;
34232   LPWSTR zTmpWide;
34233 
34234   zTmpWide = winMbcsToUnicode(zFilename);
34235   if( zTmpWide==0 ){
34236     return 0;
34237   }
34238   zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
34239   sqlite3_free(zTmpWide);
34240   return zFilenameUtf8;
34241 }
34242 
34243 /*
34244 ** Convert UTF-8 to multibyte character string.  Space to hold the
34245 ** returned string is obtained from sqlite3_malloc().
34246 */
34247 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
34248   char *zFilenameMbcs;
34249   LPWSTR zTmpWide;
34250 
34251   zTmpWide = winUtf8ToUnicode(zFilename);
34252   if( zTmpWide==0 ){
34253     return 0;
34254   }
34255   zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
34256   sqlite3_free(zTmpWide);
34257   return zFilenameMbcs;
34258 }
34259 
34260 /*
34261 ** This function sets the data directory or the temporary directory based on
34262 ** the provided arguments.  The type argument must be 1 in order to set the
34263 ** data directory or 2 in order to set the temporary directory.  The zValue
34264 ** argument is the name of the directory to use.  The return value will be
34265 ** SQLITE_OK if successful.
34266 */
34267 SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
34268   char **ppDirectory = 0;
34269 #ifndef SQLITE_OMIT_AUTOINIT
34270   int rc = sqlite3_initialize();
34271   if( rc ) return rc;
34272 #endif
34273   if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
34274     ppDirectory = &sqlite3_data_directory;
34275   }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
34276     ppDirectory = &sqlite3_temp_directory;
34277   }
34278   assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
34279           || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
34280   );
34281   assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
34282   if( ppDirectory ){
34283     char *zValueUtf8 = 0;
34284     if( zValue && zValue[0] ){
34285       zValueUtf8 = winUnicodeToUtf8(zValue);
34286       if ( zValueUtf8==0 ){
34287         return SQLITE_NOMEM;
34288       }
34289     }
34290     sqlite3_free(*ppDirectory);
34291     *ppDirectory = zValueUtf8;
34292     return SQLITE_OK;
34293   }
34294   return SQLITE_ERROR;
34295 }
34296 
34297 /*
34298 ** The return value of winGetLastErrorMsg
34299 ** is zero if the error message fits in the buffer, or non-zero
34300 ** otherwise (if the message was truncated).
34301 */
34302 static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
34303   /* FormatMessage returns 0 on failure.  Otherwise it
34304   ** returns the number of TCHARs written to the output
34305   ** buffer, excluding the terminating null char.
34306   */
34307   DWORD dwLen = 0;
34308   char *zOut = 0;
34309 
34310   if( osIsNT() ){
34311 #if SQLITE_OS_WINRT
34312     WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
34313     dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
34314                              FORMAT_MESSAGE_IGNORE_INSERTS,
34315                              NULL,
34316                              lastErrno,
34317                              0,
34318                              zTempWide,
34319                              SQLITE_WIN32_MAX_ERRMSG_CHARS,
34320                              0);
34321 #else
34322     LPWSTR zTempWide = NULL;
34323     dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
34324                              FORMAT_MESSAGE_FROM_SYSTEM |
34325                              FORMAT_MESSAGE_IGNORE_INSERTS,
34326                              NULL,
34327                              lastErrno,
34328                              0,
34329                              (LPWSTR) &zTempWide,
34330                              0,
34331                              0);
34332 #endif
34333     if( dwLen > 0 ){
34334       /* allocate a buffer and convert to UTF8 */
34335       sqlite3BeginBenignMalloc();
34336       zOut = winUnicodeToUtf8(zTempWide);
34337       sqlite3EndBenignMalloc();
34338 #if !SQLITE_OS_WINRT
34339       /* free the system buffer allocated by FormatMessage */
34340       osLocalFree(zTempWide);
34341 #endif
34342     }
34343   }
34344 #ifdef SQLITE_WIN32_HAS_ANSI
34345   else{
34346     char *zTemp = NULL;
34347     dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
34348                              FORMAT_MESSAGE_FROM_SYSTEM |
34349                              FORMAT_MESSAGE_IGNORE_INSERTS,
34350                              NULL,
34351                              lastErrno,
34352                              0,
34353                              (LPSTR) &zTemp,
34354                              0,
34355                              0);
34356     if( dwLen > 0 ){
34357       /* allocate a buffer and convert to UTF8 */
34358       sqlite3BeginBenignMalloc();
34359       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
34360       sqlite3EndBenignMalloc();
34361       /* free the system buffer allocated by FormatMessage */
34362       osLocalFree(zTemp);
34363     }
34364   }
34365 #endif
34366   if( 0 == dwLen ){
34367     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
34368   }else{
34369     /* copy a maximum of nBuf chars to output buffer */
34370     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
34371     /* free the UTF8 buffer */
34372     sqlite3_free(zOut);
34373   }
34374   return 0;
34375 }
34376 
34377 /*
34378 **
34379 ** This function - winLogErrorAtLine() - is only ever called via the macro
34380 ** winLogError().
34381 **
34382 ** This routine is invoked after an error occurs in an OS function.
34383 ** It logs a message using sqlite3_log() containing the current value of
34384 ** error code and, if possible, the human-readable equivalent from
34385 ** FormatMessage.
34386 **
34387 ** The first argument passed to the macro should be the error code that
34388 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
34389 ** The two subsequent arguments should be the name of the OS function that
34390 ** failed and the associated file-system path, if any.
34391 */
34392 #define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
34393 static int winLogErrorAtLine(
34394   int errcode,                    /* SQLite error code */
34395   DWORD lastErrno,                /* Win32 last error */
34396   const char *zFunc,              /* Name of OS function that failed */
34397   const char *zPath,              /* File path associated with error */
34398   int iLine                       /* Source line number where error occurred */
34399 ){
34400   char zMsg[500];                 /* Human readable error text */
34401   int i;                          /* Loop counter */
34402 
34403   zMsg[0] = 0;
34404   winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
34405   assert( errcode!=SQLITE_OK );
34406   if( zPath==0 ) zPath = "";
34407   for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
34408   zMsg[i] = 0;
34409   sqlite3_log(errcode,
34410       "os_win.c:%d: (%lu) %s(%s) - %s",
34411       iLine, lastErrno, zFunc, zPath, zMsg
34412   );
34413 
34414   return errcode;
34415 }
34416 
34417 /*
34418 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
34419 ** will be retried following a locking error - probably caused by
34420 ** antivirus software.  Also the initial delay before the first retry.
34421 ** The delay increases linearly with each retry.
34422 */
34423 #ifndef SQLITE_WIN32_IOERR_RETRY
34424 # define SQLITE_WIN32_IOERR_RETRY 10
34425 #endif
34426 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
34427 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
34428 #endif
34429 static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
34430 static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
34431 
34432 /*
34433 ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
34434 ** error code obtained via GetLastError() is eligible to be retried.  It
34435 ** must accept the error code DWORD as its only argument and should return
34436 ** non-zero if the error code is transient in nature and the operation
34437 ** responsible for generating the original error might succeed upon being
34438 ** retried.  The argument to this macro should be a variable.
34439 **
34440 ** Additionally, a macro named "winIoerrCanRetry2" may be defined.  If it
34441 ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
34442 ** returns zero.  The "winIoerrCanRetry2" macro is completely optional and
34443 ** may be used to include additional error codes in the set that should
34444 ** result in the failing I/O operation being retried by the caller.  If
34445 ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
34446 ** identical to those of the "winIoerrCanRetry1" macro.
34447 */
34448 #if !defined(winIoerrCanRetry1)
34449 #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED)        || \
34450                               ((a)==ERROR_SHARING_VIOLATION)    || \
34451                               ((a)==ERROR_LOCK_VIOLATION)       || \
34452                               ((a)==ERROR_DEV_NOT_EXIST)        || \
34453                               ((a)==ERROR_NETNAME_DELETED)      || \
34454                               ((a)==ERROR_SEM_TIMEOUT)          || \
34455                               ((a)==ERROR_NETWORK_UNREACHABLE))
34456 #endif
34457 
34458 /*
34459 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
34460 ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
34461 ** to give up with an error.
34462 */
34463 static int winRetryIoerr(int *pnRetry, DWORD *pError){
34464   DWORD e = osGetLastError();
34465   if( *pnRetry>=winIoerrRetry ){
34466     if( pError ){
34467       *pError = e;
34468     }
34469     return 0;
34470   }
34471   if( winIoerrCanRetry1(e) ){
34472     sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
34473     ++*pnRetry;
34474     return 1;
34475   }
34476 #if defined(winIoerrCanRetry2)
34477   else if( winIoerrCanRetry2(e) ){
34478     sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
34479     ++*pnRetry;
34480     return 1;
34481   }
34482 #endif
34483   if( pError ){
34484     *pError = e;
34485   }
34486   return 0;
34487 }
34488 
34489 /*
34490 ** Log a I/O error retry episode.
34491 */
34492 static void winLogIoerr(int nRetry){
34493   if( nRetry ){
34494     sqlite3_log(SQLITE_IOERR,
34495       "delayed %dms for lock/sharing conflict",
34496       winIoerrRetryDelay*nRetry*(nRetry+1)/2
34497     );
34498   }
34499 }
34500 
34501 #if SQLITE_OS_WINCE
34502 /*************************************************************************
34503 ** This section contains code for WinCE only.
34504 */
34505 #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
34506 /*
34507 ** The MSVC CRT on Windows CE may not have a localtime() function.  So
34508 ** create a substitute.
34509 */
34510 /* #include <time.h> */
34511 struct tm *__cdecl localtime(const time_t *t)
34512 {
34513   static struct tm y;
34514   FILETIME uTm, lTm;
34515   SYSTEMTIME pTm;
34516   sqlite3_int64 t64;
34517   t64 = *t;
34518   t64 = (t64 + 11644473600)*10000000;
34519   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
34520   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
34521   osFileTimeToLocalFileTime(&uTm,&lTm);
34522   osFileTimeToSystemTime(&lTm,&pTm);
34523   y.tm_year = pTm.wYear - 1900;
34524   y.tm_mon = pTm.wMonth - 1;
34525   y.tm_wday = pTm.wDayOfWeek;
34526   y.tm_mday = pTm.wDay;
34527   y.tm_hour = pTm.wHour;
34528   y.tm_min = pTm.wMinute;
34529   y.tm_sec = pTm.wSecond;
34530   return &y;
34531 }
34532 #endif
34533 
34534 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
34535 
34536 /*
34537 ** Acquire a lock on the handle h
34538 */
34539 static void winceMutexAcquire(HANDLE h){
34540    DWORD dwErr;
34541    do {
34542      dwErr = osWaitForSingleObject(h, INFINITE);
34543    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
34544 }
34545 /*
34546 ** Release a lock acquired by winceMutexAcquire()
34547 */
34548 #define winceMutexRelease(h) ReleaseMutex(h)
34549 
34550 /*
34551 ** Create the mutex and shared memory used for locking in the file
34552 ** descriptor pFile
34553 */
34554 static int winceCreateLock(const char *zFilename, winFile *pFile){
34555   LPWSTR zTok;
34556   LPWSTR zName;
34557   DWORD lastErrno;
34558   BOOL bLogged = FALSE;
34559   BOOL bInit = TRUE;
34560 
34561   zName = winUtf8ToUnicode(zFilename);
34562   if( zName==0 ){
34563     /* out of memory */
34564     return SQLITE_IOERR_NOMEM;
34565   }
34566 
34567   /* Initialize the local lockdata */
34568   memset(&pFile->local, 0, sizeof(pFile->local));
34569 
34570   /* Replace the backslashes from the filename and lowercase it
34571   ** to derive a mutex name. */
34572   zTok = osCharLowerW(zName);
34573   for (;*zTok;zTok++){
34574     if (*zTok == '\\') *zTok = '_';
34575   }
34576 
34577   /* Create/open the named mutex */
34578   pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
34579   if (!pFile->hMutex){
34580     pFile->lastErrno = osGetLastError();
34581     sqlite3_free(zName);
34582     return winLogError(SQLITE_IOERR, pFile->lastErrno,
34583                        "winceCreateLock1", zFilename);
34584   }
34585 
34586   /* Acquire the mutex before continuing */
34587   winceMutexAcquire(pFile->hMutex);
34588 
34589   /* Since the names of named mutexes, semaphores, file mappings etc are
34590   ** case-sensitive, take advantage of that by uppercasing the mutex name
34591   ** and using that as the shared filemapping name.
34592   */
34593   osCharUpperW(zName);
34594   pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
34595                                         PAGE_READWRITE, 0, sizeof(winceLock),
34596                                         zName);
34597 
34598   /* Set a flag that indicates we're the first to create the memory so it
34599   ** must be zero-initialized */
34600   lastErrno = osGetLastError();
34601   if (lastErrno == ERROR_ALREADY_EXISTS){
34602     bInit = FALSE;
34603   }
34604 
34605   sqlite3_free(zName);
34606 
34607   /* If we succeeded in making the shared memory handle, map it. */
34608   if( pFile->hShared ){
34609     pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
34610              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
34611     /* If mapping failed, close the shared memory handle and erase it */
34612     if( !pFile->shared ){
34613       pFile->lastErrno = osGetLastError();
34614       winLogError(SQLITE_IOERR, pFile->lastErrno,
34615                   "winceCreateLock2", zFilename);
34616       bLogged = TRUE;
34617       osCloseHandle(pFile->hShared);
34618       pFile->hShared = NULL;
34619     }
34620   }
34621 
34622   /* If shared memory could not be created, then close the mutex and fail */
34623   if( pFile->hShared==NULL ){
34624     if( !bLogged ){
34625       pFile->lastErrno = lastErrno;
34626       winLogError(SQLITE_IOERR, pFile->lastErrno,
34627                   "winceCreateLock3", zFilename);
34628       bLogged = TRUE;
34629     }
34630     winceMutexRelease(pFile->hMutex);
34631     osCloseHandle(pFile->hMutex);
34632     pFile->hMutex = NULL;
34633     return SQLITE_IOERR;
34634   }
34635 
34636   /* Initialize the shared memory if we're supposed to */
34637   if( bInit ){
34638     memset(pFile->shared, 0, sizeof(winceLock));
34639   }
34640 
34641   winceMutexRelease(pFile->hMutex);
34642   return SQLITE_OK;
34643 }
34644 
34645 /*
34646 ** Destroy the part of winFile that deals with wince locks
34647 */
34648 static void winceDestroyLock(winFile *pFile){
34649   if (pFile->hMutex){
34650     /* Acquire the mutex */
34651     winceMutexAcquire(pFile->hMutex);
34652 
34653     /* The following blocks should probably assert in debug mode, but they
34654        are to cleanup in case any locks remained open */
34655     if (pFile->local.nReaders){
34656       pFile->shared->nReaders --;
34657     }
34658     if (pFile->local.bReserved){
34659       pFile->shared->bReserved = FALSE;
34660     }
34661     if (pFile->local.bPending){
34662       pFile->shared->bPending = FALSE;
34663     }
34664     if (pFile->local.bExclusive){
34665       pFile->shared->bExclusive = FALSE;
34666     }
34667 
34668     /* De-reference and close our copy of the shared memory handle */
34669     osUnmapViewOfFile(pFile->shared);
34670     osCloseHandle(pFile->hShared);
34671 
34672     /* Done with the mutex */
34673     winceMutexRelease(pFile->hMutex);
34674     osCloseHandle(pFile->hMutex);
34675     pFile->hMutex = NULL;
34676   }
34677 }
34678 
34679 /*
34680 ** An implementation of the LockFile() API of Windows for CE
34681 */
34682 static BOOL winceLockFile(
34683   LPHANDLE phFile,
34684   DWORD dwFileOffsetLow,
34685   DWORD dwFileOffsetHigh,
34686   DWORD nNumberOfBytesToLockLow,
34687   DWORD nNumberOfBytesToLockHigh
34688 ){
34689   winFile *pFile = HANDLE_TO_WINFILE(phFile);
34690   BOOL bReturn = FALSE;
34691 
34692   UNUSED_PARAMETER(dwFileOffsetHigh);
34693   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
34694 
34695   if (!pFile->hMutex) return TRUE;
34696   winceMutexAcquire(pFile->hMutex);
34697 
34698   /* Wanting an exclusive lock? */
34699   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
34700        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
34701     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
34702        pFile->shared->bExclusive = TRUE;
34703        pFile->local.bExclusive = TRUE;
34704        bReturn = TRUE;
34705     }
34706   }
34707 
34708   /* Want a read-only lock? */
34709   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
34710            nNumberOfBytesToLockLow == 1){
34711     if (pFile->shared->bExclusive == 0){
34712       pFile->local.nReaders ++;
34713       if (pFile->local.nReaders == 1){
34714         pFile->shared->nReaders ++;
34715       }
34716       bReturn = TRUE;
34717     }
34718   }
34719 
34720   /* Want a pending lock? */
34721   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
34722            && nNumberOfBytesToLockLow == 1){
34723     /* If no pending lock has been acquired, then acquire it */
34724     if (pFile->shared->bPending == 0) {
34725       pFile->shared->bPending = TRUE;
34726       pFile->local.bPending = TRUE;
34727       bReturn = TRUE;
34728     }
34729   }
34730 
34731   /* Want a reserved lock? */
34732   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
34733            && nNumberOfBytesToLockLow == 1){
34734     if (pFile->shared->bReserved == 0) {
34735       pFile->shared->bReserved = TRUE;
34736       pFile->local.bReserved = TRUE;
34737       bReturn = TRUE;
34738     }
34739   }
34740 
34741   winceMutexRelease(pFile->hMutex);
34742   return bReturn;
34743 }
34744 
34745 /*
34746 ** An implementation of the UnlockFile API of Windows for CE
34747 */
34748 static BOOL winceUnlockFile(
34749   LPHANDLE phFile,
34750   DWORD dwFileOffsetLow,
34751   DWORD dwFileOffsetHigh,
34752   DWORD nNumberOfBytesToUnlockLow,
34753   DWORD nNumberOfBytesToUnlockHigh
34754 ){
34755   winFile *pFile = HANDLE_TO_WINFILE(phFile);
34756   BOOL bReturn = FALSE;
34757 
34758   UNUSED_PARAMETER(dwFileOffsetHigh);
34759   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
34760 
34761   if (!pFile->hMutex) return TRUE;
34762   winceMutexAcquire(pFile->hMutex);
34763 
34764   /* Releasing a reader lock or an exclusive lock */
34765   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
34766     /* Did we have an exclusive lock? */
34767     if (pFile->local.bExclusive){
34768       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
34769       pFile->local.bExclusive = FALSE;
34770       pFile->shared->bExclusive = FALSE;
34771       bReturn = TRUE;
34772     }
34773 
34774     /* Did we just have a reader lock? */
34775     else if (pFile->local.nReaders){
34776       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
34777              || nNumberOfBytesToUnlockLow == 1);
34778       pFile->local.nReaders --;
34779       if (pFile->local.nReaders == 0)
34780       {
34781         pFile->shared->nReaders --;
34782       }
34783       bReturn = TRUE;
34784     }
34785   }
34786 
34787   /* Releasing a pending lock */
34788   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
34789            && nNumberOfBytesToUnlockLow == 1){
34790     if (pFile->local.bPending){
34791       pFile->local.bPending = FALSE;
34792       pFile->shared->bPending = FALSE;
34793       bReturn = TRUE;
34794     }
34795   }
34796   /* Releasing a reserved lock */
34797   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
34798            && nNumberOfBytesToUnlockLow == 1){
34799     if (pFile->local.bReserved) {
34800       pFile->local.bReserved = FALSE;
34801       pFile->shared->bReserved = FALSE;
34802       bReturn = TRUE;
34803     }
34804   }
34805 
34806   winceMutexRelease(pFile->hMutex);
34807   return bReturn;
34808 }
34809 /*
34810 ** End of the special code for wince
34811 *****************************************************************************/
34812 #endif /* SQLITE_OS_WINCE */
34813 
34814 /*
34815 ** Lock a file region.
34816 */
34817 static BOOL winLockFile(
34818   LPHANDLE phFile,
34819   DWORD flags,
34820   DWORD offsetLow,
34821   DWORD offsetHigh,
34822   DWORD numBytesLow,
34823   DWORD numBytesHigh
34824 ){
34825 #if SQLITE_OS_WINCE
34826   /*
34827   ** NOTE: Windows CE is handled differently here due its lack of the Win32
34828   **       API LockFile.
34829   */
34830   return winceLockFile(phFile, offsetLow, offsetHigh,
34831                        numBytesLow, numBytesHigh);
34832 #else
34833   if( osIsNT() ){
34834     OVERLAPPED ovlp;
34835     memset(&ovlp, 0, sizeof(OVERLAPPED));
34836     ovlp.Offset = offsetLow;
34837     ovlp.OffsetHigh = offsetHigh;
34838     return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
34839   }else{
34840     return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
34841                       numBytesHigh);
34842   }
34843 #endif
34844 }
34845 
34846 /*
34847 ** Unlock a file region.
34848  */
34849 static BOOL winUnlockFile(
34850   LPHANDLE phFile,
34851   DWORD offsetLow,
34852   DWORD offsetHigh,
34853   DWORD numBytesLow,
34854   DWORD numBytesHigh
34855 ){
34856 #if SQLITE_OS_WINCE
34857   /*
34858   ** NOTE: Windows CE is handled differently here due its lack of the Win32
34859   **       API UnlockFile.
34860   */
34861   return winceUnlockFile(phFile, offsetLow, offsetHigh,
34862                          numBytesLow, numBytesHigh);
34863 #else
34864   if( osIsNT() ){
34865     OVERLAPPED ovlp;
34866     memset(&ovlp, 0, sizeof(OVERLAPPED));
34867     ovlp.Offset = offsetLow;
34868     ovlp.OffsetHigh = offsetHigh;
34869     return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
34870   }else{
34871     return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
34872                         numBytesHigh);
34873   }
34874 #endif
34875 }
34876 
34877 /*****************************************************************************
34878 ** The next group of routines implement the I/O methods specified
34879 ** by the sqlite3_io_methods object.
34880 ******************************************************************************/
34881 
34882 /*
34883 ** Some Microsoft compilers lack this definition.
34884 */
34885 #ifndef INVALID_SET_FILE_POINTER
34886 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
34887 #endif
34888 
34889 /*
34890 ** Move the current position of the file handle passed as the first
34891 ** argument to offset iOffset within the file. If successful, return 0.
34892 ** Otherwise, set pFile->lastErrno and return non-zero.
34893 */
34894 static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
34895 #if !SQLITE_OS_WINRT
34896   LONG upperBits;                 /* Most sig. 32 bits of new offset */
34897   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
34898   DWORD dwRet;                    /* Value returned by SetFilePointer() */
34899   DWORD lastErrno;                /* Value returned by GetLastError() */
34900 
34901   OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
34902 
34903   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
34904   lowerBits = (LONG)(iOffset & 0xffffffff);
34905 
34906   /* API oddity: If successful, SetFilePointer() returns a dword
34907   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
34908   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
34909   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
34910   ** whether an error has actually occurred, it is also necessary to call
34911   ** GetLastError().
34912   */
34913   dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
34914 
34915   if( (dwRet==INVALID_SET_FILE_POINTER
34916       && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
34917     pFile->lastErrno = lastErrno;
34918     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
34919                 "winSeekFile", pFile->zPath);
34920     OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
34921     return 1;
34922   }
34923 
34924   OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
34925   return 0;
34926 #else
34927   /*
34928   ** Same as above, except that this implementation works for WinRT.
34929   */
34930 
34931   LARGE_INTEGER x;                /* The new offset */
34932   BOOL bRet;                      /* Value returned by SetFilePointerEx() */
34933 
34934   x.QuadPart = iOffset;
34935   bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
34936 
34937   if(!bRet){
34938     pFile->lastErrno = osGetLastError();
34939     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
34940                 "winSeekFile", pFile->zPath);
34941     OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
34942     return 1;
34943   }
34944 
34945   OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
34946   return 0;
34947 #endif
34948 }
34949 
34950 #if SQLITE_MAX_MMAP_SIZE>0
34951 /* Forward references to VFS helper methods used for memory mapped files */
34952 static int winMapfile(winFile*, sqlite3_int64);
34953 static int winUnmapfile(winFile*);
34954 #endif
34955 
34956 /*
34957 ** Close a file.
34958 **
34959 ** It is reported that an attempt to close a handle might sometimes
34960 ** fail.  This is a very unreasonable result, but Windows is notorious
34961 ** for being unreasonable so I do not doubt that it might happen.  If
34962 ** the close fails, we pause for 100 milliseconds and try again.  As
34963 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
34964 ** giving up and returning an error.
34965 */
34966 #define MX_CLOSE_ATTEMPT 3
34967 static int winClose(sqlite3_file *id){
34968   int rc, cnt = 0;
34969   winFile *pFile = (winFile*)id;
34970 
34971   assert( id!=0 );
34972 #ifndef SQLITE_OMIT_WAL
34973   assert( pFile->pShm==0 );
34974 #endif
34975   assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
34976   OSTRACE(("CLOSE file=%p\n", pFile->h));
34977 
34978 #if SQLITE_MAX_MMAP_SIZE>0
34979   winUnmapfile(pFile);
34980 #endif
34981 
34982   do{
34983     rc = osCloseHandle(pFile->h);
34984     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
34985   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
34986 #if SQLITE_OS_WINCE
34987 #define WINCE_DELETION_ATTEMPTS 3
34988   winceDestroyLock(pFile);
34989   if( pFile->zDeleteOnClose ){
34990     int cnt = 0;
34991     while(
34992            osDeleteFileW(pFile->zDeleteOnClose)==0
34993         && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
34994         && cnt++ < WINCE_DELETION_ATTEMPTS
34995     ){
34996        sqlite3_win32_sleep(100);  /* Wait a little before trying again */
34997     }
34998     sqlite3_free(pFile->zDeleteOnClose);
34999   }
35000 #endif
35001   if( rc ){
35002     pFile->h = NULL;
35003   }
35004   OpenCounter(-1);
35005   OSTRACE(("CLOSE file=%p, rc=%s\n", pFile->h, rc ? "ok" : "failed"));
35006   return rc ? SQLITE_OK
35007             : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
35008                           "winClose", pFile->zPath);
35009 }
35010 
35011 /*
35012 ** Read data from a file into a buffer.  Return SQLITE_OK if all
35013 ** bytes were read successfully and SQLITE_IOERR if anything goes
35014 ** wrong.
35015 */
35016 static int winRead(
35017   sqlite3_file *id,          /* File to read from */
35018   void *pBuf,                /* Write content into this buffer */
35019   int amt,                   /* Number of bytes to read */
35020   sqlite3_int64 offset       /* Begin reading at this offset */
35021 ){
35022 #if !SQLITE_OS_WINCE
35023   OVERLAPPED overlapped;          /* The offset for ReadFile. */
35024 #endif
35025   winFile *pFile = (winFile*)id;  /* file handle */
35026   DWORD nRead;                    /* Number of bytes actually read from file */
35027   int nRetry = 0;                 /* Number of retrys */
35028 
35029   assert( id!=0 );
35030   assert( amt>0 );
35031   assert( offset>=0 );
35032   SimulateIOError(return SQLITE_IOERR_READ);
35033   OSTRACE(("READ file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
35034            pFile->h, pBuf, amt, offset, pFile->locktype));
35035 
35036 #if SQLITE_MAX_MMAP_SIZE>0
35037   /* Deal with as much of this read request as possible by transfering
35038   ** data from the memory mapping using memcpy().  */
35039   if( offset<pFile->mmapSize ){
35040     if( offset+amt <= pFile->mmapSize ){
35041       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
35042       OSTRACE(("READ-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
35043       return SQLITE_OK;
35044     }else{
35045       int nCopy = (int)(pFile->mmapSize - offset);
35046       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
35047       pBuf = &((u8 *)pBuf)[nCopy];
35048       amt -= nCopy;
35049       offset += nCopy;
35050     }
35051   }
35052 #endif
35053 
35054 #if SQLITE_OS_WINCE
35055   if( winSeekFile(pFile, offset) ){
35056     OSTRACE(("READ file=%p, rc=SQLITE_FULL\n", pFile->h));
35057     return SQLITE_FULL;
35058   }
35059   while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
35060 #else
35061   memset(&overlapped, 0, sizeof(OVERLAPPED));
35062   overlapped.Offset = (LONG)(offset & 0xffffffff);
35063   overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
35064   while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
35065          osGetLastError()!=ERROR_HANDLE_EOF ){
35066 #endif
35067     DWORD lastErrno;
35068     if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
35069     pFile->lastErrno = lastErrno;
35070     OSTRACE(("READ file=%p, rc=SQLITE_IOERR_READ\n", pFile->h));
35071     return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
35072                        "winRead", pFile->zPath);
35073   }
35074   winLogIoerr(nRetry);
35075   if( nRead<(DWORD)amt ){
35076     /* Unread parts of the buffer must be zero-filled */
35077     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
35078     OSTRACE(("READ file=%p, rc=SQLITE_IOERR_SHORT_READ\n", pFile->h));
35079     return SQLITE_IOERR_SHORT_READ;
35080   }
35081 
35082   OSTRACE(("READ file=%p, rc=SQLITE_OK\n", pFile->h));
35083   return SQLITE_OK;
35084 }
35085 
35086 /*
35087 ** Write data from a buffer into a file.  Return SQLITE_OK on success
35088 ** or some other error code on failure.
35089 */
35090 static int winWrite(
35091   sqlite3_file *id,               /* File to write into */
35092   const void *pBuf,               /* The bytes to be written */
35093   int amt,                        /* Number of bytes to write */
35094   sqlite3_int64 offset            /* Offset into the file to begin writing at */
35095 ){
35096   int rc = 0;                     /* True if error has occurred, else false */
35097   winFile *pFile = (winFile*)id;  /* File handle */
35098   int nRetry = 0;                 /* Number of retries */
35099 
35100   assert( amt>0 );
35101   assert( pFile );
35102   SimulateIOError(return SQLITE_IOERR_WRITE);
35103   SimulateDiskfullError(return SQLITE_FULL);
35104 
35105   OSTRACE(("WRITE file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
35106            pFile->h, pBuf, amt, offset, pFile->locktype));
35107 
35108 #if SQLITE_MAX_MMAP_SIZE>0
35109   /* Deal with as much of this write request as possible by transfering
35110   ** data from the memory mapping using memcpy().  */
35111   if( offset<pFile->mmapSize ){
35112     if( offset+amt <= pFile->mmapSize ){
35113       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
35114       OSTRACE(("WRITE-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
35115       return SQLITE_OK;
35116     }else{
35117       int nCopy = (int)(pFile->mmapSize - offset);
35118       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
35119       pBuf = &((u8 *)pBuf)[nCopy];
35120       amt -= nCopy;
35121       offset += nCopy;
35122     }
35123   }
35124 #endif
35125 
35126 #if SQLITE_OS_WINCE
35127   rc = winSeekFile(pFile, offset);
35128   if( rc==0 ){
35129 #else
35130   {
35131 #endif
35132 #if !SQLITE_OS_WINCE
35133     OVERLAPPED overlapped;        /* The offset for WriteFile. */
35134 #endif
35135     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
35136     int nRem = amt;               /* Number of bytes yet to be written */
35137     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
35138     DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
35139 
35140 #if !SQLITE_OS_WINCE
35141     memset(&overlapped, 0, sizeof(OVERLAPPED));
35142     overlapped.Offset = (LONG)(offset & 0xffffffff);
35143     overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
35144 #endif
35145 
35146     while( nRem>0 ){
35147 #if SQLITE_OS_WINCE
35148       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
35149 #else
35150       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
35151 #endif
35152         if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
35153         break;
35154       }
35155       assert( nWrite==0 || nWrite<=(DWORD)nRem );
35156       if( nWrite==0 || nWrite>(DWORD)nRem ){
35157         lastErrno = osGetLastError();
35158         break;
35159       }
35160 #if !SQLITE_OS_WINCE
35161       offset += nWrite;
35162       overlapped.Offset = (LONG)(offset & 0xffffffff);
35163       overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
35164 #endif
35165       aRem += nWrite;
35166       nRem -= nWrite;
35167     }
35168     if( nRem>0 ){
35169       pFile->lastErrno = lastErrno;
35170       rc = 1;
35171     }
35172   }
35173 
35174   if( rc ){
35175     if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
35176        || ( pFile->lastErrno==ERROR_DISK_FULL )){
35177       OSTRACE(("WRITE file=%p, rc=SQLITE_FULL\n", pFile->h));
35178       return winLogError(SQLITE_FULL, pFile->lastErrno,
35179                          "winWrite1", pFile->zPath);
35180     }
35181     OSTRACE(("WRITE file=%p, rc=SQLITE_IOERR_WRITE\n", pFile->h));
35182     return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
35183                        "winWrite2", pFile->zPath);
35184   }else{
35185     winLogIoerr(nRetry);
35186   }
35187   OSTRACE(("WRITE file=%p, rc=SQLITE_OK\n", pFile->h));
35188   return SQLITE_OK;
35189 }
35190 
35191 /*
35192 ** Truncate an open file to a specified size
35193 */
35194 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
35195   winFile *pFile = (winFile*)id;  /* File handle object */
35196   int rc = SQLITE_OK;             /* Return code for this function */
35197   DWORD lastErrno;
35198 
35199   assert( pFile );
35200   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
35201   OSTRACE(("TRUNCATE file=%p, size=%lld, lock=%d\n",
35202            pFile->h, nByte, pFile->locktype));
35203 
35204   /* If the user has configured a chunk-size for this file, truncate the
35205   ** file so that it consists of an integer number of chunks (i.e. the
35206   ** actual file size after the operation may be larger than the requested
35207   ** size).
35208   */
35209   if( pFile->szChunk>0 ){
35210     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
35211   }
35212 
35213   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
35214   if( winSeekFile(pFile, nByte) ){
35215     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
35216                      "winTruncate1", pFile->zPath);
35217   }else if( 0==osSetEndOfFile(pFile->h) &&
35218             ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
35219     pFile->lastErrno = lastErrno;
35220     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
35221                      "winTruncate2", pFile->zPath);
35222   }
35223 
35224 #if SQLITE_MAX_MMAP_SIZE>0
35225   /* If the file was truncated to a size smaller than the currently
35226   ** mapped region, reduce the effective mapping size as well. SQLite will
35227   ** use read() and write() to access data beyond this point from now on.
35228   */
35229   if( pFile->pMapRegion && nByte<pFile->mmapSize ){
35230     pFile->mmapSize = nByte;
35231   }
35232 #endif
35233 
35234   OSTRACE(("TRUNCATE file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
35235   return rc;
35236 }
35237 
35238 #ifdef SQLITE_TEST
35239 /*
35240 ** Count the number of fullsyncs and normal syncs.  This is used to test
35241 ** that syncs and fullsyncs are occuring at the right times.
35242 */
35243 SQLITE_API int sqlite3_sync_count = 0;
35244 SQLITE_API int sqlite3_fullsync_count = 0;
35245 #endif
35246 
35247 /*
35248 ** Make sure all writes to a particular file are committed to disk.
35249 */
35250 static int winSync(sqlite3_file *id, int flags){
35251 #ifndef SQLITE_NO_SYNC
35252   /*
35253   ** Used only when SQLITE_NO_SYNC is not defined.
35254    */
35255   BOOL rc;
35256 #endif
35257 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
35258     (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
35259   /*
35260   ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
35261   ** OSTRACE() macros.
35262    */
35263   winFile *pFile = (winFile*)id;
35264 #else
35265   UNUSED_PARAMETER(id);
35266 #endif
35267 
35268   assert( pFile );
35269   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
35270   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
35271       || (flags&0x0F)==SQLITE_SYNC_FULL
35272   );
35273 
35274   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
35275   ** line is to test that doing so does not cause any problems.
35276   */
35277   SimulateDiskfullError( return SQLITE_FULL );
35278 
35279   OSTRACE(("SYNC file=%p, flags=%x, lock=%d\n",
35280            pFile->h, flags, pFile->locktype));
35281 
35282 #ifndef SQLITE_TEST
35283   UNUSED_PARAMETER(flags);
35284 #else
35285   if( (flags&0x0F)==SQLITE_SYNC_FULL ){
35286     sqlite3_fullsync_count++;
35287   }
35288   sqlite3_sync_count++;
35289 #endif
35290 
35291   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
35292   ** no-op
35293   */
35294 #ifdef SQLITE_NO_SYNC
35295   OSTRACE(("SYNC-NOP file=%p, rc=SQLITE_OK\n", pFile->h));
35296   return SQLITE_OK;
35297 #else
35298   rc = osFlushFileBuffers(pFile->h);
35299   SimulateIOError( rc=FALSE );
35300   if( rc ){
35301     OSTRACE(("SYNC file=%p, rc=SQLITE_OK\n", pFile->h));
35302     return SQLITE_OK;
35303   }else{
35304     pFile->lastErrno = osGetLastError();
35305     OSTRACE(("SYNC file=%p, rc=SQLITE_IOERR_FSYNC\n", pFile->h));
35306     return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
35307                        "winSync", pFile->zPath);
35308   }
35309 #endif
35310 }
35311 
35312 /*
35313 ** Determine the current size of a file in bytes
35314 */
35315 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
35316   winFile *pFile = (winFile*)id;
35317   int rc = SQLITE_OK;
35318 
35319   assert( id!=0 );
35320   assert( pSize!=0 );
35321   SimulateIOError(return SQLITE_IOERR_FSTAT);
35322   OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
35323 
35324 #if SQLITE_OS_WINRT
35325   {
35326     FILE_STANDARD_INFO info;
35327     if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
35328                                      &info, sizeof(info)) ){
35329       *pSize = info.EndOfFile.QuadPart;
35330     }else{
35331       pFile->lastErrno = osGetLastError();
35332       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
35333                        "winFileSize", pFile->zPath);
35334     }
35335   }
35336 #else
35337   {
35338     DWORD upperBits;
35339     DWORD lowerBits;
35340     DWORD lastErrno;
35341 
35342     lowerBits = osGetFileSize(pFile->h, &upperBits);
35343     *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
35344     if(   (lowerBits == INVALID_FILE_SIZE)
35345        && ((lastErrno = osGetLastError())!=NO_ERROR) ){
35346       pFile->lastErrno = lastErrno;
35347       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
35348                        "winFileSize", pFile->zPath);
35349     }
35350   }
35351 #endif
35352   OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
35353            pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
35354   return rc;
35355 }
35356 
35357 /*
35358 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
35359 */
35360 #ifndef LOCKFILE_FAIL_IMMEDIATELY
35361 # define LOCKFILE_FAIL_IMMEDIATELY 1
35362 #endif
35363 
35364 #ifndef LOCKFILE_EXCLUSIVE_LOCK
35365 # define LOCKFILE_EXCLUSIVE_LOCK 2
35366 #endif
35367 
35368 /*
35369 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
35370 ** When the LockFile function was used, it was always expected to fail
35371 ** immediately if the lock could not be obtained.  Also, it always expected to
35372 ** obtain an exclusive lock.  These flags are used with the LockFileEx function
35373 ** and reflect those expectations; therefore, they should not be changed.
35374 */
35375 #ifndef SQLITE_LOCKFILE_FLAGS
35376 # define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
35377                                   LOCKFILE_EXCLUSIVE_LOCK)
35378 #endif
35379 
35380 /*
35381 ** Currently, SQLite never calls the LockFileEx function without wanting the
35382 ** call to fail immediately if the lock cannot be obtained.
35383 */
35384 #ifndef SQLITE_LOCKFILEEX_FLAGS
35385 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
35386 #endif
35387 
35388 /*
35389 ** Acquire a reader lock.
35390 ** Different API routines are called depending on whether or not this
35391 ** is Win9x or WinNT.
35392 */
35393 static int winGetReadLock(winFile *pFile){
35394   int res;
35395   OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
35396   if( osIsNT() ){
35397 #if SQLITE_OS_WINCE
35398     /*
35399     ** NOTE: Windows CE is handled differently here due its lack of the Win32
35400     **       API LockFileEx.
35401     */
35402     res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
35403 #else
35404     res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
35405                       SHARED_SIZE, 0);
35406 #endif
35407   }
35408 #ifdef SQLITE_WIN32_HAS_ANSI
35409   else{
35410     int lk;
35411     sqlite3_randomness(sizeof(lk), &lk);
35412     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
35413     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
35414                       SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
35415   }
35416 #endif
35417   if( res == 0 ){
35418     pFile->lastErrno = osGetLastError();
35419     /* No need to log a failure to lock */
35420   }
35421   OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
35422   return res;
35423 }
35424 
35425 /*
35426 ** Undo a readlock
35427 */
35428 static int winUnlockReadLock(winFile *pFile){
35429   int res;
35430   DWORD lastErrno;
35431   OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
35432   if( osIsNT() ){
35433     res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
35434   }
35435 #ifdef SQLITE_WIN32_HAS_ANSI
35436   else{
35437     res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
35438   }
35439 #endif
35440   if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
35441     pFile->lastErrno = lastErrno;
35442     winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
35443                 "winUnlockReadLock", pFile->zPath);
35444   }
35445   OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
35446   return res;
35447 }
35448 
35449 /*
35450 ** Lock the file with the lock specified by parameter locktype - one
35451 ** of the following:
35452 **
35453 **     (1) SHARED_LOCK
35454 **     (2) RESERVED_LOCK
35455 **     (3) PENDING_LOCK
35456 **     (4) EXCLUSIVE_LOCK
35457 **
35458 ** Sometimes when requesting one lock state, additional lock states
35459 ** are inserted in between.  The locking might fail on one of the later
35460 ** transitions leaving the lock state different from what it started but
35461 ** still short of its goal.  The following chart shows the allowed
35462 ** transitions and the inserted intermediate states:
35463 **
35464 **    UNLOCKED -> SHARED
35465 **    SHARED -> RESERVED
35466 **    SHARED -> (PENDING) -> EXCLUSIVE
35467 **    RESERVED -> (PENDING) -> EXCLUSIVE
35468 **    PENDING -> EXCLUSIVE
35469 **
35470 ** This routine will only increase a lock.  The winUnlock() routine
35471 ** erases all locks at once and returns us immediately to locking level 0.
35472 ** It is not possible to lower the locking level one step at a time.  You
35473 ** must go straight to locking level 0.
35474 */
35475 static int winLock(sqlite3_file *id, int locktype){
35476   int rc = SQLITE_OK;    /* Return code from subroutines */
35477   int res = 1;           /* Result of a Windows lock call */
35478   int newLocktype;       /* Set pFile->locktype to this value before exiting */
35479   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
35480   winFile *pFile = (winFile*)id;
35481   DWORD lastErrno = NO_ERROR;
35482 
35483   assert( id!=0 );
35484   OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
35485            pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
35486 
35487   /* If there is already a lock of this type or more restrictive on the
35488   ** OsFile, do nothing. Don't use the end_lock: exit path, as
35489   ** sqlite3OsEnterMutex() hasn't been called yet.
35490   */
35491   if( pFile->locktype>=locktype ){
35492     OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
35493     return SQLITE_OK;
35494   }
35495 
35496   /* Make sure the locking sequence is correct
35497   */
35498   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
35499   assert( locktype!=PENDING_LOCK );
35500   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
35501 
35502   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
35503   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
35504   ** the PENDING_LOCK byte is temporary.
35505   */
35506   newLocktype = pFile->locktype;
35507   if(   (pFile->locktype==NO_LOCK)
35508      || (   (locktype==EXCLUSIVE_LOCK)
35509          && (pFile->locktype==RESERVED_LOCK))
35510   ){
35511     int cnt = 3;
35512     while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
35513                                          PENDING_BYTE, 0, 1, 0))==0 ){
35514       /* Try 3 times to get the pending lock.  This is needed to work
35515       ** around problems caused by indexing and/or anti-virus software on
35516       ** Windows systems.
35517       ** If you are using this code as a model for alternative VFSes, do not
35518       ** copy this retry logic.  It is a hack intended for Windows only.
35519       */
35520       lastErrno = osGetLastError();
35521       OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
35522                pFile->h, cnt, res));
35523       if( lastErrno==ERROR_INVALID_HANDLE ){
35524         pFile->lastErrno = lastErrno;
35525         rc = SQLITE_IOERR_LOCK;
35526         OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
35527                  pFile->h, cnt, sqlite3ErrName(rc)));
35528         return rc;
35529       }
35530       if( cnt ) sqlite3_win32_sleep(1);
35531     }
35532     gotPendingLock = res;
35533     if( !res ){
35534       lastErrno = osGetLastError();
35535     }
35536   }
35537 
35538   /* Acquire a shared lock
35539   */
35540   if( locktype==SHARED_LOCK && res ){
35541     assert( pFile->locktype==NO_LOCK );
35542     res = winGetReadLock(pFile);
35543     if( res ){
35544       newLocktype = SHARED_LOCK;
35545     }else{
35546       lastErrno = osGetLastError();
35547     }
35548   }
35549 
35550   /* Acquire a RESERVED lock
35551   */
35552   if( locktype==RESERVED_LOCK && res ){
35553     assert( pFile->locktype==SHARED_LOCK );
35554     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
35555     if( res ){
35556       newLocktype = RESERVED_LOCK;
35557     }else{
35558       lastErrno = osGetLastError();
35559     }
35560   }
35561 
35562   /* Acquire a PENDING lock
35563   */
35564   if( locktype==EXCLUSIVE_LOCK && res ){
35565     newLocktype = PENDING_LOCK;
35566     gotPendingLock = 0;
35567   }
35568 
35569   /* Acquire an EXCLUSIVE lock
35570   */
35571   if( locktype==EXCLUSIVE_LOCK && res ){
35572     assert( pFile->locktype>=SHARED_LOCK );
35573     res = winUnlockReadLock(pFile);
35574     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
35575                       SHARED_SIZE, 0);
35576     if( res ){
35577       newLocktype = EXCLUSIVE_LOCK;
35578     }else{
35579       lastErrno = osGetLastError();
35580       winGetReadLock(pFile);
35581     }
35582   }
35583 
35584   /* If we are holding a PENDING lock that ought to be released, then
35585   ** release it now.
35586   */
35587   if( gotPendingLock && locktype==SHARED_LOCK ){
35588     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
35589   }
35590 
35591   /* Update the state of the lock has held in the file descriptor then
35592   ** return the appropriate result code.
35593   */
35594   if( res ){
35595     rc = SQLITE_OK;
35596   }else{
35597     pFile->lastErrno = lastErrno;
35598     rc = SQLITE_BUSY;
35599     OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
35600              pFile->h, locktype, newLocktype));
35601   }
35602   pFile->locktype = (u8)newLocktype;
35603   OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
35604            pFile->h, pFile->locktype, sqlite3ErrName(rc)));
35605   return rc;
35606 }
35607 
35608 /*
35609 ** This routine checks if there is a RESERVED lock held on the specified
35610 ** file by this or any other process. If such a lock is held, return
35611 ** non-zero, otherwise zero.
35612 */
35613 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
35614   int res;
35615   winFile *pFile = (winFile*)id;
35616 
35617   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
35618   OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
35619 
35620   assert( id!=0 );
35621   if( pFile->locktype>=RESERVED_LOCK ){
35622     res = 1;
35623     OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
35624   }else{
35625     res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
35626     if( res ){
35627       winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
35628     }
35629     res = !res;
35630     OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
35631   }
35632   *pResOut = res;
35633   OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
35634            pFile->h, pResOut, *pResOut));
35635   return SQLITE_OK;
35636 }
35637 
35638 /*
35639 ** Lower the locking level on file descriptor id to locktype.  locktype
35640 ** must be either NO_LOCK or SHARED_LOCK.
35641 **
35642 ** If the locking level of the file descriptor is already at or below
35643 ** the requested locking level, this routine is a no-op.
35644 **
35645 ** It is not possible for this routine to fail if the second argument
35646 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
35647 ** might return SQLITE_IOERR;
35648 */
35649 static int winUnlock(sqlite3_file *id, int locktype){
35650   int type;
35651   winFile *pFile = (winFile*)id;
35652   int rc = SQLITE_OK;
35653   assert( pFile!=0 );
35654   assert( locktype<=SHARED_LOCK );
35655   OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
35656            pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
35657   type = pFile->locktype;
35658   if( type>=EXCLUSIVE_LOCK ){
35659     winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
35660     if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
35661       /* This should never happen.  We should always be able to
35662       ** reacquire the read lock */
35663       rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
35664                        "winUnlock", pFile->zPath);
35665     }
35666   }
35667   if( type>=RESERVED_LOCK ){
35668     winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
35669   }
35670   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
35671     winUnlockReadLock(pFile);
35672   }
35673   if( type>=PENDING_LOCK ){
35674     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
35675   }
35676   pFile->locktype = (u8)locktype;
35677   OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
35678            pFile->h, pFile->locktype, sqlite3ErrName(rc)));
35679   return rc;
35680 }
35681 
35682 /*
35683 ** If *pArg is initially negative then this is a query.  Set *pArg to
35684 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
35685 **
35686 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
35687 */
35688 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
35689   if( *pArg<0 ){
35690     *pArg = (pFile->ctrlFlags & mask)!=0;
35691   }else if( (*pArg)==0 ){
35692     pFile->ctrlFlags &= ~mask;
35693   }else{
35694     pFile->ctrlFlags |= mask;
35695   }
35696 }
35697 
35698 /* Forward references to VFS helper methods used for temporary files */
35699 static int winGetTempname(sqlite3_vfs *, char **);
35700 static int winIsDir(const void *);
35701 static BOOL winIsDriveLetterAndColon(const char *);
35702 
35703 /*
35704 ** Control and query of the open file handle.
35705 */
35706 static int winFileControl(sqlite3_file *id, int op, void *pArg){
35707   winFile *pFile = (winFile*)id;
35708   OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
35709   switch( op ){
35710     case SQLITE_FCNTL_LOCKSTATE: {
35711       *(int*)pArg = pFile->locktype;
35712       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35713       return SQLITE_OK;
35714     }
35715     case SQLITE_LAST_ERRNO: {
35716       *(int*)pArg = (int)pFile->lastErrno;
35717       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35718       return SQLITE_OK;
35719     }
35720     case SQLITE_FCNTL_CHUNK_SIZE: {
35721       pFile->szChunk = *(int *)pArg;
35722       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35723       return SQLITE_OK;
35724     }
35725     case SQLITE_FCNTL_SIZE_HINT: {
35726       if( pFile->szChunk>0 ){
35727         sqlite3_int64 oldSz;
35728         int rc = winFileSize(id, &oldSz);
35729         if( rc==SQLITE_OK ){
35730           sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
35731           if( newSz>oldSz ){
35732             SimulateIOErrorBenign(1);
35733             rc = winTruncate(id, newSz);
35734             SimulateIOErrorBenign(0);
35735           }
35736         }
35737         OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
35738         return rc;
35739       }
35740       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35741       return SQLITE_OK;
35742     }
35743     case SQLITE_FCNTL_PERSIST_WAL: {
35744       winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
35745       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35746       return SQLITE_OK;
35747     }
35748     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
35749       winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
35750       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35751       return SQLITE_OK;
35752     }
35753     case SQLITE_FCNTL_VFSNAME: {
35754       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
35755       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35756       return SQLITE_OK;
35757     }
35758     case SQLITE_FCNTL_WIN32_AV_RETRY: {
35759       int *a = (int*)pArg;
35760       if( a[0]>0 ){
35761         winIoerrRetry = a[0];
35762       }else{
35763         a[0] = winIoerrRetry;
35764       }
35765       if( a[1]>0 ){
35766         winIoerrRetryDelay = a[1];
35767       }else{
35768         a[1] = winIoerrRetryDelay;
35769       }
35770       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
35771       return SQLITE_OK;
35772     }
35773 #ifdef SQLITE_TEST
35774     case SQLITE_FCNTL_WIN32_SET_HANDLE: {
35775       LPHANDLE phFile = (LPHANDLE)pArg;
35776       HANDLE hOldFile = pFile->h;
35777       pFile->h = *phFile;
35778       *phFile = hOldFile;
35779       OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
35780                hOldFile, pFile->h));
35781       return SQLITE_OK;
35782     }
35783 #endif
35784     case SQLITE_FCNTL_TEMPFILENAME: {
35785       char *zTFile = 0;
35786       int rc = winGetTempname(pFile->pVfs, &zTFile);
35787       if( rc==SQLITE_OK ){
35788         *(char**)pArg = zTFile;
35789       }
35790       OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
35791       return rc;
35792     }
35793 #if SQLITE_MAX_MMAP_SIZE>0
35794     case SQLITE_FCNTL_MMAP_SIZE: {
35795       i64 newLimit = *(i64*)pArg;
35796       int rc = SQLITE_OK;
35797       if( newLimit>sqlite3GlobalConfig.mxMmap ){
35798         newLimit = sqlite3GlobalConfig.mxMmap;
35799       }
35800       *(i64*)pArg = pFile->mmapSizeMax;
35801       if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
35802         pFile->mmapSizeMax = newLimit;
35803         if( pFile->mmapSize>0 ){
35804           winUnmapfile(pFile);
35805           rc = winMapfile(pFile, -1);
35806         }
35807       }
35808       OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
35809       return rc;
35810     }
35811 #endif
35812   }
35813   OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
35814   return SQLITE_NOTFOUND;
35815 }
35816 
35817 /*
35818 ** Return the sector size in bytes of the underlying block device for
35819 ** the specified file. This is almost always 512 bytes, but may be
35820 ** larger for some devices.
35821 **
35822 ** SQLite code assumes this function cannot fail. It also assumes that
35823 ** if two files are created in the same file-system directory (i.e.
35824 ** a database and its journal file) that the sector size will be the
35825 ** same for both.
35826 */
35827 static int winSectorSize(sqlite3_file *id){
35828   (void)id;
35829   return SQLITE_DEFAULT_SECTOR_SIZE;
35830 }
35831 
35832 /*
35833 ** Return a vector of device characteristics.
35834 */
35835 static int winDeviceCharacteristics(sqlite3_file *id){
35836   winFile *p = (winFile*)id;
35837   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
35838          ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
35839 }
35840 
35841 /*
35842 ** Windows will only let you create file view mappings
35843 ** on allocation size granularity boundaries.
35844 ** During sqlite3_os_init() we do a GetSystemInfo()
35845 ** to get the granularity size.
35846 */
35847 static SYSTEM_INFO winSysInfo;
35848 
35849 #ifndef SQLITE_OMIT_WAL
35850 
35851 /*
35852 ** Helper functions to obtain and relinquish the global mutex. The
35853 ** global mutex is used to protect the winLockInfo objects used by
35854 ** this file, all of which may be shared by multiple threads.
35855 **
35856 ** Function winShmMutexHeld() is used to assert() that the global mutex
35857 ** is held when required. This function is only used as part of assert()
35858 ** statements. e.g.
35859 **
35860 **   winShmEnterMutex()
35861 **     assert( winShmMutexHeld() );
35862 **   winShmLeaveMutex()
35863 */
35864 static void winShmEnterMutex(void){
35865   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
35866 }
35867 static void winShmLeaveMutex(void){
35868   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
35869 }
35870 #ifndef NDEBUG
35871 static int winShmMutexHeld(void) {
35872   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
35873 }
35874 #endif
35875 
35876 /*
35877 ** Object used to represent a single file opened and mmapped to provide
35878 ** shared memory.  When multiple threads all reference the same
35879 ** log-summary, each thread has its own winFile object, but they all
35880 ** point to a single instance of this object.  In other words, each
35881 ** log-summary is opened only once per process.
35882 **
35883 ** winShmMutexHeld() must be true when creating or destroying
35884 ** this object or while reading or writing the following fields:
35885 **
35886 **      nRef
35887 **      pNext
35888 **
35889 ** The following fields are read-only after the object is created:
35890 **
35891 **      fid
35892 **      zFilename
35893 **
35894 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
35895 ** winShmMutexHeld() is true when reading or writing any other field
35896 ** in this structure.
35897 **
35898 */
35899 struct winShmNode {
35900   sqlite3_mutex *mutex;      /* Mutex to access this object */
35901   char *zFilename;           /* Name of the file */
35902   winFile hFile;             /* File handle from winOpen */
35903 
35904   int szRegion;              /* Size of shared-memory regions */
35905   int nRegion;               /* Size of array apRegion */
35906   struct ShmRegion {
35907     HANDLE hMap;             /* File handle from CreateFileMapping */
35908     void *pMap;
35909   } *aRegion;
35910   DWORD lastErrno;           /* The Windows errno from the last I/O error */
35911 
35912   int nRef;                  /* Number of winShm objects pointing to this */
35913   winShm *pFirst;            /* All winShm objects pointing to this */
35914   winShmNode *pNext;         /* Next in list of all winShmNode objects */
35915 #ifdef SQLITE_DEBUG
35916   u8 nextShmId;              /* Next available winShm.id value */
35917 #endif
35918 };
35919 
35920 /*
35921 ** A global array of all winShmNode objects.
35922 **
35923 ** The winShmMutexHeld() must be true while reading or writing this list.
35924 */
35925 static winShmNode *winShmNodeList = 0;
35926 
35927 /*
35928 ** Structure used internally by this VFS to record the state of an
35929 ** open shared memory connection.
35930 **
35931 ** The following fields are initialized when this object is created and
35932 ** are read-only thereafter:
35933 **
35934 **    winShm.pShmNode
35935 **    winShm.id
35936 **
35937 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
35938 ** while accessing any read/write fields.
35939 */
35940 struct winShm {
35941   winShmNode *pShmNode;      /* The underlying winShmNode object */
35942   winShm *pNext;             /* Next winShm with the same winShmNode */
35943   u8 hasMutex;               /* True if holding the winShmNode mutex */
35944   u16 sharedMask;            /* Mask of shared locks held */
35945   u16 exclMask;              /* Mask of exclusive locks held */
35946 #ifdef SQLITE_DEBUG
35947   u8 id;                     /* Id of this connection with its winShmNode */
35948 #endif
35949 };
35950 
35951 /*
35952 ** Constants used for locking
35953 */
35954 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
35955 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
35956 
35957 /*
35958 ** Apply advisory locks for all n bytes beginning at ofst.
35959 */
35960 #define _SHM_UNLCK  1
35961 #define _SHM_RDLCK  2
35962 #define _SHM_WRLCK  3
35963 static int winShmSystemLock(
35964   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
35965   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
35966   int ofst,             /* Offset to first byte to be locked/unlocked */
35967   int nByte             /* Number of bytes to lock or unlock */
35968 ){
35969   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
35970 
35971   /* Access to the winShmNode object is serialized by the caller */
35972   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
35973 
35974   OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
35975            pFile->hFile.h, lockType, ofst, nByte));
35976 
35977   /* Release/Acquire the system-level lock */
35978   if( lockType==_SHM_UNLCK ){
35979     rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
35980   }else{
35981     /* Initialize the locking parameters */
35982     DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
35983     if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
35984     rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
35985   }
35986 
35987   if( rc!= 0 ){
35988     rc = SQLITE_OK;
35989   }else{
35990     pFile->lastErrno =  osGetLastError();
35991     rc = SQLITE_BUSY;
35992   }
35993 
35994   OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
35995            pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
35996            "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
35997 
35998   return rc;
35999 }
36000 
36001 /* Forward references to VFS methods */
36002 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
36003 static int winDelete(sqlite3_vfs *,const char*,int);
36004 
36005 /*
36006 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
36007 **
36008 ** This is not a VFS shared-memory method; it is a utility function called
36009 ** by VFS shared-memory methods.
36010 */
36011 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
36012   winShmNode **pp;
36013   winShmNode *p;
36014   assert( winShmMutexHeld() );
36015   OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
36016            osGetCurrentProcessId(), deleteFlag));
36017   pp = &winShmNodeList;
36018   while( (p = *pp)!=0 ){
36019     if( p->nRef==0 ){
36020       int i;
36021       if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
36022       for(i=0; i<p->nRegion; i++){
36023         BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
36024         OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
36025                  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
36026         UNUSED_VARIABLE_VALUE(bRc);
36027         bRc = osCloseHandle(p->aRegion[i].hMap);
36028         OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
36029                  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
36030         UNUSED_VARIABLE_VALUE(bRc);
36031       }
36032       if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
36033         SimulateIOErrorBenign(1);
36034         winClose((sqlite3_file *)&p->hFile);
36035         SimulateIOErrorBenign(0);
36036       }
36037       if( deleteFlag ){
36038         SimulateIOErrorBenign(1);
36039         sqlite3BeginBenignMalloc();
36040         winDelete(pVfs, p->zFilename, 0);
36041         sqlite3EndBenignMalloc();
36042         SimulateIOErrorBenign(0);
36043       }
36044       *pp = p->pNext;
36045       sqlite3_free(p->aRegion);
36046       sqlite3_free(p);
36047     }else{
36048       pp = &p->pNext;
36049     }
36050   }
36051 }
36052 
36053 /*
36054 ** Open the shared-memory area associated with database file pDbFd.
36055 **
36056 ** When opening a new shared-memory file, if no other instances of that
36057 ** file are currently open, in this process or in other processes, then
36058 ** the file must be truncated to zero length or have its header cleared.
36059 */
36060 static int winOpenSharedMemory(winFile *pDbFd){
36061   struct winShm *p;                  /* The connection to be opened */
36062   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
36063   int rc;                            /* Result code */
36064   struct winShmNode *pNew;           /* Newly allocated winShmNode */
36065   int nName;                         /* Size of zName in bytes */
36066 
36067   assert( pDbFd->pShm==0 );    /* Not previously opened */
36068 
36069   /* Allocate space for the new sqlite3_shm object.  Also speculatively
36070   ** allocate space for a new winShmNode and filename.
36071   */
36072   p = sqlite3MallocZero( sizeof(*p) );
36073   if( p==0 ) return SQLITE_IOERR_NOMEM;
36074   nName = sqlite3Strlen30(pDbFd->zPath);
36075   pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
36076   if( pNew==0 ){
36077     sqlite3_free(p);
36078     return SQLITE_IOERR_NOMEM;
36079   }
36080   pNew->zFilename = (char*)&pNew[1];
36081   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
36082   sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
36083 
36084   /* Look to see if there is an existing winShmNode that can be used.
36085   ** If no matching winShmNode currently exists, create a new one.
36086   */
36087   winShmEnterMutex();
36088   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
36089     /* TBD need to come up with better match here.  Perhaps
36090     ** use FILE_ID_BOTH_DIR_INFO Structure.
36091     */
36092     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
36093   }
36094   if( pShmNode ){
36095     sqlite3_free(pNew);
36096   }else{
36097     pShmNode = pNew;
36098     pNew = 0;
36099     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
36100     pShmNode->pNext = winShmNodeList;
36101     winShmNodeList = pShmNode;
36102 
36103     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
36104     if( pShmNode->mutex==0 ){
36105       rc = SQLITE_IOERR_NOMEM;
36106       goto shm_open_err;
36107     }
36108 
36109     rc = winOpen(pDbFd->pVfs,
36110                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
36111                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
36112                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
36113                  0);
36114     if( SQLITE_OK!=rc ){
36115       goto shm_open_err;
36116     }
36117 
36118     /* Check to see if another process is holding the dead-man switch.
36119     ** If not, truncate the file to zero length.
36120     */
36121     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
36122       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
36123       if( rc!=SQLITE_OK ){
36124         rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
36125                          "winOpenShm", pDbFd->zPath);
36126       }
36127     }
36128     if( rc==SQLITE_OK ){
36129       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
36130       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
36131     }
36132     if( rc ) goto shm_open_err;
36133   }
36134 
36135   /* Make the new connection a child of the winShmNode */
36136   p->pShmNode = pShmNode;
36137 #ifdef SQLITE_DEBUG
36138   p->id = pShmNode->nextShmId++;
36139 #endif
36140   pShmNode->nRef++;
36141   pDbFd->pShm = p;
36142   winShmLeaveMutex();
36143 
36144   /* The reference count on pShmNode has already been incremented under
36145   ** the cover of the winShmEnterMutex() mutex and the pointer from the
36146   ** new (struct winShm) object to the pShmNode has been set. All that is
36147   ** left to do is to link the new object into the linked list starting
36148   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
36149   ** mutex.
36150   */
36151   sqlite3_mutex_enter(pShmNode->mutex);
36152   p->pNext = pShmNode->pFirst;
36153   pShmNode->pFirst = p;
36154   sqlite3_mutex_leave(pShmNode->mutex);
36155   return SQLITE_OK;
36156 
36157   /* Jump here on any error */
36158 shm_open_err:
36159   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
36160   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
36161   sqlite3_free(p);
36162   sqlite3_free(pNew);
36163   winShmLeaveMutex();
36164   return rc;
36165 }
36166 
36167 /*
36168 ** Close a connection to shared-memory.  Delete the underlying
36169 ** storage if deleteFlag is true.
36170 */
36171 static int winShmUnmap(
36172   sqlite3_file *fd,          /* Database holding shared memory */
36173   int deleteFlag             /* Delete after closing if true */
36174 ){
36175   winFile *pDbFd;       /* Database holding shared-memory */
36176   winShm *p;            /* The connection to be closed */
36177   winShmNode *pShmNode; /* The underlying shared-memory file */
36178   winShm **pp;          /* For looping over sibling connections */
36179 
36180   pDbFd = (winFile*)fd;
36181   p = pDbFd->pShm;
36182   if( p==0 ) return SQLITE_OK;
36183   pShmNode = p->pShmNode;
36184 
36185   /* Remove connection p from the set of connections associated
36186   ** with pShmNode */
36187   sqlite3_mutex_enter(pShmNode->mutex);
36188   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
36189   *pp = p->pNext;
36190 
36191   /* Free the connection p */
36192   sqlite3_free(p);
36193   pDbFd->pShm = 0;
36194   sqlite3_mutex_leave(pShmNode->mutex);
36195 
36196   /* If pShmNode->nRef has reached 0, then close the underlying
36197   ** shared-memory file, too */
36198   winShmEnterMutex();
36199   assert( pShmNode->nRef>0 );
36200   pShmNode->nRef--;
36201   if( pShmNode->nRef==0 ){
36202     winShmPurge(pDbFd->pVfs, deleteFlag);
36203   }
36204   winShmLeaveMutex();
36205 
36206   return SQLITE_OK;
36207 }
36208 
36209 /*
36210 ** Change the lock state for a shared-memory segment.
36211 */
36212 static int winShmLock(
36213   sqlite3_file *fd,          /* Database file holding the shared memory */
36214   int ofst,                  /* First lock to acquire or release */
36215   int n,                     /* Number of locks to acquire or release */
36216   int flags                  /* What to do with the lock */
36217 ){
36218   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
36219   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
36220   winShm *pX;                           /* For looping over all siblings */
36221   winShmNode *pShmNode = p->pShmNode;
36222   int rc = SQLITE_OK;                   /* Result code */
36223   u16 mask;                             /* Mask of locks to take or release */
36224 
36225   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
36226   assert( n>=1 );
36227   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
36228        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
36229        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
36230        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
36231   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
36232 
36233   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
36234   assert( n>1 || mask==(1<<ofst) );
36235   sqlite3_mutex_enter(pShmNode->mutex);
36236   if( flags & SQLITE_SHM_UNLOCK ){
36237     u16 allMask = 0; /* Mask of locks held by siblings */
36238 
36239     /* See if any siblings hold this same lock */
36240     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
36241       if( pX==p ) continue;
36242       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
36243       allMask |= pX->sharedMask;
36244     }
36245 
36246     /* Unlock the system-level locks */
36247     if( (mask & allMask)==0 ){
36248       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
36249     }else{
36250       rc = SQLITE_OK;
36251     }
36252 
36253     /* Undo the local locks */
36254     if( rc==SQLITE_OK ){
36255       p->exclMask &= ~mask;
36256       p->sharedMask &= ~mask;
36257     }
36258   }else if( flags & SQLITE_SHM_SHARED ){
36259     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
36260 
36261     /* Find out which shared locks are already held by sibling connections.
36262     ** If any sibling already holds an exclusive lock, go ahead and return
36263     ** SQLITE_BUSY.
36264     */
36265     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
36266       if( (pX->exclMask & mask)!=0 ){
36267         rc = SQLITE_BUSY;
36268         break;
36269       }
36270       allShared |= pX->sharedMask;
36271     }
36272 
36273     /* Get shared locks at the system level, if necessary */
36274     if( rc==SQLITE_OK ){
36275       if( (allShared & mask)==0 ){
36276         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
36277       }else{
36278         rc = SQLITE_OK;
36279       }
36280     }
36281 
36282     /* Get the local shared locks */
36283     if( rc==SQLITE_OK ){
36284       p->sharedMask |= mask;
36285     }
36286   }else{
36287     /* Make sure no sibling connections hold locks that will block this
36288     ** lock.  If any do, return SQLITE_BUSY right away.
36289     */
36290     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
36291       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
36292         rc = SQLITE_BUSY;
36293         break;
36294       }
36295     }
36296 
36297     /* Get the exclusive locks at the system level.  Then if successful
36298     ** also mark the local connection as being locked.
36299     */
36300     if( rc==SQLITE_OK ){
36301       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
36302       if( rc==SQLITE_OK ){
36303         assert( (p->sharedMask & mask)==0 );
36304         p->exclMask |= mask;
36305       }
36306     }
36307   }
36308   sqlite3_mutex_leave(pShmNode->mutex);
36309   OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
36310            osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
36311            sqlite3ErrName(rc)));
36312   return rc;
36313 }
36314 
36315 /*
36316 ** Implement a memory barrier or memory fence on shared memory.
36317 **
36318 ** All loads and stores begun before the barrier must complete before
36319 ** any load or store begun after the barrier.
36320 */
36321 static void winShmBarrier(
36322   sqlite3_file *fd          /* Database holding the shared memory */
36323 ){
36324   UNUSED_PARAMETER(fd);
36325   /* MemoryBarrier(); // does not work -- do not know why not */
36326   winShmEnterMutex();
36327   winShmLeaveMutex();
36328 }
36329 
36330 /*
36331 ** This function is called to obtain a pointer to region iRegion of the
36332 ** shared-memory associated with the database file fd. Shared-memory regions
36333 ** are numbered starting from zero. Each shared-memory region is szRegion
36334 ** bytes in size.
36335 **
36336 ** If an error occurs, an error code is returned and *pp is set to NULL.
36337 **
36338 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
36339 ** region has not been allocated (by any client, including one running in a
36340 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
36341 ** isWrite is non-zero and the requested shared-memory region has not yet
36342 ** been allocated, it is allocated by this function.
36343 **
36344 ** If the shared-memory region has already been allocated or is allocated by
36345 ** this call as described above, then it is mapped into this processes
36346 ** address space (if it is not already), *pp is set to point to the mapped
36347 ** memory and SQLITE_OK returned.
36348 */
36349 static int winShmMap(
36350   sqlite3_file *fd,               /* Handle open on database file */
36351   int iRegion,                    /* Region to retrieve */
36352   int szRegion,                   /* Size of regions */
36353   int isWrite,                    /* True to extend file if necessary */
36354   void volatile **pp              /* OUT: Mapped memory */
36355 ){
36356   winFile *pDbFd = (winFile*)fd;
36357   winShm *p = pDbFd->pShm;
36358   winShmNode *pShmNode;
36359   int rc = SQLITE_OK;
36360 
36361   if( !p ){
36362     rc = winOpenSharedMemory(pDbFd);
36363     if( rc!=SQLITE_OK ) return rc;
36364     p = pDbFd->pShm;
36365   }
36366   pShmNode = p->pShmNode;
36367 
36368   sqlite3_mutex_enter(pShmNode->mutex);
36369   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
36370 
36371   if( pShmNode->nRegion<=iRegion ){
36372     struct ShmRegion *apNew;           /* New aRegion[] array */
36373     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
36374     sqlite3_int64 sz;                  /* Current size of wal-index file */
36375 
36376     pShmNode->szRegion = szRegion;
36377 
36378     /* The requested region is not mapped into this processes address space.
36379     ** Check to see if it has been allocated (i.e. if the wal-index file is
36380     ** large enough to contain the requested region).
36381     */
36382     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
36383     if( rc!=SQLITE_OK ){
36384       rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
36385                        "winShmMap1", pDbFd->zPath);
36386       goto shmpage_out;
36387     }
36388 
36389     if( sz<nByte ){
36390       /* The requested memory region does not exist. If isWrite is set to
36391       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
36392       **
36393       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
36394       ** the requested memory region.
36395       */
36396       if( !isWrite ) goto shmpage_out;
36397       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
36398       if( rc!=SQLITE_OK ){
36399         rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
36400                          "winShmMap2", pDbFd->zPath);
36401         goto shmpage_out;
36402       }
36403     }
36404 
36405     /* Map the requested memory region into this processes address space. */
36406     apNew = (struct ShmRegion *)sqlite3_realloc(
36407         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
36408     );
36409     if( !apNew ){
36410       rc = SQLITE_IOERR_NOMEM;
36411       goto shmpage_out;
36412     }
36413     pShmNode->aRegion = apNew;
36414 
36415     while( pShmNode->nRegion<=iRegion ){
36416       HANDLE hMap = NULL;         /* file-mapping handle */
36417       void *pMap = 0;             /* Mapped memory region */
36418 
36419 #if SQLITE_OS_WINRT
36420       hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
36421           NULL, PAGE_READWRITE, nByte, NULL
36422       );
36423 #elif defined(SQLITE_WIN32_HAS_WIDE)
36424       hMap = osCreateFileMappingW(pShmNode->hFile.h,
36425           NULL, PAGE_READWRITE, 0, nByte, NULL
36426       );
36427 #elif defined(SQLITE_WIN32_HAS_ANSI)
36428       hMap = osCreateFileMappingA(pShmNode->hFile.h,
36429           NULL, PAGE_READWRITE, 0, nByte, NULL
36430       );
36431 #endif
36432       OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
36433                osGetCurrentProcessId(), pShmNode->nRegion, nByte,
36434                hMap ? "ok" : "failed"));
36435       if( hMap ){
36436         int iOffset = pShmNode->nRegion*szRegion;
36437         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
36438 #if SQLITE_OS_WINRT
36439         pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
36440             iOffset - iOffsetShift, szRegion + iOffsetShift
36441         );
36442 #else
36443         pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
36444             0, iOffset - iOffsetShift, szRegion + iOffsetShift
36445         );
36446 #endif
36447         OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
36448                  osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
36449                  szRegion, pMap ? "ok" : "failed"));
36450       }
36451       if( !pMap ){
36452         pShmNode->lastErrno = osGetLastError();
36453         rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
36454                          "winShmMap3", pDbFd->zPath);
36455         if( hMap ) osCloseHandle(hMap);
36456         goto shmpage_out;
36457       }
36458 
36459       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
36460       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
36461       pShmNode->nRegion++;
36462     }
36463   }
36464 
36465 shmpage_out:
36466   if( pShmNode->nRegion>iRegion ){
36467     int iOffset = iRegion*szRegion;
36468     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
36469     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
36470     *pp = (void *)&p[iOffsetShift];
36471   }else{
36472     *pp = 0;
36473   }
36474   sqlite3_mutex_leave(pShmNode->mutex);
36475   return rc;
36476 }
36477 
36478 #else
36479 # define winShmMap     0
36480 # define winShmLock    0
36481 # define winShmBarrier 0
36482 # define winShmUnmap   0
36483 #endif /* #ifndef SQLITE_OMIT_WAL */
36484 
36485 /*
36486 ** Cleans up the mapped region of the specified file, if any.
36487 */
36488 #if SQLITE_MAX_MMAP_SIZE>0
36489 static int winUnmapfile(winFile *pFile){
36490   assert( pFile!=0 );
36491   OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
36492            "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
36493            osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
36494            pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
36495   if( pFile->pMapRegion ){
36496     if( !osUnmapViewOfFile(pFile->pMapRegion) ){
36497       pFile->lastErrno = osGetLastError();
36498       OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
36499                "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
36500                pFile->pMapRegion));
36501       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
36502                          "winUnmapfile1", pFile->zPath);
36503     }
36504     pFile->pMapRegion = 0;
36505     pFile->mmapSize = 0;
36506     pFile->mmapSizeActual = 0;
36507   }
36508   if( pFile->hMap!=NULL ){
36509     if( !osCloseHandle(pFile->hMap) ){
36510       pFile->lastErrno = osGetLastError();
36511       OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
36512                osGetCurrentProcessId(), pFile, pFile->hMap));
36513       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
36514                          "winUnmapfile2", pFile->zPath);
36515     }
36516     pFile->hMap = NULL;
36517   }
36518   OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
36519            osGetCurrentProcessId(), pFile));
36520   return SQLITE_OK;
36521 }
36522 
36523 /*
36524 ** Memory map or remap the file opened by file-descriptor pFd (if the file
36525 ** is already mapped, the existing mapping is replaced by the new). Or, if
36526 ** there already exists a mapping for this file, and there are still
36527 ** outstanding xFetch() references to it, this function is a no-op.
36528 **
36529 ** If parameter nByte is non-negative, then it is the requested size of
36530 ** the mapping to create. Otherwise, if nByte is less than zero, then the
36531 ** requested size is the size of the file on disk. The actual size of the
36532 ** created mapping is either the requested size or the value configured
36533 ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
36534 **
36535 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
36536 ** recreated as a result of outstanding references) or an SQLite error
36537 ** code otherwise.
36538 */
36539 static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
36540   sqlite3_int64 nMap = nByte;
36541   int rc;
36542 
36543   assert( nMap>=0 || pFd->nFetchOut==0 );
36544   OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
36545            osGetCurrentProcessId(), pFd, nByte));
36546 
36547   if( pFd->nFetchOut>0 ) return SQLITE_OK;
36548 
36549   if( nMap<0 ){
36550     rc = winFileSize((sqlite3_file*)pFd, &nMap);
36551     if( rc ){
36552       OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
36553                osGetCurrentProcessId(), pFd));
36554       return SQLITE_IOERR_FSTAT;
36555     }
36556   }
36557   if( nMap>pFd->mmapSizeMax ){
36558     nMap = pFd->mmapSizeMax;
36559   }
36560   nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
36561 
36562   if( nMap==0 && pFd->mmapSize>0 ){
36563     winUnmapfile(pFd);
36564   }
36565   if( nMap!=pFd->mmapSize ){
36566     void *pNew = 0;
36567     DWORD protect = PAGE_READONLY;
36568     DWORD flags = FILE_MAP_READ;
36569 
36570     winUnmapfile(pFd);
36571     if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
36572       protect = PAGE_READWRITE;
36573       flags |= FILE_MAP_WRITE;
36574     }
36575 #if SQLITE_OS_WINRT
36576     pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
36577 #elif defined(SQLITE_WIN32_HAS_WIDE)
36578     pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
36579                                 (DWORD)((nMap>>32) & 0xffffffff),
36580                                 (DWORD)(nMap & 0xffffffff), NULL);
36581 #elif defined(SQLITE_WIN32_HAS_ANSI)
36582     pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
36583                                 (DWORD)((nMap>>32) & 0xffffffff),
36584                                 (DWORD)(nMap & 0xffffffff), NULL);
36585 #endif
36586     if( pFd->hMap==NULL ){
36587       pFd->lastErrno = osGetLastError();
36588       rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
36589                        "winMapfile1", pFd->zPath);
36590       /* Log the error, but continue normal operation using xRead/xWrite */
36591       OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
36592                osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
36593       return SQLITE_OK;
36594     }
36595     assert( (nMap % winSysInfo.dwPageSize)==0 );
36596     assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
36597 #if SQLITE_OS_WINRT
36598     pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
36599 #else
36600     pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
36601 #endif
36602     if( pNew==NULL ){
36603       osCloseHandle(pFd->hMap);
36604       pFd->hMap = NULL;
36605       pFd->lastErrno = osGetLastError();
36606       rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
36607                        "winMapfile2", pFd->zPath);
36608       /* Log the error, but continue normal operation using xRead/xWrite */
36609       OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
36610                osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
36611       return SQLITE_OK;
36612     }
36613     pFd->pMapRegion = pNew;
36614     pFd->mmapSize = nMap;
36615     pFd->mmapSizeActual = nMap;
36616   }
36617 
36618   OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
36619            osGetCurrentProcessId(), pFd));
36620   return SQLITE_OK;
36621 }
36622 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
36623 
36624 /*
36625 ** If possible, return a pointer to a mapping of file fd starting at offset
36626 ** iOff. The mapping must be valid for at least nAmt bytes.
36627 **
36628 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
36629 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
36630 ** Finally, if an error does occur, return an SQLite error code. The final
36631 ** value of *pp is undefined in this case.
36632 **
36633 ** If this function does return a pointer, the caller must eventually
36634 ** release the reference by calling winUnfetch().
36635 */
36636 static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
36637 #if SQLITE_MAX_MMAP_SIZE>0
36638   winFile *pFd = (winFile*)fd;   /* The underlying database file */
36639 #endif
36640   *pp = 0;
36641 
36642   OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
36643            osGetCurrentProcessId(), fd, iOff, nAmt, pp));
36644 
36645 #if SQLITE_MAX_MMAP_SIZE>0
36646   if( pFd->mmapSizeMax>0 ){
36647     if( pFd->pMapRegion==0 ){
36648       int rc = winMapfile(pFd, -1);
36649       if( rc!=SQLITE_OK ){
36650         OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
36651                  osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
36652         return rc;
36653       }
36654     }
36655     if( pFd->mmapSize >= iOff+nAmt ){
36656       *pp = &((u8 *)pFd->pMapRegion)[iOff];
36657       pFd->nFetchOut++;
36658     }
36659   }
36660 #endif
36661 
36662   OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
36663            osGetCurrentProcessId(), fd, pp, *pp));
36664   return SQLITE_OK;
36665 }
36666 
36667 /*
36668 ** If the third argument is non-NULL, then this function releases a
36669 ** reference obtained by an earlier call to winFetch(). The second
36670 ** argument passed to this function must be the same as the corresponding
36671 ** argument that was passed to the winFetch() invocation.
36672 **
36673 ** Or, if the third argument is NULL, then this function is being called
36674 ** to inform the VFS layer that, according to POSIX, any existing mapping
36675 ** may now be invalid and should be unmapped.
36676 */
36677 static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
36678 #if SQLITE_MAX_MMAP_SIZE>0
36679   winFile *pFd = (winFile*)fd;   /* The underlying database file */
36680 
36681   /* If p==0 (unmap the entire file) then there must be no outstanding
36682   ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
36683   ** then there must be at least one outstanding.  */
36684   assert( (p==0)==(pFd->nFetchOut==0) );
36685 
36686   /* If p!=0, it must match the iOff value. */
36687   assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
36688 
36689   OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
36690            osGetCurrentProcessId(), pFd, iOff, p));
36691 
36692   if( p ){
36693     pFd->nFetchOut--;
36694   }else{
36695     /* FIXME:  If Windows truly always prevents truncating or deleting a
36696     ** file while a mapping is held, then the following winUnmapfile() call
36697     ** is unnecessary can be omitted - potentially improving
36698     ** performance.  */
36699     winUnmapfile(pFd);
36700   }
36701 
36702   assert( pFd->nFetchOut>=0 );
36703 #endif
36704 
36705   OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
36706            osGetCurrentProcessId(), fd));
36707   return SQLITE_OK;
36708 }
36709 
36710 /*
36711 ** Here ends the implementation of all sqlite3_file methods.
36712 **
36713 ********************** End sqlite3_file Methods *******************************
36714 ******************************************************************************/
36715 
36716 /*
36717 ** This vector defines all the methods that can operate on an
36718 ** sqlite3_file for win32.
36719 */
36720 static const sqlite3_io_methods winIoMethod = {
36721   3,                              /* iVersion */
36722   winClose,                       /* xClose */
36723   winRead,                        /* xRead */
36724   winWrite,                       /* xWrite */
36725   winTruncate,                    /* xTruncate */
36726   winSync,                        /* xSync */
36727   winFileSize,                    /* xFileSize */
36728   winLock,                        /* xLock */
36729   winUnlock,                      /* xUnlock */
36730   winCheckReservedLock,           /* xCheckReservedLock */
36731   winFileControl,                 /* xFileControl */
36732   winSectorSize,                  /* xSectorSize */
36733   winDeviceCharacteristics,       /* xDeviceCharacteristics */
36734   winShmMap,                      /* xShmMap */
36735   winShmLock,                     /* xShmLock */
36736   winShmBarrier,                  /* xShmBarrier */
36737   winShmUnmap,                    /* xShmUnmap */
36738   winFetch,                       /* xFetch */
36739   winUnfetch                      /* xUnfetch */
36740 };
36741 
36742 /****************************************************************************
36743 **************************** sqlite3_vfs methods ****************************
36744 **
36745 ** This division contains the implementation of methods on the
36746 ** sqlite3_vfs object.
36747 */
36748 
36749 #if defined(__CYGWIN__)
36750 /*
36751 ** Convert a filename from whatever the underlying operating system
36752 ** supports for filenames into UTF-8.  Space to hold the result is
36753 ** obtained from malloc and must be freed by the calling function.
36754 */
36755 static char *winConvertToUtf8Filename(const void *zFilename){
36756   char *zConverted = 0;
36757   if( osIsNT() ){
36758     zConverted = winUnicodeToUtf8(zFilename);
36759   }
36760 #ifdef SQLITE_WIN32_HAS_ANSI
36761   else{
36762     zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
36763   }
36764 #endif
36765   /* caller will handle out of memory */
36766   return zConverted;
36767 }
36768 #endif
36769 
36770 /*
36771 ** Convert a UTF-8 filename into whatever form the underlying
36772 ** operating system wants filenames in.  Space to hold the result
36773 ** is obtained from malloc and must be freed by the calling
36774 ** function.
36775 */
36776 static void *winConvertFromUtf8Filename(const char *zFilename){
36777   void *zConverted = 0;
36778   if( osIsNT() ){
36779     zConverted = winUtf8ToUnicode(zFilename);
36780   }
36781 #ifdef SQLITE_WIN32_HAS_ANSI
36782   else{
36783     zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
36784   }
36785 #endif
36786   /* caller will handle out of memory */
36787   return zConverted;
36788 }
36789 
36790 /*
36791 ** This function returns non-zero if the specified UTF-8 string buffer
36792 ** ends with a directory separator character or one was successfully
36793 ** added to it.
36794 */
36795 static int winMakeEndInDirSep(int nBuf, char *zBuf){
36796   if( zBuf ){
36797     int nLen = sqlite3Strlen30(zBuf);
36798     if( nLen>0 ){
36799       if( winIsDirSep(zBuf[nLen-1]) ){
36800         return 1;
36801       }else if( nLen+1<nBuf ){
36802         zBuf[nLen] = winGetDirSep();
36803         zBuf[nLen+1] = '\0';
36804         return 1;
36805       }
36806     }
36807   }
36808   return 0;
36809 }
36810 
36811 /*
36812 ** Create a temporary file name and store the resulting pointer into pzBuf.
36813 ** The pointer returned in pzBuf must be freed via sqlite3_free().
36814 */
36815 static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
36816   static char zChars[] =
36817     "abcdefghijklmnopqrstuvwxyz"
36818     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
36819     "0123456789";
36820   size_t i, j;
36821   int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
36822   int nMax, nBuf, nDir, nLen;
36823   char *zBuf;
36824 
36825   /* It's odd to simulate an io-error here, but really this is just
36826   ** using the io-error infrastructure to test that SQLite handles this
36827   ** function failing.
36828   */
36829   SimulateIOError( return SQLITE_IOERR );
36830 
36831   /* Allocate a temporary buffer to store the fully qualified file
36832   ** name for the temporary file.  If this fails, we cannot continue.
36833   */
36834   nMax = pVfs->mxPathname; nBuf = nMax + 2;
36835   zBuf = sqlite3MallocZero( nBuf );
36836   if( !zBuf ){
36837     OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
36838     return SQLITE_IOERR_NOMEM;
36839   }
36840 
36841   /* Figure out the effective temporary directory.  First, check if one
36842   ** has been explicitly set by the application; otherwise, use the one
36843   ** configured by the operating system.
36844   */
36845   nDir = nMax - (nPre + 15);
36846   assert( nDir>0 );
36847   if( sqlite3_temp_directory ){
36848     int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
36849     if( nDirLen>0 ){
36850       if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
36851         nDirLen++;
36852       }
36853       if( nDirLen>nDir ){
36854         sqlite3_free(zBuf);
36855         OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
36856         return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
36857       }
36858       sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
36859     }
36860   }
36861 #if defined(__CYGWIN__)
36862   else{
36863     static const char *azDirs[] = {
36864        0, /* getenv("SQLITE_TMPDIR") */
36865        0, /* getenv("TMPDIR") */
36866        0, /* getenv("TMP") */
36867        0, /* getenv("TEMP") */
36868        0, /* getenv("USERPROFILE") */
36869        "/var/tmp",
36870        "/usr/tmp",
36871        "/tmp",
36872        ".",
36873        0        /* List terminator */
36874     };
36875     unsigned int i;
36876     const char *zDir = 0;
36877 
36878     if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
36879     if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
36880     if( !azDirs[2] ) azDirs[2] = getenv("TMP");
36881     if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
36882     if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
36883     for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
36884       void *zConverted;
36885       if( zDir==0 ) continue;
36886       /* If the path starts with a drive letter followed by the colon
36887       ** character, assume it is already a native Win32 path; otherwise,
36888       ** it must be converted to a native Win32 path via the Cygwin API
36889       ** prior to using it.
36890       */
36891       if( winIsDriveLetterAndColon(zDir) ){
36892         zConverted = winConvertFromUtf8Filename(zDir);
36893         if( !zConverted ){
36894           sqlite3_free(zBuf);
36895           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
36896           return SQLITE_IOERR_NOMEM;
36897         }
36898         if( winIsDir(zConverted) ){
36899           sqlite3_snprintf(nMax, zBuf, "%s", zDir);
36900           sqlite3_free(zConverted);
36901           break;
36902         }
36903         sqlite3_free(zConverted);
36904       }else{
36905         zConverted = sqlite3MallocZero( nMax+1 );
36906         if( !zConverted ){
36907           sqlite3_free(zBuf);
36908           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
36909           return SQLITE_IOERR_NOMEM;
36910         }
36911         if( cygwin_conv_path(
36912                 osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
36913                 zConverted, nMax+1)<0 ){
36914           sqlite3_free(zConverted);
36915           sqlite3_free(zBuf);
36916           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
36917           return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
36918                              "winGetTempname2", zDir);
36919         }
36920         if( winIsDir(zConverted) ){
36921           /* At this point, we know the candidate directory exists and should
36922           ** be used.  However, we may need to convert the string containing
36923           ** its name into UTF-8 (i.e. if it is UTF-16 right now).
36924           */
36925           char *zUtf8 = winConvertToUtf8Filename(zConverted);
36926           if( !zUtf8 ){
36927             sqlite3_free(zConverted);
36928             sqlite3_free(zBuf);
36929             OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
36930             return SQLITE_IOERR_NOMEM;
36931           }
36932           sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
36933           sqlite3_free(zUtf8);
36934           sqlite3_free(zConverted);
36935           break;
36936         }
36937         sqlite3_free(zConverted);
36938       }
36939     }
36940   }
36941 #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
36942   else if( osIsNT() ){
36943     char *zMulti;
36944     LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
36945     if( !zWidePath ){
36946       sqlite3_free(zBuf);
36947       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
36948       return SQLITE_IOERR_NOMEM;
36949     }
36950     if( osGetTempPathW(nMax, zWidePath)==0 ){
36951       sqlite3_free(zWidePath);
36952       sqlite3_free(zBuf);
36953       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
36954       return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
36955                          "winGetTempname2", 0);
36956     }
36957     zMulti = winUnicodeToUtf8(zWidePath);
36958     if( zMulti ){
36959       sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
36960       sqlite3_free(zMulti);
36961       sqlite3_free(zWidePath);
36962     }else{
36963       sqlite3_free(zWidePath);
36964       sqlite3_free(zBuf);
36965       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
36966       return SQLITE_IOERR_NOMEM;
36967     }
36968   }
36969 #ifdef SQLITE_WIN32_HAS_ANSI
36970   else{
36971     char *zUtf8;
36972     char *zMbcsPath = sqlite3MallocZero( nMax );
36973     if( !zMbcsPath ){
36974       sqlite3_free(zBuf);
36975       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
36976       return SQLITE_IOERR_NOMEM;
36977     }
36978     if( osGetTempPathA(nMax, zMbcsPath)==0 ){
36979       sqlite3_free(zBuf);
36980       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
36981       return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
36982                          "winGetTempname3", 0);
36983     }
36984     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
36985     if( zUtf8 ){
36986       sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
36987       sqlite3_free(zUtf8);
36988     }else{
36989       sqlite3_free(zBuf);
36990       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
36991       return SQLITE_IOERR_NOMEM;
36992     }
36993   }
36994 #endif /* SQLITE_WIN32_HAS_ANSI */
36995 #endif /* !SQLITE_OS_WINRT */
36996 
36997   /*
36998   ** Check to make sure the temporary directory ends with an appropriate
36999   ** separator.  If it does not and there is not enough space left to add
37000   ** one, fail.
37001   */
37002   if( !winMakeEndInDirSep(nDir+1, zBuf) ){
37003     sqlite3_free(zBuf);
37004     OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
37005     return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
37006   }
37007 
37008   /*
37009   ** Check that the output buffer is large enough for the temporary file
37010   ** name in the following format:
37011   **
37012   **   "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
37013   **
37014   ** If not, return SQLITE_ERROR.  The number 17 is used here in order to
37015   ** account for the space used by the 15 character random suffix and the
37016   ** two trailing NUL characters.  The final directory separator character
37017   ** has already added if it was not already present.
37018   */
37019   nLen = sqlite3Strlen30(zBuf);
37020   if( (nLen + nPre + 17) > nBuf ){
37021     sqlite3_free(zBuf);
37022     OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
37023     return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
37024   }
37025 
37026   sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
37027 
37028   j = sqlite3Strlen30(zBuf);
37029   sqlite3_randomness(15, &zBuf[j]);
37030   for(i=0; i<15; i++, j++){
37031     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
37032   }
37033   zBuf[j] = 0;
37034   zBuf[j+1] = 0;
37035   *pzBuf = zBuf;
37036 
37037   OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
37038   return SQLITE_OK;
37039 }
37040 
37041 /*
37042 ** Return TRUE if the named file is really a directory.  Return false if
37043 ** it is something other than a directory, or if there is any kind of memory
37044 ** allocation failure.
37045 */
37046 static int winIsDir(const void *zConverted){
37047   DWORD attr;
37048   int rc = 0;
37049   DWORD lastErrno;
37050 
37051   if( osIsNT() ){
37052     int cnt = 0;
37053     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
37054     memset(&sAttrData, 0, sizeof(sAttrData));
37055     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
37056                              GetFileExInfoStandard,
37057                              &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
37058     if( !rc ){
37059       return 0; /* Invalid name? */
37060     }
37061     attr = sAttrData.dwFileAttributes;
37062 #if SQLITE_OS_WINCE==0
37063   }else{
37064     attr = osGetFileAttributesA((char*)zConverted);
37065 #endif
37066   }
37067   return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
37068 }
37069 
37070 /*
37071 ** Open a file.
37072 */
37073 static int winOpen(
37074   sqlite3_vfs *pVfs,        /* Used to get maximum path name length */
37075   const char *zName,        /* Name of the file (UTF-8) */
37076   sqlite3_file *id,         /* Write the SQLite file handle here */
37077   int flags,                /* Open mode flags */
37078   int *pOutFlags            /* Status return flags */
37079 ){
37080   HANDLE h;
37081   DWORD lastErrno = 0;
37082   DWORD dwDesiredAccess;
37083   DWORD dwShareMode;
37084   DWORD dwCreationDisposition;
37085   DWORD dwFlagsAndAttributes = 0;
37086 #if SQLITE_OS_WINCE
37087   int isTemp = 0;
37088 #endif
37089   winFile *pFile = (winFile*)id;
37090   void *zConverted;              /* Filename in OS encoding */
37091   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
37092   int cnt = 0;
37093 
37094   /* If argument zPath is a NULL pointer, this function is required to open
37095   ** a temporary file. Use this buffer to store the file name in.
37096   */
37097   char *zTmpname = 0; /* For temporary filename, if necessary. */
37098 
37099   int rc = SQLITE_OK;            /* Function Return Code */
37100 #if !defined(NDEBUG) || SQLITE_OS_WINCE
37101   int eType = flags&0xFFFFFF00;  /* Type of file to open */
37102 #endif
37103 
37104   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
37105   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
37106   int isCreate     = (flags & SQLITE_OPEN_CREATE);
37107   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
37108   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
37109 
37110 #ifndef NDEBUG
37111   int isOpenJournal = (isCreate && (
37112         eType==SQLITE_OPEN_MASTER_JOURNAL
37113      || eType==SQLITE_OPEN_MAIN_JOURNAL
37114      || eType==SQLITE_OPEN_WAL
37115   ));
37116 #endif
37117 
37118   OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
37119            zUtf8Name, id, flags, pOutFlags));
37120 
37121   /* Check the following statements are true:
37122   **
37123   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
37124   **   (b) if CREATE is set, then READWRITE must also be set, and
37125   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
37126   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
37127   */
37128   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
37129   assert(isCreate==0 || isReadWrite);
37130   assert(isExclusive==0 || isCreate);
37131   assert(isDelete==0 || isCreate);
37132 
37133   /* The main DB, main journal, WAL file and master journal are never
37134   ** automatically deleted. Nor are they ever temporary files.  */
37135   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
37136   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
37137   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
37138   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
37139 
37140   /* Assert that the upper layer has set one of the "file-type" flags. */
37141   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
37142        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
37143        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
37144        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
37145   );
37146 
37147   assert( pFile!=0 );
37148   memset(pFile, 0, sizeof(winFile));
37149   pFile->h = INVALID_HANDLE_VALUE;
37150 
37151 #if SQLITE_OS_WINRT
37152   if( !zUtf8Name && !sqlite3_temp_directory ){
37153     sqlite3_log(SQLITE_ERROR,
37154         "sqlite3_temp_directory variable should be set for WinRT");
37155   }
37156 #endif
37157 
37158   /* If the second argument to this function is NULL, generate a
37159   ** temporary file name to use
37160   */
37161   if( !zUtf8Name ){
37162     assert( isDelete && !isOpenJournal );
37163     rc = winGetTempname(pVfs, &zTmpname);
37164     if( rc!=SQLITE_OK ){
37165       OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
37166       return rc;
37167     }
37168     zUtf8Name = zTmpname;
37169   }
37170 
37171   /* Database filenames are double-zero terminated if they are not
37172   ** URIs with parameters.  Hence, they can always be passed into
37173   ** sqlite3_uri_parameter().
37174   */
37175   assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
37176        zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
37177 
37178   /* Convert the filename to the system encoding. */
37179   zConverted = winConvertFromUtf8Filename(zUtf8Name);
37180   if( zConverted==0 ){
37181     sqlite3_free(zTmpname);
37182     OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
37183     return SQLITE_IOERR_NOMEM;
37184   }
37185 
37186   if( winIsDir(zConverted) ){
37187     sqlite3_free(zConverted);
37188     sqlite3_free(zTmpname);
37189     OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
37190     return SQLITE_CANTOPEN_ISDIR;
37191   }
37192 
37193   if( isReadWrite ){
37194     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
37195   }else{
37196     dwDesiredAccess = GENERIC_READ;
37197   }
37198 
37199   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
37200   ** created. SQLite doesn't use it to indicate "exclusive access"
37201   ** as it is usually understood.
37202   */
37203   if( isExclusive ){
37204     /* Creates a new file, only if it does not already exist. */
37205     /* If the file exists, it fails. */
37206     dwCreationDisposition = CREATE_NEW;
37207   }else if( isCreate ){
37208     /* Open existing file, or create if it doesn't exist */
37209     dwCreationDisposition = OPEN_ALWAYS;
37210   }else{
37211     /* Opens a file, only if it exists. */
37212     dwCreationDisposition = OPEN_EXISTING;
37213   }
37214 
37215   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
37216 
37217   if( isDelete ){
37218 #if SQLITE_OS_WINCE
37219     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
37220     isTemp = 1;
37221 #else
37222     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
37223                                | FILE_ATTRIBUTE_HIDDEN
37224                                | FILE_FLAG_DELETE_ON_CLOSE;
37225 #endif
37226   }else{
37227     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
37228   }
37229   /* Reports from the internet are that performance is always
37230   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
37231 #if SQLITE_OS_WINCE
37232   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
37233 #endif
37234 
37235   if( osIsNT() ){
37236 #if SQLITE_OS_WINRT
37237     CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
37238     extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
37239     extendedParameters.dwFileAttributes =
37240             dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
37241     extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
37242     extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
37243     extendedParameters.lpSecurityAttributes = NULL;
37244     extendedParameters.hTemplateFile = NULL;
37245     while( (h = osCreateFile2((LPCWSTR)zConverted,
37246                               dwDesiredAccess,
37247                               dwShareMode,
37248                               dwCreationDisposition,
37249                               &extendedParameters))==INVALID_HANDLE_VALUE &&
37250                               winRetryIoerr(&cnt, &lastErrno) ){
37251                /* Noop */
37252     }
37253 #else
37254     while( (h = osCreateFileW((LPCWSTR)zConverted,
37255                               dwDesiredAccess,
37256                               dwShareMode, NULL,
37257                               dwCreationDisposition,
37258                               dwFlagsAndAttributes,
37259                               NULL))==INVALID_HANDLE_VALUE &&
37260                               winRetryIoerr(&cnt, &lastErrno) ){
37261                /* Noop */
37262     }
37263 #endif
37264   }
37265 #ifdef SQLITE_WIN32_HAS_ANSI
37266   else{
37267     while( (h = osCreateFileA((LPCSTR)zConverted,
37268                               dwDesiredAccess,
37269                               dwShareMode, NULL,
37270                               dwCreationDisposition,
37271                               dwFlagsAndAttributes,
37272                               NULL))==INVALID_HANDLE_VALUE &&
37273                               winRetryIoerr(&cnt, &lastErrno) ){
37274                /* Noop */
37275     }
37276   }
37277 #endif
37278   winLogIoerr(cnt);
37279 
37280   OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
37281            dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
37282 
37283   if( h==INVALID_HANDLE_VALUE ){
37284     pFile->lastErrno = lastErrno;
37285     winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
37286     sqlite3_free(zConverted);
37287     sqlite3_free(zTmpname);
37288     if( isReadWrite && !isExclusive ){
37289       return winOpen(pVfs, zName, id,
37290          ((flags|SQLITE_OPEN_READONLY) &
37291                      ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
37292          pOutFlags);
37293     }else{
37294       return SQLITE_CANTOPEN_BKPT;
37295     }
37296   }
37297 
37298   if( pOutFlags ){
37299     if( isReadWrite ){
37300       *pOutFlags = SQLITE_OPEN_READWRITE;
37301     }else{
37302       *pOutFlags = SQLITE_OPEN_READONLY;
37303     }
37304   }
37305 
37306   OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
37307            "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
37308            *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
37309 
37310 #if SQLITE_OS_WINCE
37311   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
37312        && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
37313   ){
37314     osCloseHandle(h);
37315     sqlite3_free(zConverted);
37316     sqlite3_free(zTmpname);
37317     OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
37318     return rc;
37319   }
37320   if( isTemp ){
37321     pFile->zDeleteOnClose = zConverted;
37322   }else
37323 #endif
37324   {
37325     sqlite3_free(zConverted);
37326   }
37327 
37328   sqlite3_free(zTmpname);
37329   pFile->pMethod = &winIoMethod;
37330   pFile->pVfs = pVfs;
37331   pFile->h = h;
37332   if( isReadonly ){
37333     pFile->ctrlFlags |= WINFILE_RDONLY;
37334   }
37335   if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
37336     pFile->ctrlFlags |= WINFILE_PSOW;
37337   }
37338   pFile->lastErrno = NO_ERROR;
37339   pFile->zPath = zName;
37340 #if SQLITE_MAX_MMAP_SIZE>0
37341   pFile->hMap = NULL;
37342   pFile->pMapRegion = 0;
37343   pFile->mmapSize = 0;
37344   pFile->mmapSizeActual = 0;
37345   pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
37346 #endif
37347 
37348   OpenCounter(+1);
37349   return rc;
37350 }
37351 
37352 /*
37353 ** Delete the named file.
37354 **
37355 ** Note that Windows does not allow a file to be deleted if some other
37356 ** process has it open.  Sometimes a virus scanner or indexing program
37357 ** will open a journal file shortly after it is created in order to do
37358 ** whatever it does.  While this other process is holding the
37359 ** file open, we will be unable to delete it.  To work around this
37360 ** problem, we delay 100 milliseconds and try to delete again.  Up
37361 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
37362 ** up and returning an error.
37363 */
37364 static int winDelete(
37365   sqlite3_vfs *pVfs,          /* Not used on win32 */
37366   const char *zFilename,      /* Name of file to delete */
37367   int syncDir                 /* Not used on win32 */
37368 ){
37369   int cnt = 0;
37370   int rc;
37371   DWORD attr;
37372   DWORD lastErrno = 0;
37373   void *zConverted;
37374   UNUSED_PARAMETER(pVfs);
37375   UNUSED_PARAMETER(syncDir);
37376 
37377   SimulateIOError(return SQLITE_IOERR_DELETE);
37378   OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
37379 
37380   zConverted = winConvertFromUtf8Filename(zFilename);
37381   if( zConverted==0 ){
37382     OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
37383     return SQLITE_IOERR_NOMEM;
37384   }
37385   if( osIsNT() ){
37386     do {
37387 #if SQLITE_OS_WINRT
37388       WIN32_FILE_ATTRIBUTE_DATA sAttrData;
37389       memset(&sAttrData, 0, sizeof(sAttrData));
37390       if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
37391                                   &sAttrData) ){
37392         attr = sAttrData.dwFileAttributes;
37393       }else{
37394         lastErrno = osGetLastError();
37395         if( lastErrno==ERROR_FILE_NOT_FOUND
37396          || lastErrno==ERROR_PATH_NOT_FOUND ){
37397           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
37398         }else{
37399           rc = SQLITE_ERROR;
37400         }
37401         break;
37402       }
37403 #else
37404       attr = osGetFileAttributesW(zConverted);
37405 #endif
37406       if ( attr==INVALID_FILE_ATTRIBUTES ){
37407         lastErrno = osGetLastError();
37408         if( lastErrno==ERROR_FILE_NOT_FOUND
37409          || lastErrno==ERROR_PATH_NOT_FOUND ){
37410           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
37411         }else{
37412           rc = SQLITE_ERROR;
37413         }
37414         break;
37415       }
37416       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
37417         rc = SQLITE_ERROR; /* Files only. */
37418         break;
37419       }
37420       if ( osDeleteFileW(zConverted) ){
37421         rc = SQLITE_OK; /* Deleted OK. */
37422         break;
37423       }
37424       if ( !winRetryIoerr(&cnt, &lastErrno) ){
37425         rc = SQLITE_ERROR; /* No more retries. */
37426         break;
37427       }
37428     } while(1);
37429   }
37430 #ifdef SQLITE_WIN32_HAS_ANSI
37431   else{
37432     do {
37433       attr = osGetFileAttributesA(zConverted);
37434       if ( attr==INVALID_FILE_ATTRIBUTES ){
37435         lastErrno = osGetLastError();
37436         if( lastErrno==ERROR_FILE_NOT_FOUND
37437          || lastErrno==ERROR_PATH_NOT_FOUND ){
37438           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
37439         }else{
37440           rc = SQLITE_ERROR;
37441         }
37442         break;
37443       }
37444       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
37445         rc = SQLITE_ERROR; /* Files only. */
37446         break;
37447       }
37448       if ( osDeleteFileA(zConverted) ){
37449         rc = SQLITE_OK; /* Deleted OK. */
37450         break;
37451       }
37452       if ( !winRetryIoerr(&cnt, &lastErrno) ){
37453         rc = SQLITE_ERROR; /* No more retries. */
37454         break;
37455       }
37456     } while(1);
37457   }
37458 #endif
37459   if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
37460     rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
37461   }else{
37462     winLogIoerr(cnt);
37463   }
37464   sqlite3_free(zConverted);
37465   OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
37466   return rc;
37467 }
37468 
37469 /*
37470 ** Check the existence and status of a file.
37471 */
37472 static int winAccess(
37473   sqlite3_vfs *pVfs,         /* Not used on win32 */
37474   const char *zFilename,     /* Name of file to check */
37475   int flags,                 /* Type of test to make on this file */
37476   int *pResOut               /* OUT: Result */
37477 ){
37478   DWORD attr;
37479   int rc = 0;
37480   DWORD lastErrno = 0;
37481   void *zConverted;
37482   UNUSED_PARAMETER(pVfs);
37483 
37484   SimulateIOError( return SQLITE_IOERR_ACCESS; );
37485   OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
37486            zFilename, flags, pResOut));
37487 
37488   zConverted = winConvertFromUtf8Filename(zFilename);
37489   if( zConverted==0 ){
37490     OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
37491     return SQLITE_IOERR_NOMEM;
37492   }
37493   if( osIsNT() ){
37494     int cnt = 0;
37495     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
37496     memset(&sAttrData, 0, sizeof(sAttrData));
37497     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
37498                              GetFileExInfoStandard,
37499                              &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
37500     if( rc ){
37501       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
37502       ** as if it does not exist.
37503       */
37504       if(    flags==SQLITE_ACCESS_EXISTS
37505           && sAttrData.nFileSizeHigh==0
37506           && sAttrData.nFileSizeLow==0 ){
37507         attr = INVALID_FILE_ATTRIBUTES;
37508       }else{
37509         attr = sAttrData.dwFileAttributes;
37510       }
37511     }else{
37512       winLogIoerr(cnt);
37513       if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
37514         sqlite3_free(zConverted);
37515         return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
37516                            zFilename);
37517       }else{
37518         attr = INVALID_FILE_ATTRIBUTES;
37519       }
37520     }
37521   }
37522 #ifdef SQLITE_WIN32_HAS_ANSI
37523   else{
37524     attr = osGetFileAttributesA((char*)zConverted);
37525   }
37526 #endif
37527   sqlite3_free(zConverted);
37528   switch( flags ){
37529     case SQLITE_ACCESS_READ:
37530     case SQLITE_ACCESS_EXISTS:
37531       rc = attr!=INVALID_FILE_ATTRIBUTES;
37532       break;
37533     case SQLITE_ACCESS_READWRITE:
37534       rc = attr!=INVALID_FILE_ATTRIBUTES &&
37535              (attr & FILE_ATTRIBUTE_READONLY)==0;
37536       break;
37537     default:
37538       assert(!"Invalid flags argument");
37539   }
37540   *pResOut = rc;
37541   OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
37542            zFilename, pResOut, *pResOut));
37543   return SQLITE_OK;
37544 }
37545 
37546 /*
37547 ** Returns non-zero if the specified path name starts with a drive letter
37548 ** followed by a colon character.
37549 */
37550 static BOOL winIsDriveLetterAndColon(
37551   const char *zPathname
37552 ){
37553   return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
37554 }
37555 
37556 /*
37557 ** Returns non-zero if the specified path name should be used verbatim.  If
37558 ** non-zero is returned from this function, the calling function must simply
37559 ** use the provided path name verbatim -OR- resolve it into a full path name
37560 ** using the GetFullPathName Win32 API function (if available).
37561 */
37562 static BOOL winIsVerbatimPathname(
37563   const char *zPathname
37564 ){
37565   /*
37566   ** If the path name starts with a forward slash or a backslash, it is either
37567   ** a legal UNC name, a volume relative path, or an absolute path name in the
37568   ** "Unix" format on Windows.  There is no easy way to differentiate between
37569   ** the final two cases; therefore, we return the safer return value of TRUE
37570   ** so that callers of this function will simply use it verbatim.
37571   */
37572   if ( winIsDirSep(zPathname[0]) ){
37573     return TRUE;
37574   }
37575 
37576   /*
37577   ** If the path name starts with a letter and a colon it is either a volume
37578   ** relative path or an absolute path.  Callers of this function must not
37579   ** attempt to treat it as a relative path name (i.e. they should simply use
37580   ** it verbatim).
37581   */
37582   if ( winIsDriveLetterAndColon(zPathname) ){
37583     return TRUE;
37584   }
37585 
37586   /*
37587   ** If we get to this point, the path name should almost certainly be a purely
37588   ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
37589   */
37590   return FALSE;
37591 }
37592 
37593 /*
37594 ** Turn a relative pathname into a full pathname.  Write the full
37595 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
37596 ** bytes in size.
37597 */
37598 static int winFullPathname(
37599   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
37600   const char *zRelative,        /* Possibly relative input path */
37601   int nFull,                    /* Size of output buffer in bytes */
37602   char *zFull                   /* Output buffer */
37603 ){
37604 
37605 #if defined(__CYGWIN__)
37606   SimulateIOError( return SQLITE_ERROR );
37607   UNUSED_PARAMETER(nFull);
37608   assert( nFull>=pVfs->mxPathname );
37609   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
37610     /*
37611     ** NOTE: We are dealing with a relative path name and the data
37612     **       directory has been set.  Therefore, use it as the basis
37613     **       for converting the relative path name to an absolute
37614     **       one by prepending the data directory and a slash.
37615     */
37616     char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
37617     if( !zOut ){
37618       return SQLITE_IOERR_NOMEM;
37619     }
37620     if( cygwin_conv_path(
37621             (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
37622             CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
37623       sqlite3_free(zOut);
37624       return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
37625                          "winFullPathname1", zRelative);
37626     }else{
37627       char *zUtf8 = winConvertToUtf8Filename(zOut);
37628       if( !zUtf8 ){
37629         sqlite3_free(zOut);
37630         return SQLITE_IOERR_NOMEM;
37631       }
37632       sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
37633                        sqlite3_data_directory, winGetDirSep(), zUtf8);
37634       sqlite3_free(zUtf8);
37635       sqlite3_free(zOut);
37636     }
37637   }else{
37638     char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
37639     if( !zOut ){
37640       return SQLITE_IOERR_NOMEM;
37641     }
37642     if( cygwin_conv_path(
37643             (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
37644             zRelative, zOut, pVfs->mxPathname+1)<0 ){
37645       sqlite3_free(zOut);
37646       return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
37647                          "winFullPathname2", zRelative);
37648     }else{
37649       char *zUtf8 = winConvertToUtf8Filename(zOut);
37650       if( !zUtf8 ){
37651         sqlite3_free(zOut);
37652         return SQLITE_IOERR_NOMEM;
37653       }
37654       sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
37655       sqlite3_free(zUtf8);
37656       sqlite3_free(zOut);
37657     }
37658   }
37659   return SQLITE_OK;
37660 #endif
37661 
37662 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
37663   SimulateIOError( return SQLITE_ERROR );
37664   /* WinCE has no concept of a relative pathname, or so I am told. */
37665   /* WinRT has no way to convert a relative path to an absolute one. */
37666   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
37667     /*
37668     ** NOTE: We are dealing with a relative path name and the data
37669     **       directory has been set.  Therefore, use it as the basis
37670     **       for converting the relative path name to an absolute
37671     **       one by prepending the data directory and a backslash.
37672     */
37673     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
37674                      sqlite3_data_directory, winGetDirSep(), zRelative);
37675   }else{
37676     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
37677   }
37678   return SQLITE_OK;
37679 #endif
37680 
37681 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
37682   DWORD nByte;
37683   void *zConverted;
37684   char *zOut;
37685 
37686   /* If this path name begins with "/X:", where "X" is any alphabetic
37687   ** character, discard the initial "/" from the pathname.
37688   */
37689   if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
37690     zRelative++;
37691   }
37692 
37693   /* It's odd to simulate an io-error here, but really this is just
37694   ** using the io-error infrastructure to test that SQLite handles this
37695   ** function failing. This function could fail if, for example, the
37696   ** current working directory has been unlinked.
37697   */
37698   SimulateIOError( return SQLITE_ERROR );
37699   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
37700     /*
37701     ** NOTE: We are dealing with a relative path name and the data
37702     **       directory has been set.  Therefore, use it as the basis
37703     **       for converting the relative path name to an absolute
37704     **       one by prepending the data directory and a backslash.
37705     */
37706     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
37707                      sqlite3_data_directory, winGetDirSep(), zRelative);
37708     return SQLITE_OK;
37709   }
37710   zConverted = winConvertFromUtf8Filename(zRelative);
37711   if( zConverted==0 ){
37712     return SQLITE_IOERR_NOMEM;
37713   }
37714   if( osIsNT() ){
37715     LPWSTR zTemp;
37716     nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
37717     if( nByte==0 ){
37718       sqlite3_free(zConverted);
37719       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
37720                          "winFullPathname1", zRelative);
37721     }
37722     nByte += 3;
37723     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
37724     if( zTemp==0 ){
37725       sqlite3_free(zConverted);
37726       return SQLITE_IOERR_NOMEM;
37727     }
37728     nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
37729     if( nByte==0 ){
37730       sqlite3_free(zConverted);
37731       sqlite3_free(zTemp);
37732       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
37733                          "winFullPathname2", zRelative);
37734     }
37735     sqlite3_free(zConverted);
37736     zOut = winUnicodeToUtf8(zTemp);
37737     sqlite3_free(zTemp);
37738   }
37739 #ifdef SQLITE_WIN32_HAS_ANSI
37740   else{
37741     char *zTemp;
37742     nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
37743     if( nByte==0 ){
37744       sqlite3_free(zConverted);
37745       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
37746                          "winFullPathname3", zRelative);
37747     }
37748     nByte += 3;
37749     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
37750     if( zTemp==0 ){
37751       sqlite3_free(zConverted);
37752       return SQLITE_IOERR_NOMEM;
37753     }
37754     nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
37755     if( nByte==0 ){
37756       sqlite3_free(zConverted);
37757       sqlite3_free(zTemp);
37758       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
37759                          "winFullPathname4", zRelative);
37760     }
37761     sqlite3_free(zConverted);
37762     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
37763     sqlite3_free(zTemp);
37764   }
37765 #endif
37766   if( zOut ){
37767     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
37768     sqlite3_free(zOut);
37769     return SQLITE_OK;
37770   }else{
37771     return SQLITE_IOERR_NOMEM;
37772   }
37773 #endif
37774 }
37775 
37776 #ifndef SQLITE_OMIT_LOAD_EXTENSION
37777 /*
37778 ** Interfaces for opening a shared library, finding entry points
37779 ** within the shared library, and closing the shared library.
37780 */
37781 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
37782   HANDLE h;
37783 #if defined(__CYGWIN__)
37784   int nFull = pVfs->mxPathname+1;
37785   char *zFull = sqlite3MallocZero( nFull );
37786   void *zConverted = 0;
37787   if( zFull==0 ){
37788     OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
37789     return 0;
37790   }
37791   if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
37792     sqlite3_free(zFull);
37793     OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
37794     return 0;
37795   }
37796   zConverted = winConvertFromUtf8Filename(zFull);
37797   sqlite3_free(zFull);
37798 #else
37799   void *zConverted = winConvertFromUtf8Filename(zFilename);
37800   UNUSED_PARAMETER(pVfs);
37801 #endif
37802   if( zConverted==0 ){
37803     OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
37804     return 0;
37805   }
37806   if( osIsNT() ){
37807 #if SQLITE_OS_WINRT
37808     h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
37809 #else
37810     h = osLoadLibraryW((LPCWSTR)zConverted);
37811 #endif
37812   }
37813 #ifdef SQLITE_WIN32_HAS_ANSI
37814   else{
37815     h = osLoadLibraryA((char*)zConverted);
37816   }
37817 #endif
37818   OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
37819   sqlite3_free(zConverted);
37820   return (void*)h;
37821 }
37822 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
37823   UNUSED_PARAMETER(pVfs);
37824   winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
37825 }
37826 static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
37827   FARPROC proc;
37828   UNUSED_PARAMETER(pVfs);
37829   proc = osGetProcAddressA((HANDLE)pH, zSym);
37830   OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
37831            (void*)pH, zSym, (void*)proc));
37832   return (void(*)(void))proc;
37833 }
37834 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
37835   UNUSED_PARAMETER(pVfs);
37836   osFreeLibrary((HANDLE)pHandle);
37837   OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
37838 }
37839 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
37840   #define winDlOpen  0
37841   #define winDlError 0
37842   #define winDlSym   0
37843   #define winDlClose 0
37844 #endif
37845 
37846 
37847 /*
37848 ** Write up to nBuf bytes of randomness into zBuf.
37849 */
37850 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
37851   int n = 0;
37852   UNUSED_PARAMETER(pVfs);
37853 #if defined(SQLITE_TEST)
37854   n = nBuf;
37855   memset(zBuf, 0, nBuf);
37856 #else
37857   if( sizeof(SYSTEMTIME)<=nBuf-n ){
37858     SYSTEMTIME x;
37859     osGetSystemTime(&x);
37860     memcpy(&zBuf[n], &x, sizeof(x));
37861     n += sizeof(x);
37862   }
37863   if( sizeof(DWORD)<=nBuf-n ){
37864     DWORD pid = osGetCurrentProcessId();
37865     memcpy(&zBuf[n], &pid, sizeof(pid));
37866     n += sizeof(pid);
37867   }
37868 #if SQLITE_OS_WINRT
37869   if( sizeof(ULONGLONG)<=nBuf-n ){
37870     ULONGLONG cnt = osGetTickCount64();
37871     memcpy(&zBuf[n], &cnt, sizeof(cnt));
37872     n += sizeof(cnt);
37873   }
37874 #else
37875   if( sizeof(DWORD)<=nBuf-n ){
37876     DWORD cnt = osGetTickCount();
37877     memcpy(&zBuf[n], &cnt, sizeof(cnt));
37878     n += sizeof(cnt);
37879   }
37880 #endif
37881   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
37882     LARGE_INTEGER i;
37883     osQueryPerformanceCounter(&i);
37884     memcpy(&zBuf[n], &i, sizeof(i));
37885     n += sizeof(i);
37886   }
37887 #endif
37888   return n;
37889 }
37890 
37891 
37892 /*
37893 ** Sleep for a little while.  Return the amount of time slept.
37894 */
37895 static int winSleep(sqlite3_vfs *pVfs, int microsec){
37896   sqlite3_win32_sleep((microsec+999)/1000);
37897   UNUSED_PARAMETER(pVfs);
37898   return ((microsec+999)/1000)*1000;
37899 }
37900 
37901 /*
37902 ** The following variable, if set to a non-zero value, is interpreted as
37903 ** the number of seconds since 1970 and is used to set the result of
37904 ** sqlite3OsCurrentTime() during testing.
37905 */
37906 #ifdef SQLITE_TEST
37907 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
37908 #endif
37909 
37910 /*
37911 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
37912 ** the current time and date as a Julian Day number times 86_400_000.  In
37913 ** other words, write into *piNow the number of milliseconds since the Julian
37914 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
37915 ** proleptic Gregorian calendar.
37916 **
37917 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
37918 ** cannot be found.
37919 */
37920 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
37921   /* FILETIME structure is a 64-bit value representing the number of
37922      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
37923   */
37924   FILETIME ft;
37925   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
37926 #ifdef SQLITE_TEST
37927   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
37928 #endif
37929   /* 2^32 - to avoid use of LL and warnings in gcc */
37930   static const sqlite3_int64 max32BitValue =
37931       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
37932       (sqlite3_int64)294967296;
37933 
37934 #if SQLITE_OS_WINCE
37935   SYSTEMTIME time;
37936   osGetSystemTime(&time);
37937   /* if SystemTimeToFileTime() fails, it returns zero. */
37938   if (!osSystemTimeToFileTime(&time,&ft)){
37939     return SQLITE_ERROR;
37940   }
37941 #else
37942   osGetSystemTimeAsFileTime( &ft );
37943 #endif
37944 
37945   *piNow = winFiletimeEpoch +
37946             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
37947                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
37948 
37949 #ifdef SQLITE_TEST
37950   if( sqlite3_current_time ){
37951     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
37952   }
37953 #endif
37954   UNUSED_PARAMETER(pVfs);
37955   return SQLITE_OK;
37956 }
37957 
37958 /*
37959 ** Find the current time (in Universal Coordinated Time).  Write the
37960 ** current time and date as a Julian Day number into *prNow and
37961 ** return 0.  Return 1 if the time and date cannot be found.
37962 */
37963 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
37964   int rc;
37965   sqlite3_int64 i;
37966   rc = winCurrentTimeInt64(pVfs, &i);
37967   if( !rc ){
37968     *prNow = i/86400000.0;
37969   }
37970   return rc;
37971 }
37972 
37973 /*
37974 ** The idea is that this function works like a combination of
37975 ** GetLastError() and FormatMessage() on Windows (or errno and
37976 ** strerror_r() on Unix). After an error is returned by an OS
37977 ** function, SQLite calls this function with zBuf pointing to
37978 ** a buffer of nBuf bytes. The OS layer should populate the
37979 ** buffer with a nul-terminated UTF-8 encoded error message
37980 ** describing the last IO error to have occurred within the calling
37981 ** thread.
37982 **
37983 ** If the error message is too large for the supplied buffer,
37984 ** it should be truncated. The return value of xGetLastError
37985 ** is zero if the error message fits in the buffer, or non-zero
37986 ** otherwise (if the message was truncated). If non-zero is returned,
37987 ** then it is not necessary to include the nul-terminator character
37988 ** in the output buffer.
37989 **
37990 ** Not supplying an error message will have no adverse effect
37991 ** on SQLite. It is fine to have an implementation that never
37992 ** returns an error message:
37993 **
37994 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
37995 **     assert(zBuf[0]=='\0');
37996 **     return 0;
37997 **   }
37998 **
37999 ** However if an error message is supplied, it will be incorporated
38000 ** by sqlite into the error message available to the user using
38001 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
38002 */
38003 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
38004   UNUSED_PARAMETER(pVfs);
38005   return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
38006 }
38007 
38008 /*
38009 ** Initialize and deinitialize the operating system interface.
38010 */
38011 SQLITE_API int sqlite3_os_init(void){
38012   static sqlite3_vfs winVfs = {
38013     3,                   /* iVersion */
38014     sizeof(winFile),     /* szOsFile */
38015     SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
38016     0,                   /* pNext */
38017     "win32",             /* zName */
38018     0,                   /* pAppData */
38019     winOpen,             /* xOpen */
38020     winDelete,           /* xDelete */
38021     winAccess,           /* xAccess */
38022     winFullPathname,     /* xFullPathname */
38023     winDlOpen,           /* xDlOpen */
38024     winDlError,          /* xDlError */
38025     winDlSym,            /* xDlSym */
38026     winDlClose,          /* xDlClose */
38027     winRandomness,       /* xRandomness */
38028     winSleep,            /* xSleep */
38029     winCurrentTime,      /* xCurrentTime */
38030     winGetLastError,     /* xGetLastError */
38031     winCurrentTimeInt64, /* xCurrentTimeInt64 */
38032     winSetSystemCall,    /* xSetSystemCall */
38033     winGetSystemCall,    /* xGetSystemCall */
38034     winNextSystemCall,   /* xNextSystemCall */
38035   };
38036 #if defined(SQLITE_WIN32_HAS_WIDE)
38037   static sqlite3_vfs winLongPathVfs = {
38038     3,                   /* iVersion */
38039     sizeof(winFile),     /* szOsFile */
38040     SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
38041     0,                   /* pNext */
38042     "win32-longpath",    /* zName */
38043     0,                   /* pAppData */
38044     winOpen,             /* xOpen */
38045     winDelete,           /* xDelete */
38046     winAccess,           /* xAccess */
38047     winFullPathname,     /* xFullPathname */
38048     winDlOpen,           /* xDlOpen */
38049     winDlError,          /* xDlError */
38050     winDlSym,            /* xDlSym */
38051     winDlClose,          /* xDlClose */
38052     winRandomness,       /* xRandomness */
38053     winSleep,            /* xSleep */
38054     winCurrentTime,      /* xCurrentTime */
38055     winGetLastError,     /* xGetLastError */
38056     winCurrentTimeInt64, /* xCurrentTimeInt64 */
38057     winSetSystemCall,    /* xSetSystemCall */
38058     winGetSystemCall,    /* xGetSystemCall */
38059     winNextSystemCall,   /* xNextSystemCall */
38060   };
38061 #endif
38062 
38063   /* Double-check that the aSyscall[] array has been constructed
38064   ** correctly.  See ticket [bb3a86e890c8e96ab] */
38065   assert( ArraySize(aSyscall)==77 );
38066 
38067   /* get memory map allocation granularity */
38068   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
38069 #if SQLITE_OS_WINRT
38070   osGetNativeSystemInfo(&winSysInfo);
38071 #else
38072   osGetSystemInfo(&winSysInfo);
38073 #endif
38074   assert( winSysInfo.dwAllocationGranularity>0 );
38075   assert( winSysInfo.dwPageSize>0 );
38076 
38077   sqlite3_vfs_register(&winVfs, 1);
38078 
38079 #if defined(SQLITE_WIN32_HAS_WIDE)
38080   sqlite3_vfs_register(&winLongPathVfs, 0);
38081 #endif
38082 
38083   return SQLITE_OK;
38084 }
38085 
38086 SQLITE_API int sqlite3_os_end(void){
38087 #if SQLITE_OS_WINRT
38088   if( sleepObj!=NULL ){
38089     osCloseHandle(sleepObj);
38090     sleepObj = NULL;
38091   }
38092 #endif
38093   return SQLITE_OK;
38094 }
38095 
38096 #endif /* SQLITE_OS_WIN */
38097 
38098 /************** End of os_win.c **********************************************/
38099 /************** Begin file bitvec.c ******************************************/
38100 /*
38101 ** 2008 February 16
38102 **
38103 ** The author disclaims copyright to this source code.  In place of
38104 ** a legal notice, here is a blessing:
38105 **
38106 **    May you do good and not evil.
38107 **    May you find forgiveness for yourself and forgive others.
38108 **    May you share freely, never taking more than you give.
38109 **
38110 *************************************************************************
38111 ** This file implements an object that represents a fixed-length
38112 ** bitmap.  Bits are numbered starting with 1.
38113 **
38114 ** A bitmap is used to record which pages of a database file have been
38115 ** journalled during a transaction, or which pages have the "dont-write"
38116 ** property.  Usually only a few pages are meet either condition.
38117 ** So the bitmap is usually sparse and has low cardinality.
38118 ** But sometimes (for example when during a DROP of a large table) most
38119 ** or all of the pages in a database can get journalled.  In those cases,
38120 ** the bitmap becomes dense with high cardinality.  The algorithm needs
38121 ** to handle both cases well.
38122 **
38123 ** The size of the bitmap is fixed when the object is created.
38124 **
38125 ** All bits are clear when the bitmap is created.  Individual bits
38126 ** may be set or cleared one at a time.
38127 **
38128 ** Test operations are about 100 times more common that set operations.
38129 ** Clear operations are exceedingly rare.  There are usually between
38130 ** 5 and 500 set operations per Bitvec object, though the number of sets can
38131 ** sometimes grow into tens of thousands or larger.  The size of the
38132 ** Bitvec object is the number of pages in the database file at the
38133 ** start of a transaction, and is thus usually less than a few thousand,
38134 ** but can be as large as 2 billion for a really big database.
38135 */
38136 
38137 /* Size of the Bitvec structure in bytes. */
38138 #define BITVEC_SZ        512
38139 
38140 /* Round the union size down to the nearest pointer boundary, since that's how
38141 ** it will be aligned within the Bitvec struct. */
38142 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
38143 
38144 /* Type of the array "element" for the bitmap representation.
38145 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
38146 ** Setting this to the "natural word" size of your CPU may improve
38147 ** performance. */
38148 #define BITVEC_TELEM     u8
38149 /* Size, in bits, of the bitmap element. */
38150 #define BITVEC_SZELEM    8
38151 /* Number of elements in a bitmap array. */
38152 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
38153 /* Number of bits in the bitmap array. */
38154 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
38155 
38156 /* Number of u32 values in hash table. */
38157 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
38158 /* Maximum number of entries in hash table before
38159 ** sub-dividing and re-hashing. */
38160 #define BITVEC_MXHASH    (BITVEC_NINT/2)
38161 /* Hashing function for the aHash representation.
38162 ** Empirical testing showed that the *37 multiplier
38163 ** (an arbitrary prime)in the hash function provided
38164 ** no fewer collisions than the no-op *1. */
38165 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
38166 
38167 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
38168 
38169 
38170 /*
38171 ** A bitmap is an instance of the following structure.
38172 **
38173 ** This bitmap records the existence of zero or more bits
38174 ** with values between 1 and iSize, inclusive.
38175 **
38176 ** There are three possible representations of the bitmap.
38177 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
38178 ** bitmap.  The least significant bit is bit 1.
38179 **
38180 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
38181 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
38182 **
38183 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
38184 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
38185 ** handles up to iDivisor separate values of i.  apSub[0] holds
38186 ** values between 1 and iDivisor.  apSub[1] holds values between
38187 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
38188 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
38189 ** to hold deal with values between 1 and iDivisor.
38190 */
38191 struct Bitvec {
38192   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
38193   u32 nSet;       /* Number of bits that are set - only valid for aHash
38194                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
38195                   ** this would be 125. */
38196   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
38197                   /* Should >=0 for apSub element. */
38198                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
38199                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
38200   union {
38201     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
38202     u32 aHash[BITVEC_NINT];      /* Hash table representation */
38203     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
38204   } u;
38205 };
38206 
38207 /*
38208 ** Create a new bitmap object able to handle bits between 0 and iSize,
38209 ** inclusive.  Return a pointer to the new object.  Return NULL if
38210 ** malloc fails.
38211 */
38212 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
38213   Bitvec *p;
38214   assert( sizeof(*p)==BITVEC_SZ );
38215   p = sqlite3MallocZero( sizeof(*p) );
38216   if( p ){
38217     p->iSize = iSize;
38218   }
38219   return p;
38220 }
38221 
38222 /*
38223 ** Check to see if the i-th bit is set.  Return true or false.
38224 ** If p is NULL (if the bitmap has not been created) or if
38225 ** i is out of range, then return false.
38226 */
38227 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
38228   if( p==0 ) return 0;
38229   if( i>p->iSize || i==0 ) return 0;
38230   i--;
38231   while( p->iDivisor ){
38232     u32 bin = i/p->iDivisor;
38233     i = i%p->iDivisor;
38234     p = p->u.apSub[bin];
38235     if (!p) {
38236       return 0;
38237     }
38238   }
38239   if( p->iSize<=BITVEC_NBIT ){
38240     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
38241   } else{
38242     u32 h = BITVEC_HASH(i++);
38243     while( p->u.aHash[h] ){
38244       if( p->u.aHash[h]==i ) return 1;
38245       h = (h+1) % BITVEC_NINT;
38246     }
38247     return 0;
38248   }
38249 }
38250 
38251 /*
38252 ** Set the i-th bit.  Return 0 on success and an error code if
38253 ** anything goes wrong.
38254 **
38255 ** This routine might cause sub-bitmaps to be allocated.  Failing
38256 ** to get the memory needed to hold the sub-bitmap is the only
38257 ** that can go wrong with an insert, assuming p and i are valid.
38258 **
38259 ** The calling function must ensure that p is a valid Bitvec object
38260 ** and that the value for "i" is within range of the Bitvec object.
38261 ** Otherwise the behavior is undefined.
38262 */
38263 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
38264   u32 h;
38265   if( p==0 ) return SQLITE_OK;
38266   assert( i>0 );
38267   assert( i<=p->iSize );
38268   i--;
38269   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
38270     u32 bin = i/p->iDivisor;
38271     i = i%p->iDivisor;
38272     if( p->u.apSub[bin]==0 ){
38273       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
38274       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
38275     }
38276     p = p->u.apSub[bin];
38277   }
38278   if( p->iSize<=BITVEC_NBIT ){
38279     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
38280     return SQLITE_OK;
38281   }
38282   h = BITVEC_HASH(i++);
38283   /* if there wasn't a hash collision, and this doesn't */
38284   /* completely fill the hash, then just add it without */
38285   /* worring about sub-dividing and re-hashing. */
38286   if( !p->u.aHash[h] ){
38287     if (p->nSet<(BITVEC_NINT-1)) {
38288       goto bitvec_set_end;
38289     } else {
38290       goto bitvec_set_rehash;
38291     }
38292   }
38293   /* there was a collision, check to see if it's already */
38294   /* in hash, if not, try to find a spot for it */
38295   do {
38296     if( p->u.aHash[h]==i ) return SQLITE_OK;
38297     h++;
38298     if( h>=BITVEC_NINT ) h = 0;
38299   } while( p->u.aHash[h] );
38300   /* we didn't find it in the hash.  h points to the first */
38301   /* available free spot. check to see if this is going to */
38302   /* make our hash too "full".  */
38303 bitvec_set_rehash:
38304   if( p->nSet>=BITVEC_MXHASH ){
38305     unsigned int j;
38306     int rc;
38307     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
38308     if( aiValues==0 ){
38309       return SQLITE_NOMEM;
38310     }else{
38311       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
38312       memset(p->u.apSub, 0, sizeof(p->u.apSub));
38313       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
38314       rc = sqlite3BitvecSet(p, i);
38315       for(j=0; j<BITVEC_NINT; j++){
38316         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
38317       }
38318       sqlite3StackFree(0, aiValues);
38319       return rc;
38320     }
38321   }
38322 bitvec_set_end:
38323   p->nSet++;
38324   p->u.aHash[h] = i;
38325   return SQLITE_OK;
38326 }
38327 
38328 /*
38329 ** Clear the i-th bit.
38330 **
38331 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
38332 ** that BitvecClear can use to rebuilt its hash table.
38333 */
38334 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
38335   if( p==0 ) return;
38336   assert( i>0 );
38337   i--;
38338   while( p->iDivisor ){
38339     u32 bin = i/p->iDivisor;
38340     i = i%p->iDivisor;
38341     p = p->u.apSub[bin];
38342     if (!p) {
38343       return;
38344     }
38345   }
38346   if( p->iSize<=BITVEC_NBIT ){
38347     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
38348   }else{
38349     unsigned int j;
38350     u32 *aiValues = pBuf;
38351     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
38352     memset(p->u.aHash, 0, sizeof(p->u.aHash));
38353     p->nSet = 0;
38354     for(j=0; j<BITVEC_NINT; j++){
38355       if( aiValues[j] && aiValues[j]!=(i+1) ){
38356         u32 h = BITVEC_HASH(aiValues[j]-1);
38357         p->nSet++;
38358         while( p->u.aHash[h] ){
38359           h++;
38360           if( h>=BITVEC_NINT ) h = 0;
38361         }
38362         p->u.aHash[h] = aiValues[j];
38363       }
38364     }
38365   }
38366 }
38367 
38368 /*
38369 ** Destroy a bitmap object.  Reclaim all memory used.
38370 */
38371 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
38372   if( p==0 ) return;
38373   if( p->iDivisor ){
38374     unsigned int i;
38375     for(i=0; i<BITVEC_NPTR; i++){
38376       sqlite3BitvecDestroy(p->u.apSub[i]);
38377     }
38378   }
38379   sqlite3_free(p);
38380 }
38381 
38382 /*
38383 ** Return the value of the iSize parameter specified when Bitvec *p
38384 ** was created.
38385 */
38386 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
38387   return p->iSize;
38388 }
38389 
38390 #ifndef SQLITE_OMIT_BUILTIN_TEST
38391 /*
38392 ** Let V[] be an array of unsigned characters sufficient to hold
38393 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
38394 ** Then the following macros can be used to set, clear, or test
38395 ** individual bits within V.
38396 */
38397 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
38398 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
38399 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
38400 
38401 /*
38402 ** This routine runs an extensive test of the Bitvec code.
38403 **
38404 ** The input is an array of integers that acts as a program
38405 ** to test the Bitvec.  The integers are opcodes followed
38406 ** by 0, 1, or 3 operands, depending on the opcode.  Another
38407 ** opcode follows immediately after the last operand.
38408 **
38409 ** There are 6 opcodes numbered from 0 through 5.  0 is the
38410 ** "halt" opcode and causes the test to end.
38411 **
38412 **    0          Halt and return the number of errors
38413 **    1 N S X    Set N bits beginning with S and incrementing by X
38414 **    2 N S X    Clear N bits beginning with S and incrementing by X
38415 **    3 N        Set N randomly chosen bits
38416 **    4 N        Clear N randomly chosen bits
38417 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
38418 **
38419 ** The opcodes 1 through 4 perform set and clear operations are performed
38420 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
38421 ** Opcode 5 works on the linear array only, not on the Bitvec.
38422 ** Opcode 5 is used to deliberately induce a fault in order to
38423 ** confirm that error detection works.
38424 **
38425 ** At the conclusion of the test the linear array is compared
38426 ** against the Bitvec object.  If there are any differences,
38427 ** an error is returned.  If they are the same, zero is returned.
38428 **
38429 ** If a memory allocation error occurs, return -1.
38430 */
38431 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
38432   Bitvec *pBitvec = 0;
38433   unsigned char *pV = 0;
38434   int rc = -1;
38435   int i, nx, pc, op;
38436   void *pTmpSpace;
38437 
38438   /* Allocate the Bitvec to be tested and a linear array of
38439   ** bits to act as the reference */
38440   pBitvec = sqlite3BitvecCreate( sz );
38441   pV = sqlite3MallocZero( (sz+7)/8 + 1 );
38442   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
38443   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
38444 
38445   /* NULL pBitvec tests */
38446   sqlite3BitvecSet(0, 1);
38447   sqlite3BitvecClear(0, 1, pTmpSpace);
38448 
38449   /* Run the program */
38450   pc = 0;
38451   while( (op = aOp[pc])!=0 ){
38452     switch( op ){
38453       case 1:
38454       case 2:
38455       case 5: {
38456         nx = 4;
38457         i = aOp[pc+2] - 1;
38458         aOp[pc+2] += aOp[pc+3];
38459         break;
38460       }
38461       case 3:
38462       case 4:
38463       default: {
38464         nx = 2;
38465         sqlite3_randomness(sizeof(i), &i);
38466         break;
38467       }
38468     }
38469     if( (--aOp[pc+1]) > 0 ) nx = 0;
38470     pc += nx;
38471     i = (i & 0x7fffffff)%sz;
38472     if( (op & 1)!=0 ){
38473       SETBIT(pV, (i+1));
38474       if( op!=5 ){
38475         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
38476       }
38477     }else{
38478       CLEARBIT(pV, (i+1));
38479       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
38480     }
38481   }
38482 
38483   /* Test to make sure the linear array exactly matches the
38484   ** Bitvec object.  Start with the assumption that they do
38485   ** match (rc==0).  Change rc to non-zero if a discrepancy
38486   ** is found.
38487   */
38488   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
38489           + sqlite3BitvecTest(pBitvec, 0)
38490           + (sqlite3BitvecSize(pBitvec) - sz);
38491   for(i=1; i<=sz; i++){
38492     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
38493       rc = i;
38494       break;
38495     }
38496   }
38497 
38498   /* Free allocated structure */
38499 bitvec_end:
38500   sqlite3_free(pTmpSpace);
38501   sqlite3_free(pV);
38502   sqlite3BitvecDestroy(pBitvec);
38503   return rc;
38504 }
38505 #endif /* SQLITE_OMIT_BUILTIN_TEST */
38506 
38507 /************** End of bitvec.c **********************************************/
38508 /************** Begin file pcache.c ******************************************/
38509 /*
38510 ** 2008 August 05
38511 **
38512 ** The author disclaims copyright to this source code.  In place of
38513 ** a legal notice, here is a blessing:
38514 **
38515 **    May you do good and not evil.
38516 **    May you find forgiveness for yourself and forgive others.
38517 **    May you share freely, never taking more than you give.
38518 **
38519 *************************************************************************
38520 ** This file implements that page cache.
38521 */
38522 
38523 /*
38524 ** A complete page cache is an instance of this structure.
38525 */
38526 struct PCache {
38527   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
38528   PgHdr *pSynced;                     /* Last synced page in dirty page list */
38529   int nRef;                           /* Number of referenced pages */
38530   int szCache;                        /* Configured cache size */
38531   int szPage;                         /* Size of every page in this cache */
38532   int szExtra;                        /* Size of extra space for each page */
38533   u8 bPurgeable;                      /* True if pages are on backing store */
38534   u8 eCreate;                         /* eCreate value for for xFetch() */
38535   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
38536   void *pStress;                      /* Argument to xStress */
38537   sqlite3_pcache *pCache;             /* Pluggable cache module */
38538   PgHdr *pPage1;                      /* Reference to page 1 */
38539 };
38540 
38541 /*
38542 ** Some of the assert() macros in this code are too expensive to run
38543 ** even during normal debugging.  Use them only rarely on long-running
38544 ** tests.  Enable the expensive asserts using the
38545 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
38546 */
38547 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
38548 # define expensive_assert(X)  assert(X)
38549 #else
38550 # define expensive_assert(X)
38551 #endif
38552 
38553 /********************************** Linked List Management ********************/
38554 
38555 /* Allowed values for second argument to pcacheManageDirtyList() */
38556 #define PCACHE_DIRTYLIST_REMOVE   1    /* Remove pPage from dirty list */
38557 #define PCACHE_DIRTYLIST_ADD      2    /* Add pPage to the dirty list */
38558 #define PCACHE_DIRTYLIST_FRONT    3    /* Move pPage to the front of the list */
38559 
38560 /*
38561 ** Manage pPage's participation on the dirty list.  Bits of the addRemove
38562 ** argument determines what operation to do.  The 0x01 bit means first
38563 ** remove pPage from the dirty list.  The 0x02 means add pPage back to
38564 ** the dirty list.  Doing both moves pPage to the front of the dirty list.
38565 */
38566 static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
38567   PCache *p = pPage->pCache;
38568 
38569   if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
38570     assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
38571     assert( pPage->pDirtyPrev || pPage==p->pDirty );
38572 
38573     /* Update the PCache1.pSynced variable if necessary. */
38574     if( p->pSynced==pPage ){
38575       PgHdr *pSynced = pPage->pDirtyPrev;
38576       while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
38577         pSynced = pSynced->pDirtyPrev;
38578       }
38579       p->pSynced = pSynced;
38580     }
38581 
38582     if( pPage->pDirtyNext ){
38583       pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
38584     }else{
38585       assert( pPage==p->pDirtyTail );
38586       p->pDirtyTail = pPage->pDirtyPrev;
38587     }
38588     if( pPage->pDirtyPrev ){
38589       pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
38590     }else{
38591       assert( pPage==p->pDirty );
38592       p->pDirty = pPage->pDirtyNext;
38593       if( p->pDirty==0 && p->bPurgeable ){
38594         assert( p->eCreate==1 );
38595         p->eCreate = 2;
38596       }
38597     }
38598     pPage->pDirtyNext = 0;
38599     pPage->pDirtyPrev = 0;
38600   }
38601   if( addRemove & PCACHE_DIRTYLIST_ADD ){
38602     assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
38603 
38604     pPage->pDirtyNext = p->pDirty;
38605     if( pPage->pDirtyNext ){
38606       assert( pPage->pDirtyNext->pDirtyPrev==0 );
38607       pPage->pDirtyNext->pDirtyPrev = pPage;
38608     }else{
38609       p->pDirtyTail = pPage;
38610       if( p->bPurgeable ){
38611         assert( p->eCreate==2 );
38612         p->eCreate = 1;
38613       }
38614     }
38615     p->pDirty = pPage;
38616     if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
38617       p->pSynced = pPage;
38618     }
38619   }
38620 }
38621 
38622 /*
38623 ** Wrapper around the pluggable caches xUnpin method. If the cache is
38624 ** being used for an in-memory database, this function is a no-op.
38625 */
38626 static void pcacheUnpin(PgHdr *p){
38627   if( p->pCache->bPurgeable ){
38628     if( p->pgno==1 ){
38629       p->pCache->pPage1 = 0;
38630     }
38631     sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
38632   }
38633 }
38634 
38635 /*
38636 ** Compute the number of pages of cache requested.
38637 */
38638 static int numberOfCachePages(PCache *p){
38639   if( p->szCache>=0 ){
38640     return p->szCache;
38641   }else{
38642     return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
38643   }
38644 }
38645 
38646 /*************************************************** General Interfaces ******
38647 **
38648 ** Initialize and shutdown the page cache subsystem. Neither of these
38649 ** functions are threadsafe.
38650 */
38651 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
38652   if( sqlite3GlobalConfig.pcache2.xInit==0 ){
38653     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
38654     ** built-in default page cache is used instead of the application defined
38655     ** page cache. */
38656     sqlite3PCacheSetDefault();
38657   }
38658   return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
38659 }
38660 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
38661   if( sqlite3GlobalConfig.pcache2.xShutdown ){
38662     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
38663     sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
38664   }
38665 }
38666 
38667 /*
38668 ** Return the size in bytes of a PCache object.
38669 */
38670 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
38671 
38672 /*
38673 ** Create a new PCache object. Storage space to hold the object
38674 ** has already been allocated and is passed in as the p pointer.
38675 ** The caller discovers how much space needs to be allocated by
38676 ** calling sqlite3PcacheSize().
38677 */
38678 SQLITE_PRIVATE int sqlite3PcacheOpen(
38679   int szPage,                  /* Size of every page */
38680   int szExtra,                 /* Extra space associated with each page */
38681   int bPurgeable,              /* True if pages are on backing store */
38682   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
38683   void *pStress,               /* Argument to xStress */
38684   PCache *p                    /* Preallocated space for the PCache */
38685 ){
38686   memset(p, 0, sizeof(PCache));
38687   p->szPage = 1;
38688   p->szExtra = szExtra;
38689   p->bPurgeable = bPurgeable;
38690   p->eCreate = 2;
38691   p->xStress = xStress;
38692   p->pStress = pStress;
38693   p->szCache = 100;
38694   return sqlite3PcacheSetPageSize(p, szPage);
38695 }
38696 
38697 /*
38698 ** Change the page size for PCache object. The caller must ensure that there
38699 ** are no outstanding page references when this function is called.
38700 */
38701 SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
38702   assert( pCache->nRef==0 && pCache->pDirty==0 );
38703   if( pCache->szPage ){
38704     sqlite3_pcache *pNew;
38705     pNew = sqlite3GlobalConfig.pcache2.xCreate(
38706                 szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
38707     );
38708     if( pNew==0 ) return SQLITE_NOMEM;
38709     sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
38710     if( pCache->pCache ){
38711       sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
38712     }
38713     pCache->pCache = pNew;
38714     pCache->pPage1 = 0;
38715     pCache->szPage = szPage;
38716   }
38717   return SQLITE_OK;
38718 }
38719 
38720 /*
38721 ** Try to obtain a page from the cache.
38722 **
38723 ** This routine returns a pointer to an sqlite3_pcache_page object if
38724 ** such an object is already in cache, or if a new one is created.
38725 ** This routine returns a NULL pointer if the object was not in cache
38726 ** and could not be created.
38727 **
38728 ** The createFlags should be 0 to check for existing pages and should
38729 ** be 3 (not 1, but 3) to try to create a new page.
38730 **
38731 ** If the createFlag is 0, then NULL is always returned if the page
38732 ** is not already in the cache.  If createFlag is 1, then a new page
38733 ** is created only if that can be done without spilling dirty pages
38734 ** and without exceeding the cache size limit.
38735 **
38736 ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
38737 ** initialize the sqlite3_pcache_page object and convert it into a
38738 ** PgHdr object.  The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
38739 ** routines are split this way for performance reasons. When separated
38740 ** they can both (usually) operate without having to push values to
38741 ** the stack on entry and pop them back off on exit, which saves a
38742 ** lot of pushing and popping.
38743 */
38744 SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
38745   PCache *pCache,       /* Obtain the page from this cache */
38746   Pgno pgno,            /* Page number to obtain */
38747   int createFlag        /* If true, create page if it does not exist already */
38748 ){
38749   int eCreate;
38750 
38751   assert( pCache!=0 );
38752   assert( pCache->pCache!=0 );
38753   assert( createFlag==3 || createFlag==0 );
38754   assert( pgno>0 );
38755 
38756   /* eCreate defines what to do if the page does not exist.
38757   **    0     Do not allocate a new page.  (createFlag==0)
38758   **    1     Allocate a new page if doing so is inexpensive.
38759   **          (createFlag==1 AND bPurgeable AND pDirty)
38760   **    2     Allocate a new page even it doing so is difficult.
38761   **          (createFlag==1 AND !(bPurgeable AND pDirty)
38762   */
38763   eCreate = createFlag & pCache->eCreate;
38764   assert( eCreate==0 || eCreate==1 || eCreate==2 );
38765   assert( createFlag==0 || pCache->eCreate==eCreate );
38766   assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
38767   return sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
38768 }
38769 
38770 /*
38771 ** If the sqlite3PcacheFetch() routine is unable to allocate a new
38772 ** page because new clean pages are available for reuse and the cache
38773 ** size limit has been reached, then this routine can be invoked to
38774 ** try harder to allocate a page.  This routine might invoke the stress
38775 ** callback to spill dirty pages to the journal.  It will then try to
38776 ** allocate the new page and will only fail to allocate a new page on
38777 ** an OOM error.
38778 **
38779 ** This routine should be invoked only after sqlite3PcacheFetch() fails.
38780 */
38781 SQLITE_PRIVATE int sqlite3PcacheFetchStress(
38782   PCache *pCache,                 /* Obtain the page from this cache */
38783   Pgno pgno,                      /* Page number to obtain */
38784   sqlite3_pcache_page **ppPage    /* Write result here */
38785 ){
38786   PgHdr *pPg;
38787   if( pCache->eCreate==2 ) return 0;
38788 
38789 
38790   /* Find a dirty page to write-out and recycle. First try to find a
38791   ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
38792   ** cleared), but if that is not possible settle for any other
38793   ** unreferenced dirty page.
38794   */
38795   for(pPg=pCache->pSynced;
38796       pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
38797       pPg=pPg->pDirtyPrev
38798   );
38799   pCache->pSynced = pPg;
38800   if( !pPg ){
38801     for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
38802   }
38803   if( pPg ){
38804     int rc;
38805 #ifdef SQLITE_LOG_CACHE_SPILL
38806     sqlite3_log(SQLITE_FULL,
38807                 "spill page %d making room for %d - cache used: %d/%d",
38808                 pPg->pgno, pgno,
38809                 sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
38810                 numberOfCachePages(pCache));
38811 #endif
38812     rc = pCache->xStress(pCache->pStress, pPg);
38813     if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
38814       return rc;
38815     }
38816   }
38817   *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
38818   return *ppPage==0 ? SQLITE_NOMEM : SQLITE_OK;
38819 }
38820 
38821 /*
38822 ** This is a helper routine for sqlite3PcacheFetchFinish()
38823 **
38824 ** In the uncommon case where the page being fetched has not been
38825 ** initialized, this routine is invoked to do the initialization.
38826 ** This routine is broken out into a separate function since it
38827 ** requires extra stack manipulation that can be avoided in the common
38828 ** case.
38829 */
38830 static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
38831   PCache *pCache,             /* Obtain the page from this cache */
38832   Pgno pgno,                  /* Page number obtained */
38833   sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
38834 ){
38835   PgHdr *pPgHdr;
38836   assert( pPage!=0 );
38837   pPgHdr = (PgHdr*)pPage->pExtra;
38838   assert( pPgHdr->pPage==0 );
38839  memset(pPgHdr, 0, sizeof(PgHdr));
38840   pPgHdr->pPage = pPage;
38841   pPgHdr->pData = pPage->pBuf;
38842   pPgHdr->pExtra = (void *)&pPgHdr[1];
38843   memset(pPgHdr->pExtra, 0, pCache->szExtra);
38844   pPgHdr->pCache = pCache;
38845   pPgHdr->pgno = pgno;
38846   return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
38847 }
38848 
38849 /*
38850 ** This routine converts the sqlite3_pcache_page object returned by
38851 ** sqlite3PcacheFetch() into an initialized PgHdr object.  This routine
38852 ** must be called after sqlite3PcacheFetch() in order to get a usable
38853 ** result.
38854 */
38855 SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
38856   PCache *pCache,             /* Obtain the page from this cache */
38857   Pgno pgno,                  /* Page number obtained */
38858   sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
38859 ){
38860   PgHdr *pPgHdr;
38861 
38862   if( pPage==0 ) return 0;
38863   pPgHdr = (PgHdr *)pPage->pExtra;
38864 
38865   if( !pPgHdr->pPage ){
38866     return pcacheFetchFinishWithInit(pCache, pgno, pPage);
38867   }
38868   if( 0==pPgHdr->nRef ){
38869     pCache->nRef++;
38870   }
38871   pPgHdr->nRef++;
38872   if( pgno==1 ){
38873     pCache->pPage1 = pPgHdr;
38874   }
38875   return pPgHdr;
38876 }
38877 
38878 /*
38879 ** Decrement the reference count on a page. If the page is clean and the
38880 ** reference count drops to 0, then it is made eligible for recycling.
38881 */
38882 SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
38883   assert( p->nRef>0 );
38884   p->nRef--;
38885   if( p->nRef==0 ){
38886     p->pCache->nRef--;
38887     if( (p->flags&PGHDR_DIRTY)==0 ){
38888       pcacheUnpin(p);
38889     }else if( p->pDirtyPrev!=0 ){
38890       /* Move the page to the head of the dirty list. */
38891       pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
38892     }
38893   }
38894 }
38895 
38896 /*
38897 ** Increase the reference count of a supplied page by 1.
38898 */
38899 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
38900   assert(p->nRef>0);
38901   p->nRef++;
38902 }
38903 
38904 /*
38905 ** Drop a page from the cache. There must be exactly one reference to the
38906 ** page. This function deletes that reference, so after it returns the
38907 ** page pointed to by p is invalid.
38908 */
38909 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
38910   assert( p->nRef==1 );
38911   if( p->flags&PGHDR_DIRTY ){
38912     pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
38913   }
38914   p->pCache->nRef--;
38915   if( p->pgno==1 ){
38916     p->pCache->pPage1 = 0;
38917   }
38918   sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
38919 }
38920 
38921 /*
38922 ** Make sure the page is marked as dirty. If it isn't dirty already,
38923 ** make it so.
38924 */
38925 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
38926   p->flags &= ~PGHDR_DONT_WRITE;
38927   assert( p->nRef>0 );
38928   if( 0==(p->flags & PGHDR_DIRTY) ){
38929     p->flags |= PGHDR_DIRTY;
38930     pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
38931   }
38932 }
38933 
38934 /*
38935 ** Make sure the page is marked as clean. If it isn't clean already,
38936 ** make it so.
38937 */
38938 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
38939   if( (p->flags & PGHDR_DIRTY) ){
38940     pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
38941     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
38942     if( p->nRef==0 ){
38943       pcacheUnpin(p);
38944     }
38945   }
38946 }
38947 
38948 /*
38949 ** Make every page in the cache clean.
38950 */
38951 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
38952   PgHdr *p;
38953   while( (p = pCache->pDirty)!=0 ){
38954     sqlite3PcacheMakeClean(p);
38955   }
38956 }
38957 
38958 /*
38959 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
38960 */
38961 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
38962   PgHdr *p;
38963   for(p=pCache->pDirty; p; p=p->pDirtyNext){
38964     p->flags &= ~PGHDR_NEED_SYNC;
38965   }
38966   pCache->pSynced = pCache->pDirtyTail;
38967 }
38968 
38969 /*
38970 ** Change the page number of page p to newPgno.
38971 */
38972 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
38973   PCache *pCache = p->pCache;
38974   assert( p->nRef>0 );
38975   assert( newPgno>0 );
38976   sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
38977   p->pgno = newPgno;
38978   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
38979     pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
38980   }
38981 }
38982 
38983 /*
38984 ** Drop every cache entry whose page number is greater than "pgno". The
38985 ** caller must ensure that there are no outstanding references to any pages
38986 ** other than page 1 with a page number greater than pgno.
38987 **
38988 ** If there is a reference to page 1 and the pgno parameter passed to this
38989 ** function is 0, then the data area associated with page 1 is zeroed, but
38990 ** the page object is not dropped.
38991 */
38992 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
38993   if( pCache->pCache ){
38994     PgHdr *p;
38995     PgHdr *pNext;
38996     for(p=pCache->pDirty; p; p=pNext){
38997       pNext = p->pDirtyNext;
38998       /* This routine never gets call with a positive pgno except right
38999       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
39000       ** it must be that pgno==0.
39001       */
39002       assert( p->pgno>0 );
39003       if( ALWAYS(p->pgno>pgno) ){
39004         assert( p->flags&PGHDR_DIRTY );
39005         sqlite3PcacheMakeClean(p);
39006       }
39007     }
39008     if( pgno==0 && pCache->pPage1 ){
39009       memset(pCache->pPage1->pData, 0, pCache->szPage);
39010       pgno = 1;
39011     }
39012     sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
39013   }
39014 }
39015 
39016 /*
39017 ** Close a cache.
39018 */
39019 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
39020   assert( pCache->pCache!=0 );
39021   sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
39022 }
39023 
39024 /*
39025 ** Discard the contents of the cache.
39026 */
39027 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
39028   sqlite3PcacheTruncate(pCache, 0);
39029 }
39030 
39031 /*
39032 ** Merge two lists of pages connected by pDirty and in pgno order.
39033 ** Do not both fixing the pDirtyPrev pointers.
39034 */
39035 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
39036   PgHdr result, *pTail;
39037   pTail = &result;
39038   while( pA && pB ){
39039     if( pA->pgno<pB->pgno ){
39040       pTail->pDirty = pA;
39041       pTail = pA;
39042       pA = pA->pDirty;
39043     }else{
39044       pTail->pDirty = pB;
39045       pTail = pB;
39046       pB = pB->pDirty;
39047     }
39048   }
39049   if( pA ){
39050     pTail->pDirty = pA;
39051   }else if( pB ){
39052     pTail->pDirty = pB;
39053   }else{
39054     pTail->pDirty = 0;
39055   }
39056   return result.pDirty;
39057 }
39058 
39059 /*
39060 ** Sort the list of pages in accending order by pgno.  Pages are
39061 ** connected by pDirty pointers.  The pDirtyPrev pointers are
39062 ** corrupted by this sort.
39063 **
39064 ** Since there cannot be more than 2^31 distinct pages in a database,
39065 ** there cannot be more than 31 buckets required by the merge sorter.
39066 ** One extra bucket is added to catch overflow in case something
39067 ** ever changes to make the previous sentence incorrect.
39068 */
39069 #define N_SORT_BUCKET  32
39070 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
39071   PgHdr *a[N_SORT_BUCKET], *p;
39072   int i;
39073   memset(a, 0, sizeof(a));
39074   while( pIn ){
39075     p = pIn;
39076     pIn = p->pDirty;
39077     p->pDirty = 0;
39078     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
39079       if( a[i]==0 ){
39080         a[i] = p;
39081         break;
39082       }else{
39083         p = pcacheMergeDirtyList(a[i], p);
39084         a[i] = 0;
39085       }
39086     }
39087     if( NEVER(i==N_SORT_BUCKET-1) ){
39088       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
39089       ** the input list.  But that is impossible.
39090       */
39091       a[i] = pcacheMergeDirtyList(a[i], p);
39092     }
39093   }
39094   p = a[0];
39095   for(i=1; i<N_SORT_BUCKET; i++){
39096     p = pcacheMergeDirtyList(p, a[i]);
39097   }
39098   return p;
39099 }
39100 
39101 /*
39102 ** Return a list of all dirty pages in the cache, sorted by page number.
39103 */
39104 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
39105   PgHdr *p;
39106   for(p=pCache->pDirty; p; p=p->pDirtyNext){
39107     p->pDirty = p->pDirtyNext;
39108   }
39109   return pcacheSortDirtyList(pCache->pDirty);
39110 }
39111 
39112 /*
39113 ** Return the total number of referenced pages held by the cache.
39114 */
39115 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
39116   return pCache->nRef;
39117 }
39118 
39119 /*
39120 ** Return the number of references to the page supplied as an argument.
39121 */
39122 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
39123   return p->nRef;
39124 }
39125 
39126 /*
39127 ** Return the total number of pages in the cache.
39128 */
39129 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
39130   assert( pCache->pCache!=0 );
39131   return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
39132 }
39133 
39134 #ifdef SQLITE_TEST
39135 /*
39136 ** Get the suggested cache-size value.
39137 */
39138 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
39139   return numberOfCachePages(pCache);
39140 }
39141 #endif
39142 
39143 /*
39144 ** Set the suggested cache-size value.
39145 */
39146 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
39147   assert( pCache->pCache!=0 );
39148   pCache->szCache = mxPage;
39149   sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
39150                                          numberOfCachePages(pCache));
39151 }
39152 
39153 /*
39154 ** Free up as much memory as possible from the page cache.
39155 */
39156 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
39157   assert( pCache->pCache!=0 );
39158   sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
39159 }
39160 
39161 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
39162 /*
39163 ** For all dirty pages currently in the cache, invoke the specified
39164 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
39165 ** defined.
39166 */
39167 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
39168   PgHdr *pDirty;
39169   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
39170     xIter(pDirty);
39171   }
39172 }
39173 #endif
39174 
39175 /************** End of pcache.c **********************************************/
39176 /************** Begin file pcache1.c *****************************************/
39177 /*
39178 ** 2008 November 05
39179 **
39180 ** The author disclaims copyright to this source code.  In place of
39181 ** a legal notice, here is a blessing:
39182 **
39183 **    May you do good and not evil.
39184 **    May you find forgiveness for yourself and forgive others.
39185 **    May you share freely, never taking more than you give.
39186 **
39187 *************************************************************************
39188 **
39189 ** This file implements the default page cache implementation (the
39190 ** sqlite3_pcache interface). It also contains part of the implementation
39191 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
39192 ** If the default page cache implementation is overridden, then neither of
39193 ** these two features are available.
39194 */
39195 
39196 
39197 typedef struct PCache1 PCache1;
39198 typedef struct PgHdr1 PgHdr1;
39199 typedef struct PgFreeslot PgFreeslot;
39200 typedef struct PGroup PGroup;
39201 
39202 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set
39203 ** of one or more PCaches that are able to recycle each other's unpinned
39204 ** pages when they are under memory pressure.  A PGroup is an instance of
39205 ** the following object.
39206 **
39207 ** This page cache implementation works in one of two modes:
39208 **
39209 **   (1)  Every PCache is the sole member of its own PGroup.  There is
39210 **        one PGroup per PCache.
39211 **
39212 **   (2)  There is a single global PGroup that all PCaches are a member
39213 **        of.
39214 **
39215 ** Mode 1 uses more memory (since PCache instances are not able to rob
39216 ** unused pages from other PCaches) but it also operates without a mutex,
39217 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
39218 ** threadsafe, but recycles pages more efficiently.
39219 **
39220 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
39221 ** PGroup which is the pcache1.grp global variable and its mutex is
39222 ** SQLITE_MUTEX_STATIC_LRU.
39223 */
39224 struct PGroup {
39225   sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
39226   unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
39227   unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
39228   unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
39229   unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
39230   PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
39231 };
39232 
39233 /* Each page cache is an instance of the following object.  Every
39234 ** open database file (including each in-memory database and each
39235 ** temporary or transient database) has a single page cache which
39236 ** is an instance of this object.
39237 **
39238 ** Pointers to structures of this type are cast and returned as
39239 ** opaque sqlite3_pcache* handles.
39240 */
39241 struct PCache1 {
39242   /* Cache configuration parameters. Page size (szPage) and the purgeable
39243   ** flag (bPurgeable) are set when the cache is created. nMax may be
39244   ** modified at any time by a call to the pcache1Cachesize() method.
39245   ** The PGroup mutex must be held when accessing nMax.
39246   */
39247   PGroup *pGroup;                     /* PGroup this cache belongs to */
39248   int szPage;                         /* Size of allocated pages in bytes */
39249   int szExtra;                        /* Size of extra space in bytes */
39250   int bPurgeable;                     /* True if cache is purgeable */
39251   unsigned int nMin;                  /* Minimum number of pages reserved */
39252   unsigned int nMax;                  /* Configured "cache_size" value */
39253   unsigned int n90pct;                /* nMax*9/10 */
39254   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
39255 
39256   /* Hash table of all pages. The following variables may only be accessed
39257   ** when the accessor is holding the PGroup mutex.
39258   */
39259   unsigned int nRecyclable;           /* Number of pages in the LRU list */
39260   unsigned int nPage;                 /* Total number of pages in apHash */
39261   unsigned int nHash;                 /* Number of slots in apHash[] */
39262   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
39263 };
39264 
39265 /*
39266 ** Each cache entry is represented by an instance of the following
39267 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
39268 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
39269 ** in memory.
39270 */
39271 struct PgHdr1 {
39272   sqlite3_pcache_page page;
39273   unsigned int iKey;             /* Key value (page number) */
39274   u8 isPinned;                   /* Page in use, not on the LRU list */
39275   PgHdr1 *pNext;                 /* Next in hash table chain */
39276   PCache1 *pCache;               /* Cache that currently owns this page */
39277   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
39278   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
39279 };
39280 
39281 /*
39282 ** Free slots in the allocator used to divide up the buffer provided using
39283 ** the SQLITE_CONFIG_PAGECACHE mechanism.
39284 */
39285 struct PgFreeslot {
39286   PgFreeslot *pNext;  /* Next free slot */
39287 };
39288 
39289 /*
39290 ** Global data used by this cache.
39291 */
39292 static SQLITE_WSD struct PCacheGlobal {
39293   PGroup grp;                    /* The global PGroup for mode (2) */
39294 
39295   /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
39296   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
39297   ** fixed at sqlite3_initialize() time and do not require mutex protection.
39298   ** The nFreeSlot and pFree values do require mutex protection.
39299   */
39300   int isInit;                    /* True if initialized */
39301   int szSlot;                    /* Size of each free slot */
39302   int nSlot;                     /* The number of pcache slots */
39303   int nReserve;                  /* Try to keep nFreeSlot above this */
39304   void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
39305   /* Above requires no mutex.  Use mutex below for variable that follow. */
39306   sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
39307   PgFreeslot *pFree;             /* Free page blocks */
39308   int nFreeSlot;                 /* Number of unused pcache slots */
39309   /* The following value requires a mutex to change.  We skip the mutex on
39310   ** reading because (1) most platforms read a 32-bit integer atomically and
39311   ** (2) even if an incorrect value is read, no great harm is done since this
39312   ** is really just an optimization. */
39313   int bUnderPressure;            /* True if low on PAGECACHE memory */
39314 } pcache1_g;
39315 
39316 /*
39317 ** All code in this file should access the global structure above via the
39318 ** alias "pcache1". This ensures that the WSD emulation is used when
39319 ** compiling for systems that do not support real WSD.
39320 */
39321 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
39322 
39323 /*
39324 ** Macros to enter and leave the PCache LRU mutex.
39325 */
39326 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
39327 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
39328 
39329 /******************************************************************************/
39330 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
39331 
39332 /*
39333 ** This function is called during initialization if a static buffer is
39334 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
39335 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
39336 ** enough to contain 'n' buffers of 'sz' bytes each.
39337 **
39338 ** This routine is called from sqlite3_initialize() and so it is guaranteed
39339 ** to be serialized already.  There is no need for further mutexing.
39340 */
39341 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
39342   if( pcache1.isInit ){
39343     PgFreeslot *p;
39344     sz = ROUNDDOWN8(sz);
39345     pcache1.szSlot = sz;
39346     pcache1.nSlot = pcache1.nFreeSlot = n;
39347     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
39348     pcache1.pStart = pBuf;
39349     pcache1.pFree = 0;
39350     pcache1.bUnderPressure = 0;
39351     while( n-- ){
39352       p = (PgFreeslot*)pBuf;
39353       p->pNext = pcache1.pFree;
39354       pcache1.pFree = p;
39355       pBuf = (void*)&((char*)pBuf)[sz];
39356     }
39357     pcache1.pEnd = pBuf;
39358   }
39359 }
39360 
39361 /*
39362 ** Malloc function used within this file to allocate space from the buffer
39363 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
39364 ** such buffer exists or there is no space left in it, this function falls
39365 ** back to sqlite3Malloc().
39366 **
39367 ** Multiple threads can run this routine at the same time.  Global variables
39368 ** in pcache1 need to be protected via mutex.
39369 */
39370 static void *pcache1Alloc(int nByte){
39371   void *p = 0;
39372   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
39373   sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
39374   if( nByte<=pcache1.szSlot ){
39375     sqlite3_mutex_enter(pcache1.mutex);
39376     p = (PgHdr1 *)pcache1.pFree;
39377     if( p ){
39378       pcache1.pFree = pcache1.pFree->pNext;
39379       pcache1.nFreeSlot--;
39380       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
39381       assert( pcache1.nFreeSlot>=0 );
39382       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
39383     }
39384     sqlite3_mutex_leave(pcache1.mutex);
39385   }
39386   if( p==0 ){
39387     /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
39388     ** it from sqlite3Malloc instead.
39389     */
39390     p = sqlite3Malloc(nByte);
39391 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
39392     if( p ){
39393       int sz = sqlite3MallocSize(p);
39394       sqlite3_mutex_enter(pcache1.mutex);
39395       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
39396       sqlite3_mutex_leave(pcache1.mutex);
39397     }
39398 #endif
39399     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
39400   }
39401   return p;
39402 }
39403 
39404 /*
39405 ** Free an allocated buffer obtained from pcache1Alloc().
39406 */
39407 static int pcache1Free(void *p){
39408   int nFreed = 0;
39409   if( p==0 ) return 0;
39410   if( p>=pcache1.pStart && p<pcache1.pEnd ){
39411     PgFreeslot *pSlot;
39412     sqlite3_mutex_enter(pcache1.mutex);
39413     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
39414     pSlot = (PgFreeslot*)p;
39415     pSlot->pNext = pcache1.pFree;
39416     pcache1.pFree = pSlot;
39417     pcache1.nFreeSlot++;
39418     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
39419     assert( pcache1.nFreeSlot<=pcache1.nSlot );
39420     sqlite3_mutex_leave(pcache1.mutex);
39421   }else{
39422     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
39423     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
39424     nFreed = sqlite3MallocSize(p);
39425 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
39426     sqlite3_mutex_enter(pcache1.mutex);
39427     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
39428     sqlite3_mutex_leave(pcache1.mutex);
39429 #endif
39430     sqlite3_free(p);
39431   }
39432   return nFreed;
39433 }
39434 
39435 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
39436 /*
39437 ** Return the size of a pcache allocation
39438 */
39439 static int pcache1MemSize(void *p){
39440   if( p>=pcache1.pStart && p<pcache1.pEnd ){
39441     return pcache1.szSlot;
39442   }else{
39443     int iSize;
39444     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
39445     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
39446     iSize = sqlite3MallocSize(p);
39447     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
39448     return iSize;
39449   }
39450 }
39451 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
39452 
39453 /*
39454 ** Allocate a new page object initially associated with cache pCache.
39455 */
39456 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
39457   PgHdr1 *p = 0;
39458   void *pPg;
39459 
39460   /* The group mutex must be released before pcache1Alloc() is called. This
39461   ** is because it may call sqlite3_release_memory(), which assumes that
39462   ** this mutex is not held. */
39463   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
39464   pcache1LeaveMutex(pCache->pGroup);
39465 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
39466   pPg = pcache1Alloc(pCache->szPage);
39467   p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
39468   if( !pPg || !p ){
39469     pcache1Free(pPg);
39470     sqlite3_free(p);
39471     pPg = 0;
39472   }
39473 #else
39474   pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
39475   p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
39476 #endif
39477   pcache1EnterMutex(pCache->pGroup);
39478 
39479   if( pPg ){
39480     p->page.pBuf = pPg;
39481     p->page.pExtra = &p[1];
39482     if( pCache->bPurgeable ){
39483       pCache->pGroup->nCurrentPage++;
39484     }
39485     return p;
39486   }
39487   return 0;
39488 }
39489 
39490 /*
39491 ** Free a page object allocated by pcache1AllocPage().
39492 **
39493 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
39494 ** that the current implementation happens to never call this routine
39495 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
39496 */
39497 static void pcache1FreePage(PgHdr1 *p){
39498   if( ALWAYS(p) ){
39499     PCache1 *pCache = p->pCache;
39500     assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
39501     pcache1Free(p->page.pBuf);
39502 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
39503     sqlite3_free(p);
39504 #endif
39505     if( pCache->bPurgeable ){
39506       pCache->pGroup->nCurrentPage--;
39507     }
39508   }
39509 }
39510 
39511 /*
39512 ** Malloc function used by SQLite to obtain space from the buffer configured
39513 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
39514 ** exists, this function falls back to sqlite3Malloc().
39515 */
39516 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
39517   return pcache1Alloc(sz);
39518 }
39519 
39520 /*
39521 ** Free an allocated buffer obtained from sqlite3PageMalloc().
39522 */
39523 SQLITE_PRIVATE void sqlite3PageFree(void *p){
39524   pcache1Free(p);
39525 }
39526 
39527 
39528 /*
39529 ** Return true if it desirable to avoid allocating a new page cache
39530 ** entry.
39531 **
39532 ** If memory was allocated specifically to the page cache using
39533 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
39534 ** it is desirable to avoid allocating a new page cache entry because
39535 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
39536 ** for all page cache needs and we should not need to spill the
39537 ** allocation onto the heap.
39538 **
39539 ** Or, the heap is used for all page cache memory but the heap is
39540 ** under memory pressure, then again it is desirable to avoid
39541 ** allocating a new page cache entry in order to avoid stressing
39542 ** the heap even further.
39543 */
39544 static int pcache1UnderMemoryPressure(PCache1 *pCache){
39545   if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
39546     return pcache1.bUnderPressure;
39547   }else{
39548     return sqlite3HeapNearlyFull();
39549   }
39550 }
39551 
39552 /******************************************************************************/
39553 /******** General Implementation Functions ************************************/
39554 
39555 /*
39556 ** This function is used to resize the hash table used by the cache passed
39557 ** as the first argument.
39558 **
39559 ** The PCache mutex must be held when this function is called.
39560 */
39561 static void pcache1ResizeHash(PCache1 *p){
39562   PgHdr1 **apNew;
39563   unsigned int nNew;
39564   unsigned int i;
39565 
39566   assert( sqlite3_mutex_held(p->pGroup->mutex) );
39567 
39568   nNew = p->nHash*2;
39569   if( nNew<256 ){
39570     nNew = 256;
39571   }
39572 
39573   pcache1LeaveMutex(p->pGroup);
39574   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
39575   apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
39576   if( p->nHash ){ sqlite3EndBenignMalloc(); }
39577   pcache1EnterMutex(p->pGroup);
39578   if( apNew ){
39579     for(i=0; i<p->nHash; i++){
39580       PgHdr1 *pPage;
39581       PgHdr1 *pNext = p->apHash[i];
39582       while( (pPage = pNext)!=0 ){
39583         unsigned int h = pPage->iKey % nNew;
39584         pNext = pPage->pNext;
39585         pPage->pNext = apNew[h];
39586         apNew[h] = pPage;
39587       }
39588     }
39589     sqlite3_free(p->apHash);
39590     p->apHash = apNew;
39591     p->nHash = nNew;
39592   }
39593 }
39594 
39595 /*
39596 ** This function is used internally to remove the page pPage from the
39597 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
39598 ** LRU list, then this function is a no-op.
39599 **
39600 ** The PGroup mutex must be held when this function is called.
39601 */
39602 static void pcache1PinPage(PgHdr1 *pPage){
39603   PCache1 *pCache;
39604   PGroup *pGroup;
39605 
39606   assert( pPage!=0 );
39607   assert( pPage->isPinned==0 );
39608   pCache = pPage->pCache;
39609   pGroup = pCache->pGroup;
39610   assert( pPage->pLruNext || pPage==pGroup->pLruTail );
39611   assert( pPage->pLruPrev || pPage==pGroup->pLruHead );
39612   assert( sqlite3_mutex_held(pGroup->mutex) );
39613   if( pPage->pLruPrev ){
39614     pPage->pLruPrev->pLruNext = pPage->pLruNext;
39615   }else{
39616     pGroup->pLruHead = pPage->pLruNext;
39617   }
39618   if( pPage->pLruNext ){
39619     pPage->pLruNext->pLruPrev = pPage->pLruPrev;
39620   }else{
39621     pGroup->pLruTail = pPage->pLruPrev;
39622   }
39623   pPage->pLruNext = 0;
39624   pPage->pLruPrev = 0;
39625   pPage->isPinned = 1;
39626   pCache->nRecyclable--;
39627 }
39628 
39629 
39630 /*
39631 ** Remove the page supplied as an argument from the hash table
39632 ** (PCache1.apHash structure) that it is currently stored in.
39633 **
39634 ** The PGroup mutex must be held when this function is called.
39635 */
39636 static void pcache1RemoveFromHash(PgHdr1 *pPage){
39637   unsigned int h;
39638   PCache1 *pCache = pPage->pCache;
39639   PgHdr1 **pp;
39640 
39641   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
39642   h = pPage->iKey % pCache->nHash;
39643   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
39644   *pp = (*pp)->pNext;
39645 
39646   pCache->nPage--;
39647 }
39648 
39649 /*
39650 ** If there are currently more than nMaxPage pages allocated, try
39651 ** to recycle pages to reduce the number allocated to nMaxPage.
39652 */
39653 static void pcache1EnforceMaxPage(PGroup *pGroup){
39654   assert( sqlite3_mutex_held(pGroup->mutex) );
39655   while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
39656     PgHdr1 *p = pGroup->pLruTail;
39657     assert( p->pCache->pGroup==pGroup );
39658     assert( p->isPinned==0 );
39659     pcache1PinPage(p);
39660     pcache1RemoveFromHash(p);
39661     pcache1FreePage(p);
39662   }
39663 }
39664 
39665 /*
39666 ** Discard all pages from cache pCache with a page number (key value)
39667 ** greater than or equal to iLimit. Any pinned pages that meet this
39668 ** criteria are unpinned before they are discarded.
39669 **
39670 ** The PCache mutex must be held when this function is called.
39671 */
39672 static void pcache1TruncateUnsafe(
39673   PCache1 *pCache,             /* The cache to truncate */
39674   unsigned int iLimit          /* Drop pages with this pgno or larger */
39675 ){
39676   TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
39677   unsigned int h;
39678   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
39679   for(h=0; h<pCache->nHash; h++){
39680     PgHdr1 **pp = &pCache->apHash[h];
39681     PgHdr1 *pPage;
39682     while( (pPage = *pp)!=0 ){
39683       if( pPage->iKey>=iLimit ){
39684         pCache->nPage--;
39685         *pp = pPage->pNext;
39686         if( !pPage->isPinned ) pcache1PinPage(pPage);
39687         pcache1FreePage(pPage);
39688       }else{
39689         pp = &pPage->pNext;
39690         TESTONLY( nPage++; )
39691       }
39692     }
39693   }
39694   assert( pCache->nPage==nPage );
39695 }
39696 
39697 /******************************************************************************/
39698 /******** sqlite3_pcache Methods **********************************************/
39699 
39700 /*
39701 ** Implementation of the sqlite3_pcache.xInit method.
39702 */
39703 static int pcache1Init(void *NotUsed){
39704   UNUSED_PARAMETER(NotUsed);
39705   assert( pcache1.isInit==0 );
39706   memset(&pcache1, 0, sizeof(pcache1));
39707   if( sqlite3GlobalConfig.bCoreMutex ){
39708     pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
39709     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
39710   }
39711   pcache1.grp.mxPinned = 10;
39712   pcache1.isInit = 1;
39713   return SQLITE_OK;
39714 }
39715 
39716 /*
39717 ** Implementation of the sqlite3_pcache.xShutdown method.
39718 ** Note that the static mutex allocated in xInit does
39719 ** not need to be freed.
39720 */
39721 static void pcache1Shutdown(void *NotUsed){
39722   UNUSED_PARAMETER(NotUsed);
39723   assert( pcache1.isInit!=0 );
39724   memset(&pcache1, 0, sizeof(pcache1));
39725 }
39726 
39727 /* forward declaration */
39728 static void pcache1Destroy(sqlite3_pcache *p);
39729 
39730 /*
39731 ** Implementation of the sqlite3_pcache.xCreate method.
39732 **
39733 ** Allocate a new cache.
39734 */
39735 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
39736   PCache1 *pCache;      /* The newly created page cache */
39737   PGroup *pGroup;       /* The group the new page cache will belong to */
39738   int sz;               /* Bytes of memory required to allocate the new cache */
39739 
39740   /*
39741   ** The separateCache variable is true if each PCache has its own private
39742   ** PGroup.  In other words, separateCache is true for mode (1) where no
39743   ** mutexing is required.
39744   **
39745   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
39746   **
39747   **   *  Always use a unified cache in single-threaded applications
39748   **
39749   **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
39750   **      use separate caches (mode-1)
39751   */
39752 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
39753   const int separateCache = 0;
39754 #else
39755   int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
39756 #endif
39757 
39758   assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
39759   assert( szExtra < 300 );
39760 
39761   sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
39762   pCache = (PCache1 *)sqlite3MallocZero(sz);
39763   if( pCache ){
39764     if( separateCache ){
39765       pGroup = (PGroup*)&pCache[1];
39766       pGroup->mxPinned = 10;
39767     }else{
39768       pGroup = &pcache1.grp;
39769     }
39770     pCache->pGroup = pGroup;
39771     pCache->szPage = szPage;
39772     pCache->szExtra = szExtra;
39773     pCache->bPurgeable = (bPurgeable ? 1 : 0);
39774     pcache1EnterMutex(pGroup);
39775     pcache1ResizeHash(pCache);
39776     if( bPurgeable ){
39777       pCache->nMin = 10;
39778       pGroup->nMinPage += pCache->nMin;
39779       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
39780     }
39781     pcache1LeaveMutex(pGroup);
39782     if( pCache->nHash==0 ){
39783       pcache1Destroy((sqlite3_pcache*)pCache);
39784       pCache = 0;
39785     }
39786   }
39787   return (sqlite3_pcache *)pCache;
39788 }
39789 
39790 /*
39791 ** Implementation of the sqlite3_pcache.xCachesize method.
39792 **
39793 ** Configure the cache_size limit for a cache.
39794 */
39795 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
39796   PCache1 *pCache = (PCache1 *)p;
39797   if( pCache->bPurgeable ){
39798     PGroup *pGroup = pCache->pGroup;
39799     pcache1EnterMutex(pGroup);
39800     pGroup->nMaxPage += (nMax - pCache->nMax);
39801     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
39802     pCache->nMax = nMax;
39803     pCache->n90pct = pCache->nMax*9/10;
39804     pcache1EnforceMaxPage(pGroup);
39805     pcache1LeaveMutex(pGroup);
39806   }
39807 }
39808 
39809 /*
39810 ** Implementation of the sqlite3_pcache.xShrink method.
39811 **
39812 ** Free up as much memory as possible.
39813 */
39814 static void pcache1Shrink(sqlite3_pcache *p){
39815   PCache1 *pCache = (PCache1*)p;
39816   if( pCache->bPurgeable ){
39817     PGroup *pGroup = pCache->pGroup;
39818     int savedMaxPage;
39819     pcache1EnterMutex(pGroup);
39820     savedMaxPage = pGroup->nMaxPage;
39821     pGroup->nMaxPage = 0;
39822     pcache1EnforceMaxPage(pGroup);
39823     pGroup->nMaxPage = savedMaxPage;
39824     pcache1LeaveMutex(pGroup);
39825   }
39826 }
39827 
39828 /*
39829 ** Implementation of the sqlite3_pcache.xPagecount method.
39830 */
39831 static int pcache1Pagecount(sqlite3_pcache *p){
39832   int n;
39833   PCache1 *pCache = (PCache1*)p;
39834   pcache1EnterMutex(pCache->pGroup);
39835   n = pCache->nPage;
39836   pcache1LeaveMutex(pCache->pGroup);
39837   return n;
39838 }
39839 
39840 
39841 /*
39842 ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
39843 ** in the header of the pcache1Fetch() procedure.
39844 **
39845 ** This steps are broken out into a separate procedure because they are
39846 ** usually not needed, and by avoiding the stack initialization required
39847 ** for these steps, the main pcache1Fetch() procedure can run faster.
39848 */
39849 static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
39850   PCache1 *pCache,
39851   unsigned int iKey,
39852   int createFlag
39853 ){
39854   unsigned int nPinned;
39855   PGroup *pGroup = pCache->pGroup;
39856   PgHdr1 *pPage = 0;
39857 
39858   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
39859   assert( pCache->nPage >= pCache->nRecyclable );
39860   nPinned = pCache->nPage - pCache->nRecyclable;
39861   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
39862   assert( pCache->n90pct == pCache->nMax*9/10 );
39863   if( createFlag==1 && (
39864         nPinned>=pGroup->mxPinned
39865      || nPinned>=pCache->n90pct
39866      || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
39867   )){
39868     return 0;
39869   }
39870 
39871   if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
39872   assert( pCache->nHash>0 && pCache->apHash );
39873 
39874   /* Step 4. Try to recycle a page. */
39875   if( pCache->bPurgeable && pGroup->pLruTail && (
39876          (pCache->nPage+1>=pCache->nMax)
39877       || pGroup->nCurrentPage>=pGroup->nMaxPage
39878       || pcache1UnderMemoryPressure(pCache)
39879   )){
39880     PCache1 *pOther;
39881     pPage = pGroup->pLruTail;
39882     assert( pPage->isPinned==0 );
39883     pcache1RemoveFromHash(pPage);
39884     pcache1PinPage(pPage);
39885     pOther = pPage->pCache;
39886 
39887     /* We want to verify that szPage and szExtra are the same for pOther
39888     ** and pCache.  Assert that we can verify this by comparing sums. */
39889     assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
39890     assert( pCache->szExtra<512 );
39891     assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
39892     assert( pOther->szExtra<512 );
39893 
39894     if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
39895       pcache1FreePage(pPage);
39896       pPage = 0;
39897     }else{
39898       pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
39899     }
39900   }
39901 
39902   /* Step 5. If a usable page buffer has still not been found,
39903   ** attempt to allocate a new one.
39904   */
39905   if( !pPage ){
39906     if( createFlag==1 ) sqlite3BeginBenignMalloc();
39907     pPage = pcache1AllocPage(pCache);
39908     if( createFlag==1 ) sqlite3EndBenignMalloc();
39909   }
39910 
39911   if( pPage ){
39912     unsigned int h = iKey % pCache->nHash;
39913     pCache->nPage++;
39914     pPage->iKey = iKey;
39915     pPage->pNext = pCache->apHash[h];
39916     pPage->pCache = pCache;
39917     pPage->pLruPrev = 0;
39918     pPage->pLruNext = 0;
39919     pPage->isPinned = 1;
39920     *(void **)pPage->page.pExtra = 0;
39921     pCache->apHash[h] = pPage;
39922     if( iKey>pCache->iMaxKey ){
39923       pCache->iMaxKey = iKey;
39924     }
39925   }
39926   return pPage;
39927 }
39928 
39929 /*
39930 ** Implementation of the sqlite3_pcache.xFetch method.
39931 **
39932 ** Fetch a page by key value.
39933 **
39934 ** Whether or not a new page may be allocated by this function depends on
39935 ** the value of the createFlag argument.  0 means do not allocate a new
39936 ** page.  1 means allocate a new page if space is easily available.  2
39937 ** means to try really hard to allocate a new page.
39938 **
39939 ** For a non-purgeable cache (a cache used as the storage for an in-memory
39940 ** database) there is really no difference between createFlag 1 and 2.  So
39941 ** the calling function (pcache.c) will never have a createFlag of 1 on
39942 ** a non-purgeable cache.
39943 **
39944 ** There are three different approaches to obtaining space for a page,
39945 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
39946 **
39947 **   1. Regardless of the value of createFlag, the cache is searched for a
39948 **      copy of the requested page. If one is found, it is returned.
39949 **
39950 **   2. If createFlag==0 and the page is not already in the cache, NULL is
39951 **      returned.
39952 **
39953 **   3. If createFlag is 1, and the page is not already in the cache, then
39954 **      return NULL (do not allocate a new page) if any of the following
39955 **      conditions are true:
39956 **
39957 **       (a) the number of pages pinned by the cache is greater than
39958 **           PCache1.nMax, or
39959 **
39960 **       (b) the number of pages pinned by the cache is greater than
39961 **           the sum of nMax for all purgeable caches, less the sum of
39962 **           nMin for all other purgeable caches, or
39963 **
39964 **   4. If none of the first three conditions apply and the cache is marked
39965 **      as purgeable, and if one of the following is true:
39966 **
39967 **       (a) The number of pages allocated for the cache is already
39968 **           PCache1.nMax, or
39969 **
39970 **       (b) The number of pages allocated for all purgeable caches is
39971 **           already equal to or greater than the sum of nMax for all
39972 **           purgeable caches,
39973 **
39974 **       (c) The system is under memory pressure and wants to avoid
39975 **           unnecessary pages cache entry allocations
39976 **
39977 **      then attempt to recycle a page from the LRU list. If it is the right
39978 **      size, return the recycled buffer. Otherwise, free the buffer and
39979 **      proceed to step 5.
39980 **
39981 **   5. Otherwise, allocate and return a new page buffer.
39982 */
39983 static sqlite3_pcache_page *pcache1Fetch(
39984   sqlite3_pcache *p,
39985   unsigned int iKey,
39986   int createFlag
39987 ){
39988   PCache1 *pCache = (PCache1 *)p;
39989   PgHdr1 *pPage = 0;
39990 
39991   assert( offsetof(PgHdr1,page)==0 );
39992   assert( pCache->bPurgeable || createFlag!=1 );
39993   assert( pCache->bPurgeable || pCache->nMin==0 );
39994   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
39995   assert( pCache->nMin==0 || pCache->bPurgeable );
39996   assert( pCache->nHash>0 );
39997   pcache1EnterMutex(pCache->pGroup);
39998 
39999   /* Step 1: Search the hash table for an existing entry. */
40000   pPage = pCache->apHash[iKey % pCache->nHash];
40001   while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
40002 
40003   /* Step 2: Abort if no existing page is found and createFlag is 0 */
40004   if( pPage ){
40005     if( !pPage->isPinned ) pcache1PinPage(pPage);
40006   }else if( createFlag ){
40007     /* Steps 3, 4, and 5 implemented by this subroutine */
40008     pPage = pcache1FetchStage2(pCache, iKey, createFlag);
40009   }
40010   assert( pPage==0 || pCache->iMaxKey>=iKey );
40011   pcache1LeaveMutex(pCache->pGroup);
40012   return (sqlite3_pcache_page*)pPage;
40013 }
40014 
40015 
40016 /*
40017 ** Implementation of the sqlite3_pcache.xUnpin method.
40018 **
40019 ** Mark a page as unpinned (eligible for asynchronous recycling).
40020 */
40021 static void pcache1Unpin(
40022   sqlite3_pcache *p,
40023   sqlite3_pcache_page *pPg,
40024   int reuseUnlikely
40025 ){
40026   PCache1 *pCache = (PCache1 *)p;
40027   PgHdr1 *pPage = (PgHdr1 *)pPg;
40028   PGroup *pGroup = pCache->pGroup;
40029 
40030   assert( pPage->pCache==pCache );
40031   pcache1EnterMutex(pGroup);
40032 
40033   /* It is an error to call this function if the page is already
40034   ** part of the PGroup LRU list.
40035   */
40036   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
40037   assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
40038   assert( pPage->isPinned==1 );
40039 
40040   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
40041     pcache1RemoveFromHash(pPage);
40042     pcache1FreePage(pPage);
40043   }else{
40044     /* Add the page to the PGroup LRU list. */
40045     if( pGroup->pLruHead ){
40046       pGroup->pLruHead->pLruPrev = pPage;
40047       pPage->pLruNext = pGroup->pLruHead;
40048       pGroup->pLruHead = pPage;
40049     }else{
40050       pGroup->pLruTail = pPage;
40051       pGroup->pLruHead = pPage;
40052     }
40053     pCache->nRecyclable++;
40054     pPage->isPinned = 0;
40055   }
40056 
40057   pcache1LeaveMutex(pCache->pGroup);
40058 }
40059 
40060 /*
40061 ** Implementation of the sqlite3_pcache.xRekey method.
40062 */
40063 static void pcache1Rekey(
40064   sqlite3_pcache *p,
40065   sqlite3_pcache_page *pPg,
40066   unsigned int iOld,
40067   unsigned int iNew
40068 ){
40069   PCache1 *pCache = (PCache1 *)p;
40070   PgHdr1 *pPage = (PgHdr1 *)pPg;
40071   PgHdr1 **pp;
40072   unsigned int h;
40073   assert( pPage->iKey==iOld );
40074   assert( pPage->pCache==pCache );
40075 
40076   pcache1EnterMutex(pCache->pGroup);
40077 
40078   h = iOld%pCache->nHash;
40079   pp = &pCache->apHash[h];
40080   while( (*pp)!=pPage ){
40081     pp = &(*pp)->pNext;
40082   }
40083   *pp = pPage->pNext;
40084 
40085   h = iNew%pCache->nHash;
40086   pPage->iKey = iNew;
40087   pPage->pNext = pCache->apHash[h];
40088   pCache->apHash[h] = pPage;
40089   if( iNew>pCache->iMaxKey ){
40090     pCache->iMaxKey = iNew;
40091   }
40092 
40093   pcache1LeaveMutex(pCache->pGroup);
40094 }
40095 
40096 /*
40097 ** Implementation of the sqlite3_pcache.xTruncate method.
40098 **
40099 ** Discard all unpinned pages in the cache with a page number equal to
40100 ** or greater than parameter iLimit. Any pinned pages with a page number
40101 ** equal to or greater than iLimit are implicitly unpinned.
40102 */
40103 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
40104   PCache1 *pCache = (PCache1 *)p;
40105   pcache1EnterMutex(pCache->pGroup);
40106   if( iLimit<=pCache->iMaxKey ){
40107     pcache1TruncateUnsafe(pCache, iLimit);
40108     pCache->iMaxKey = iLimit-1;
40109   }
40110   pcache1LeaveMutex(pCache->pGroup);
40111 }
40112 
40113 /*
40114 ** Implementation of the sqlite3_pcache.xDestroy method.
40115 **
40116 ** Destroy a cache allocated using pcache1Create().
40117 */
40118 static void pcache1Destroy(sqlite3_pcache *p){
40119   PCache1 *pCache = (PCache1 *)p;
40120   PGroup *pGroup = pCache->pGroup;
40121   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
40122   pcache1EnterMutex(pGroup);
40123   pcache1TruncateUnsafe(pCache, 0);
40124   assert( pGroup->nMaxPage >= pCache->nMax );
40125   pGroup->nMaxPage -= pCache->nMax;
40126   assert( pGroup->nMinPage >= pCache->nMin );
40127   pGroup->nMinPage -= pCache->nMin;
40128   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
40129   pcache1EnforceMaxPage(pGroup);
40130   pcache1LeaveMutex(pGroup);
40131   sqlite3_free(pCache->apHash);
40132   sqlite3_free(pCache);
40133 }
40134 
40135 /*
40136 ** This function is called during initialization (sqlite3_initialize()) to
40137 ** install the default pluggable cache module, assuming the user has not
40138 ** already provided an alternative.
40139 */
40140 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
40141   static const sqlite3_pcache_methods2 defaultMethods = {
40142     1,                       /* iVersion */
40143     0,                       /* pArg */
40144     pcache1Init,             /* xInit */
40145     pcache1Shutdown,         /* xShutdown */
40146     pcache1Create,           /* xCreate */
40147     pcache1Cachesize,        /* xCachesize */
40148     pcache1Pagecount,        /* xPagecount */
40149     pcache1Fetch,            /* xFetch */
40150     pcache1Unpin,            /* xUnpin */
40151     pcache1Rekey,            /* xRekey */
40152     pcache1Truncate,         /* xTruncate */
40153     pcache1Destroy,          /* xDestroy */
40154     pcache1Shrink            /* xShrink */
40155   };
40156   sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
40157 }
40158 
40159 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
40160 /*
40161 ** This function is called to free superfluous dynamically allocated memory
40162 ** held by the pager system. Memory in use by any SQLite pager allocated
40163 ** by the current thread may be sqlite3_free()ed.
40164 **
40165 ** nReq is the number of bytes of memory required. Once this much has
40166 ** been released, the function returns. The return value is the total number
40167 ** of bytes of memory released.
40168 */
40169 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
40170   int nFree = 0;
40171   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
40172   assert( sqlite3_mutex_notheld(pcache1.mutex) );
40173   if( pcache1.pStart==0 ){
40174     PgHdr1 *p;
40175     pcache1EnterMutex(&pcache1.grp);
40176     while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
40177       nFree += pcache1MemSize(p->page.pBuf);
40178 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
40179       nFree += sqlite3MemSize(p);
40180 #endif
40181       assert( p->isPinned==0 );
40182       pcache1PinPage(p);
40183       pcache1RemoveFromHash(p);
40184       pcache1FreePage(p);
40185     }
40186     pcache1LeaveMutex(&pcache1.grp);
40187   }
40188   return nFree;
40189 }
40190 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
40191 
40192 #ifdef SQLITE_TEST
40193 /*
40194 ** This function is used by test procedures to inspect the internal state
40195 ** of the global cache.
40196 */
40197 SQLITE_PRIVATE void sqlite3PcacheStats(
40198   int *pnCurrent,      /* OUT: Total number of pages cached */
40199   int *pnMax,          /* OUT: Global maximum cache size */
40200   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
40201   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
40202 ){
40203   PgHdr1 *p;
40204   int nRecyclable = 0;
40205   for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
40206     assert( p->isPinned==0 );
40207     nRecyclable++;
40208   }
40209   *pnCurrent = pcache1.grp.nCurrentPage;
40210   *pnMax = (int)pcache1.grp.nMaxPage;
40211   *pnMin = (int)pcache1.grp.nMinPage;
40212   *pnRecyclable = nRecyclable;
40213 }
40214 #endif
40215 
40216 /************** End of pcache1.c *********************************************/
40217 /************** Begin file rowset.c ******************************************/
40218 /*
40219 ** 2008 December 3
40220 **
40221 ** The author disclaims copyright to this source code.  In place of
40222 ** a legal notice, here is a blessing:
40223 **
40224 **    May you do good and not evil.
40225 **    May you find forgiveness for yourself and forgive others.
40226 **    May you share freely, never taking more than you give.
40227 **
40228 *************************************************************************
40229 **
40230 ** This module implements an object we call a "RowSet".
40231 **
40232 ** The RowSet object is a collection of rowids.  Rowids
40233 ** are inserted into the RowSet in an arbitrary order.  Inserts
40234 ** can be intermixed with tests to see if a given rowid has been
40235 ** previously inserted into the RowSet.
40236 **
40237 ** After all inserts are finished, it is possible to extract the
40238 ** elements of the RowSet in sorted order.  Once this extraction
40239 ** process has started, no new elements may be inserted.
40240 **
40241 ** Hence, the primitive operations for a RowSet are:
40242 **
40243 **    CREATE
40244 **    INSERT
40245 **    TEST
40246 **    SMALLEST
40247 **    DESTROY
40248 **
40249 ** The CREATE and DESTROY primitives are the constructor and destructor,
40250 ** obviously.  The INSERT primitive adds a new element to the RowSet.
40251 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
40252 ** extracts the least value from the RowSet.
40253 **
40254 ** The INSERT primitive might allocate additional memory.  Memory is
40255 ** allocated in chunks so most INSERTs do no allocation.  There is an
40256 ** upper bound on the size of allocated memory.  No memory is freed
40257 ** until DESTROY.
40258 **
40259 ** The TEST primitive includes a "batch" number.  The TEST primitive
40260 ** will only see elements that were inserted before the last change
40261 ** in the batch number.  In other words, if an INSERT occurs between
40262 ** two TESTs where the TESTs have the same batch nubmer, then the
40263 ** value added by the INSERT will not be visible to the second TEST.
40264 ** The initial batch number is zero, so if the very first TEST contains
40265 ** a non-zero batch number, it will see all prior INSERTs.
40266 **
40267 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
40268 ** that is attempted.
40269 **
40270 ** The cost of an INSERT is roughly constant.  (Sometimes new memory
40271 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
40272 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
40273 ** The cost of a TEST using the same batch number is O(logN).  The cost
40274 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
40275 ** primitives are constant time.  The cost of DESTROY is O(N).
40276 **
40277 ** There is an added cost of O(N) when switching between TEST and
40278 ** SMALLEST primitives.
40279 */
40280 
40281 
40282 /*
40283 ** Target size for allocation chunks.
40284 */
40285 #define ROWSET_ALLOCATION_SIZE 1024
40286 
40287 /*
40288 ** The number of rowset entries per allocation chunk.
40289 */
40290 #define ROWSET_ENTRY_PER_CHUNK  \
40291                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
40292 
40293 /*
40294 ** Each entry in a RowSet is an instance of the following object.
40295 **
40296 ** This same object is reused to store a linked list of trees of RowSetEntry
40297 ** objects.  In that alternative use, pRight points to the next entry
40298 ** in the list, pLeft points to the tree, and v is unused.  The
40299 ** RowSet.pForest value points to the head of this forest list.
40300 */
40301 struct RowSetEntry {
40302   i64 v;                        /* ROWID value for this entry */
40303   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
40304   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
40305 };
40306 
40307 /*
40308 ** RowSetEntry objects are allocated in large chunks (instances of the
40309 ** following structure) to reduce memory allocation overhead.  The
40310 ** chunks are kept on a linked list so that they can be deallocated
40311 ** when the RowSet is destroyed.
40312 */
40313 struct RowSetChunk {
40314   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
40315   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
40316 };
40317 
40318 /*
40319 ** A RowSet in an instance of the following structure.
40320 **
40321 ** A typedef of this structure if found in sqliteInt.h.
40322 */
40323 struct RowSet {
40324   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
40325   sqlite3 *db;                   /* The database connection */
40326   struct RowSetEntry *pEntry;    /* List of entries using pRight */
40327   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
40328   struct RowSetEntry *pFresh;    /* Source of new entry objects */
40329   struct RowSetEntry *pForest;   /* List of binary trees of entries */
40330   u16 nFresh;                    /* Number of objects on pFresh */
40331   u16 rsFlags;                   /* Various flags */
40332   int iBatch;                    /* Current insert batch */
40333 };
40334 
40335 /*
40336 ** Allowed values for RowSet.rsFlags
40337 */
40338 #define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
40339 #define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
40340 
40341 /*
40342 ** Turn bulk memory into a RowSet object.  N bytes of memory
40343 ** are available at pSpace.  The db pointer is used as a memory context
40344 ** for any subsequent allocations that need to occur.
40345 ** Return a pointer to the new RowSet object.
40346 **
40347 ** It must be the case that N is sufficient to make a Rowset.  If not
40348 ** an assertion fault occurs.
40349 **
40350 ** If N is larger than the minimum, use the surplus as an initial
40351 ** allocation of entries available to be filled.
40352 */
40353 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
40354   RowSet *p;
40355   assert( N >= ROUND8(sizeof(*p)) );
40356   p = pSpace;
40357   p->pChunk = 0;
40358   p->db = db;
40359   p->pEntry = 0;
40360   p->pLast = 0;
40361   p->pForest = 0;
40362   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
40363   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
40364   p->rsFlags = ROWSET_SORTED;
40365   p->iBatch = 0;
40366   return p;
40367 }
40368 
40369 /*
40370 ** Deallocate all chunks from a RowSet.  This frees all memory that
40371 ** the RowSet has allocated over its lifetime.  This routine is
40372 ** the destructor for the RowSet.
40373 */
40374 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
40375   struct RowSetChunk *pChunk, *pNextChunk;
40376   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
40377     pNextChunk = pChunk->pNextChunk;
40378     sqlite3DbFree(p->db, pChunk);
40379   }
40380   p->pChunk = 0;
40381   p->nFresh = 0;
40382   p->pEntry = 0;
40383   p->pLast = 0;
40384   p->pForest = 0;
40385   p->rsFlags = ROWSET_SORTED;
40386 }
40387 
40388 /*
40389 ** Allocate a new RowSetEntry object that is associated with the
40390 ** given RowSet.  Return a pointer to the new and completely uninitialized
40391 ** objected.
40392 **
40393 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
40394 ** routine returns NULL.
40395 */
40396 static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
40397   assert( p!=0 );
40398   if( p->nFresh==0 ){
40399     struct RowSetChunk *pNew;
40400     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
40401     if( pNew==0 ){
40402       return 0;
40403     }
40404     pNew->pNextChunk = p->pChunk;
40405     p->pChunk = pNew;
40406     p->pFresh = pNew->aEntry;
40407     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
40408   }
40409   p->nFresh--;
40410   return p->pFresh++;
40411 }
40412 
40413 /*
40414 ** Insert a new value into a RowSet.
40415 **
40416 ** The mallocFailed flag of the database connection is set if a
40417 ** memory allocation fails.
40418 */
40419 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
40420   struct RowSetEntry *pEntry;  /* The new entry */
40421   struct RowSetEntry *pLast;   /* The last prior entry */
40422 
40423   /* This routine is never called after sqlite3RowSetNext() */
40424   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
40425 
40426   pEntry = rowSetEntryAlloc(p);
40427   if( pEntry==0 ) return;
40428   pEntry->v = rowid;
40429   pEntry->pRight = 0;
40430   pLast = p->pLast;
40431   if( pLast ){
40432     if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
40433       p->rsFlags &= ~ROWSET_SORTED;
40434     }
40435     pLast->pRight = pEntry;
40436   }else{
40437     p->pEntry = pEntry;
40438   }
40439   p->pLast = pEntry;
40440 }
40441 
40442 /*
40443 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
40444 **
40445 ** The input lists are connected via pRight pointers and are
40446 ** assumed to each already be in sorted order.
40447 */
40448 static struct RowSetEntry *rowSetEntryMerge(
40449   struct RowSetEntry *pA,    /* First sorted list to be merged */
40450   struct RowSetEntry *pB     /* Second sorted list to be merged */
40451 ){
40452   struct RowSetEntry head;
40453   struct RowSetEntry *pTail;
40454 
40455   pTail = &head;
40456   while( pA && pB ){
40457     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
40458     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
40459     if( pA->v<pB->v ){
40460       pTail->pRight = pA;
40461       pA = pA->pRight;
40462       pTail = pTail->pRight;
40463     }else if( pB->v<pA->v ){
40464       pTail->pRight = pB;
40465       pB = pB->pRight;
40466       pTail = pTail->pRight;
40467     }else{
40468       pA = pA->pRight;
40469     }
40470   }
40471   if( pA ){
40472     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
40473     pTail->pRight = pA;
40474   }else{
40475     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
40476     pTail->pRight = pB;
40477   }
40478   return head.pRight;
40479 }
40480 
40481 /*
40482 ** Sort all elements on the list of RowSetEntry objects into order of
40483 ** increasing v.
40484 */
40485 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
40486   unsigned int i;
40487   struct RowSetEntry *pNext, *aBucket[40];
40488 
40489   memset(aBucket, 0, sizeof(aBucket));
40490   while( pIn ){
40491     pNext = pIn->pRight;
40492     pIn->pRight = 0;
40493     for(i=0; aBucket[i]; i++){
40494       pIn = rowSetEntryMerge(aBucket[i], pIn);
40495       aBucket[i] = 0;
40496     }
40497     aBucket[i] = pIn;
40498     pIn = pNext;
40499   }
40500   pIn = 0;
40501   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
40502     pIn = rowSetEntryMerge(pIn, aBucket[i]);
40503   }
40504   return pIn;
40505 }
40506 
40507 
40508 /*
40509 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
40510 ** Convert this tree into a linked list connected by the pRight pointers
40511 ** and return pointers to the first and last elements of the new list.
40512 */
40513 static void rowSetTreeToList(
40514   struct RowSetEntry *pIn,         /* Root of the input tree */
40515   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
40516   struct RowSetEntry **ppLast      /* Write tail of the output list here */
40517 ){
40518   assert( pIn!=0 );
40519   if( pIn->pLeft ){
40520     struct RowSetEntry *p;
40521     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
40522     p->pRight = pIn;
40523   }else{
40524     *ppFirst = pIn;
40525   }
40526   if( pIn->pRight ){
40527     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
40528   }else{
40529     *ppLast = pIn;
40530   }
40531   assert( (*ppLast)->pRight==0 );
40532 }
40533 
40534 
40535 /*
40536 ** Convert a sorted list of elements (connected by pRight) into a binary
40537 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
40538 ** node taken from the head of *ppList.  A depth of 2 means a tree with
40539 ** three nodes.  And so forth.
40540 **
40541 ** Use as many entries from the input list as required and update the
40542 ** *ppList to point to the unused elements of the list.  If the input
40543 ** list contains too few elements, then construct an incomplete tree
40544 ** and leave *ppList set to NULL.
40545 **
40546 ** Return a pointer to the root of the constructed binary tree.
40547 */
40548 static struct RowSetEntry *rowSetNDeepTree(
40549   struct RowSetEntry **ppList,
40550   int iDepth
40551 ){
40552   struct RowSetEntry *p;         /* Root of the new tree */
40553   struct RowSetEntry *pLeft;     /* Left subtree */
40554   if( *ppList==0 ){
40555     return 0;
40556   }
40557   if( iDepth==1 ){
40558     p = *ppList;
40559     *ppList = p->pRight;
40560     p->pLeft = p->pRight = 0;
40561     return p;
40562   }
40563   pLeft = rowSetNDeepTree(ppList, iDepth-1);
40564   p = *ppList;
40565   if( p==0 ){
40566     return pLeft;
40567   }
40568   p->pLeft = pLeft;
40569   *ppList = p->pRight;
40570   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
40571   return p;
40572 }
40573 
40574 /*
40575 ** Convert a sorted list of elements into a binary tree. Make the tree
40576 ** as deep as it needs to be in order to contain the entire list.
40577 */
40578 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
40579   int iDepth;           /* Depth of the tree so far */
40580   struct RowSetEntry *p;       /* Current tree root */
40581   struct RowSetEntry *pLeft;   /* Left subtree */
40582 
40583   assert( pList!=0 );
40584   p = pList;
40585   pList = p->pRight;
40586   p->pLeft = p->pRight = 0;
40587   for(iDepth=1; pList; iDepth++){
40588     pLeft = p;
40589     p = pList;
40590     pList = p->pRight;
40591     p->pLeft = pLeft;
40592     p->pRight = rowSetNDeepTree(&pList, iDepth);
40593   }
40594   return p;
40595 }
40596 
40597 /*
40598 ** Take all the entries on p->pEntry and on the trees in p->pForest and
40599 ** sort them all together into one big ordered list on p->pEntry.
40600 **
40601 ** This routine should only be called once in the life of a RowSet.
40602 */
40603 static void rowSetToList(RowSet *p){
40604 
40605   /* This routine is called only once */
40606   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
40607 
40608   if( (p->rsFlags & ROWSET_SORTED)==0 ){
40609     p->pEntry = rowSetEntrySort(p->pEntry);
40610   }
40611 
40612   /* While this module could theoretically support it, sqlite3RowSetNext()
40613   ** is never called after sqlite3RowSetText() for the same RowSet.  So
40614   ** there is never a forest to deal with.  Should this change, simply
40615   ** remove the assert() and the #if 0. */
40616   assert( p->pForest==0 );
40617 #if 0
40618   while( p->pForest ){
40619     struct RowSetEntry *pTree = p->pForest->pLeft;
40620     if( pTree ){
40621       struct RowSetEntry *pHead, *pTail;
40622       rowSetTreeToList(pTree, &pHead, &pTail);
40623       p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
40624     }
40625     p->pForest = p->pForest->pRight;
40626   }
40627 #endif
40628   p->rsFlags |= ROWSET_NEXT;  /* Verify this routine is never called again */
40629 }
40630 
40631 /*
40632 ** Extract the smallest element from the RowSet.
40633 ** Write the element into *pRowid.  Return 1 on success.  Return
40634 ** 0 if the RowSet is already empty.
40635 **
40636 ** After this routine has been called, the sqlite3RowSetInsert()
40637 ** routine may not be called again.
40638 */
40639 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
40640   assert( p!=0 );
40641 
40642   /* Merge the forest into a single sorted list on first call */
40643   if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
40644 
40645   /* Return the next entry on the list */
40646   if( p->pEntry ){
40647     *pRowid = p->pEntry->v;
40648     p->pEntry = p->pEntry->pRight;
40649     if( p->pEntry==0 ){
40650       sqlite3RowSetClear(p);
40651     }
40652     return 1;
40653   }else{
40654     return 0;
40655   }
40656 }
40657 
40658 /*
40659 ** Check to see if element iRowid was inserted into the rowset as
40660 ** part of any insert batch prior to iBatch.  Return 1 or 0.
40661 **
40662 ** If this is the first test of a new batch and if there exist entries
40663 ** on pRowSet->pEntry, then sort those entries into the forest at
40664 ** pRowSet->pForest so that they can be tested.
40665 */
40666 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
40667   struct RowSetEntry *p, *pTree;
40668 
40669   /* This routine is never called after sqlite3RowSetNext() */
40670   assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
40671 
40672   /* Sort entries into the forest on the first test of a new batch
40673   */
40674   if( iBatch!=pRowSet->iBatch ){
40675     p = pRowSet->pEntry;
40676     if( p ){
40677       struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
40678       if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
40679         p = rowSetEntrySort(p);
40680       }
40681       for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
40682         ppPrevTree = &pTree->pRight;
40683         if( pTree->pLeft==0 ){
40684           pTree->pLeft = rowSetListToTree(p);
40685           break;
40686         }else{
40687           struct RowSetEntry *pAux, *pTail;
40688           rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
40689           pTree->pLeft = 0;
40690           p = rowSetEntryMerge(pAux, p);
40691         }
40692       }
40693       if( pTree==0 ){
40694         *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
40695         if( pTree ){
40696           pTree->v = 0;
40697           pTree->pRight = 0;
40698           pTree->pLeft = rowSetListToTree(p);
40699         }
40700       }
40701       pRowSet->pEntry = 0;
40702       pRowSet->pLast = 0;
40703       pRowSet->rsFlags |= ROWSET_SORTED;
40704     }
40705     pRowSet->iBatch = iBatch;
40706   }
40707 
40708   /* Test to see if the iRowid value appears anywhere in the forest.
40709   ** Return 1 if it does and 0 if not.
40710   */
40711   for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
40712     p = pTree->pLeft;
40713     while( p ){
40714       if( p->v<iRowid ){
40715         p = p->pRight;
40716       }else if( p->v>iRowid ){
40717         p = p->pLeft;
40718       }else{
40719         return 1;
40720       }
40721     }
40722   }
40723   return 0;
40724 }
40725 
40726 /************** End of rowset.c **********************************************/
40727 /************** Begin file pager.c *******************************************/
40728 /*
40729 ** 2001 September 15
40730 **
40731 ** The author disclaims copyright to this source code.  In place of
40732 ** a legal notice, here is a blessing:
40733 **
40734 **    May you do good and not evil.
40735 **    May you find forgiveness for yourself and forgive others.
40736 **    May you share freely, never taking more than you give.
40737 **
40738 *************************************************************************
40739 ** This is the implementation of the page cache subsystem or "pager".
40740 **
40741 ** The pager is used to access a database disk file.  It implements
40742 ** atomic commit and rollback through the use of a journal file that
40743 ** is separate from the database file.  The pager also implements file
40744 ** locking to prevent two processes from writing the same database
40745 ** file simultaneously, or one process from reading the database while
40746 ** another is writing.
40747 */
40748 #ifndef SQLITE_OMIT_DISKIO
40749 /************** Include wal.h in the middle of pager.c ***********************/
40750 /************** Begin file wal.h *********************************************/
40751 /*
40752 ** 2010 February 1
40753 **
40754 ** The author disclaims copyright to this source code.  In place of
40755 ** a legal notice, here is a blessing:
40756 **
40757 **    May you do good and not evil.
40758 **    May you find forgiveness for yourself and forgive others.
40759 **    May you share freely, never taking more than you give.
40760 **
40761 *************************************************************************
40762 ** This header file defines the interface to the write-ahead logging
40763 ** system. Refer to the comments below and the header comment attached to
40764 ** the implementation of each function in log.c for further details.
40765 */
40766 
40767 #ifndef _WAL_H_
40768 #define _WAL_H_
40769 
40770 
40771 /* Additional values that can be added to the sync_flags argument of
40772 ** sqlite3WalFrames():
40773 */
40774 #define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
40775 #define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
40776 
40777 #ifdef SQLITE_OMIT_WAL
40778 # define sqlite3WalOpen(x,y,z)                   0
40779 # define sqlite3WalLimit(x,y)
40780 # define sqlite3WalClose(w,x,y,z)                0
40781 # define sqlite3WalBeginReadTransaction(y,z)     0
40782 # define sqlite3WalEndReadTransaction(z)
40783 # define sqlite3WalDbsize(y)                     0
40784 # define sqlite3WalBeginWriteTransaction(y)      0
40785 # define sqlite3WalEndWriteTransaction(x)        0
40786 # define sqlite3WalUndo(x,y,z)                   0
40787 # define sqlite3WalSavepoint(y,z)
40788 # define sqlite3WalSavepointUndo(y,z)            0
40789 # define sqlite3WalFrames(u,v,w,x,y,z)           0
40790 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
40791 # define sqlite3WalCallback(z)                   0
40792 # define sqlite3WalExclusiveMode(y,z)            0
40793 # define sqlite3WalHeapMemory(z)                 0
40794 # define sqlite3WalFramesize(z)                  0
40795 # define sqlite3WalFindFrame(x,y,z)              0
40796 #else
40797 
40798 #define WAL_SAVEPOINT_NDATA 4
40799 
40800 /* Connection to a write-ahead log (WAL) file.
40801 ** There is one object of this type for each pager.
40802 */
40803 typedef struct Wal Wal;
40804 
40805 /* Open and close a connection to a write-ahead log. */
40806 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
40807 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
40808 
40809 /* Set the limiting size of a WAL file. */
40810 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
40811 
40812 /* Used by readers to open (lock) and close (unlock) a snapshot.  A
40813 ** snapshot is like a read-transaction.  It is the state of the database
40814 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
40815 ** preserves the current state even if the other threads or processes
40816 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
40817 ** transaction and releases the lock.
40818 */
40819 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
40820 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
40821 
40822 /* Read a page from the write-ahead log, if it is present. */
40823 SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
40824 SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
40825 
40826 /* If the WAL is not empty, return the size of the database. */
40827 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
40828 
40829 /* Obtain or release the WRITER lock. */
40830 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
40831 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
40832 
40833 /* Undo any frames written (but not committed) to the log */
40834 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
40835 
40836 /* Return an integer that records the current (uncommitted) write
40837 ** position in the WAL */
40838 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
40839 
40840 /* Move the write position of the WAL back to iFrame.  Called in
40841 ** response to a ROLLBACK TO command. */
40842 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
40843 
40844 /* Write a frame or frames to the log. */
40845 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
40846 
40847 /* Copy pages from the log to the database file */
40848 SQLITE_PRIVATE int sqlite3WalCheckpoint(
40849   Wal *pWal,                      /* Write-ahead log connection */
40850   int eMode,                      /* One of PASSIVE, FULL and RESTART */
40851   int (*xBusy)(void*),            /* Function to call when busy */
40852   void *pBusyArg,                 /* Context argument for xBusyHandler */
40853   int sync_flags,                 /* Flags to sync db file with (or 0) */
40854   int nBuf,                       /* Size of buffer nBuf */
40855   u8 *zBuf,                       /* Temporary buffer to use */
40856   int *pnLog,                     /* OUT: Number of frames in WAL */
40857   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
40858 );
40859 
40860 /* Return the value to pass to a sqlite3_wal_hook callback, the
40861 ** number of frames in the WAL at the point of the last commit since
40862 ** sqlite3WalCallback() was called.  If no commits have occurred since
40863 ** the last call, then return 0.
40864 */
40865 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
40866 
40867 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
40868 ** by the pager layer on the database file.
40869 */
40870 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
40871 
40872 /* Return true if the argument is non-NULL and the WAL module is using
40873 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
40874 ** WAL module is using shared-memory, return false.
40875 */
40876 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
40877 
40878 #ifdef SQLITE_ENABLE_ZIPVFS
40879 /* If the WAL file is not empty, return the number of bytes of content
40880 ** stored in each frame (i.e. the db page-size when the WAL was created).
40881 */
40882 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
40883 #endif
40884 
40885 #endif /* ifndef SQLITE_OMIT_WAL */
40886 #endif /* _WAL_H_ */
40887 
40888 /************** End of wal.h *************************************************/
40889 /************** Continuing where we left off in pager.c **********************/
40890 
40891 
40892 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
40893 **
40894 ** This comment block describes invariants that hold when using a rollback
40895 ** journal.  These invariants do not apply for journal_mode=WAL,
40896 ** journal_mode=MEMORY, or journal_mode=OFF.
40897 **
40898 ** Within this comment block, a page is deemed to have been synced
40899 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
40900 ** Otherwise, the page is not synced until the xSync method of the VFS
40901 ** is called successfully on the file containing the page.
40902 **
40903 ** Definition:  A page of the database file is said to be "overwriteable" if
40904 ** one or more of the following are true about the page:
40905 **
40906 **     (a)  The original content of the page as it was at the beginning of
40907 **          the transaction has been written into the rollback journal and
40908 **          synced.
40909 **
40910 **     (b)  The page was a freelist leaf page at the start of the transaction.
40911 **
40912 **     (c)  The page number is greater than the largest page that existed in
40913 **          the database file at the start of the transaction.
40914 **
40915 ** (1) A page of the database file is never overwritten unless one of the
40916 **     following are true:
40917 **
40918 **     (a) The page and all other pages on the same sector are overwriteable.
40919 **
40920 **     (b) The atomic page write optimization is enabled, and the entire
40921 **         transaction other than the update of the transaction sequence
40922 **         number consists of a single page change.
40923 **
40924 ** (2) The content of a page written into the rollback journal exactly matches
40925 **     both the content in the database when the rollback journal was written
40926 **     and the content in the database at the beginning of the current
40927 **     transaction.
40928 **
40929 ** (3) Writes to the database file are an integer multiple of the page size
40930 **     in length and are aligned on a page boundary.
40931 **
40932 ** (4) Reads from the database file are either aligned on a page boundary and
40933 **     an integer multiple of the page size in length or are taken from the
40934 **     first 100 bytes of the database file.
40935 **
40936 ** (5) All writes to the database file are synced prior to the rollback journal
40937 **     being deleted, truncated, or zeroed.
40938 **
40939 ** (6) If a master journal file is used, then all writes to the database file
40940 **     are synced prior to the master journal being deleted.
40941 **
40942 ** Definition: Two databases (or the same database at two points it time)
40943 ** are said to be "logically equivalent" if they give the same answer to
40944 ** all queries.  Note in particular the content of freelist leaf
40945 ** pages can be changed arbitrarily without affecting the logical equivalence
40946 ** of the database.
40947 **
40948 ** (7) At any time, if any subset, including the empty set and the total set,
40949 **     of the unsynced changes to a rollback journal are removed and the
40950 **     journal is rolled back, the resulting database file will be logically
40951 **     equivalent to the database file at the beginning of the transaction.
40952 **
40953 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
40954 **     is called to restore the database file to the same size it was at
40955 **     the beginning of the transaction.  (In some VFSes, the xTruncate
40956 **     method is a no-op, but that does not change the fact the SQLite will
40957 **     invoke it.)
40958 **
40959 ** (9) Whenever the database file is modified, at least one bit in the range
40960 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
40961 **     the EXCLUSIVE lock, thus signaling other connections on the same
40962 **     database to flush their caches.
40963 **
40964 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
40965 **      than one billion transactions.
40966 **
40967 ** (11) A database file is well-formed at the beginning and at the conclusion
40968 **      of every transaction.
40969 **
40970 ** (12) An EXCLUSIVE lock is held on the database file when writing to
40971 **      the database file.
40972 **
40973 ** (13) A SHARED lock is held on the database file while reading any
40974 **      content out of the database file.
40975 **
40976 ******************************************************************************/
40977 
40978 /*
40979 ** Macros for troubleshooting.  Normally turned off
40980 */
40981 #if 0
40982 int sqlite3PagerTrace=1;  /* True to enable tracing */
40983 #define sqlite3DebugPrintf printf
40984 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
40985 #else
40986 #define PAGERTRACE(X)
40987 #endif
40988 
40989 /*
40990 ** The following two macros are used within the PAGERTRACE() macros above
40991 ** to print out file-descriptors.
40992 **
40993 ** PAGERID() takes a pointer to a Pager struct as its argument. The
40994 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
40995 ** struct as its argument.
40996 */
40997 #define PAGERID(p) ((int)(p->fd))
40998 #define FILEHANDLEID(fd) ((int)fd)
40999 
41000 /*
41001 ** The Pager.eState variable stores the current 'state' of a pager. A
41002 ** pager may be in any one of the seven states shown in the following
41003 ** state diagram.
41004 **
41005 **                            OPEN <------+------+
41006 **                              |         |      |
41007 **                              V         |      |
41008 **               +---------> READER-------+      |
41009 **               |              |                |
41010 **               |              V                |
41011 **               |<-------WRITER_LOCKED------> ERROR
41012 **               |              |                ^
41013 **               |              V                |
41014 **               |<------WRITER_CACHEMOD-------->|
41015 **               |              |                |
41016 **               |              V                |
41017 **               |<-------WRITER_DBMOD---------->|
41018 **               |              |                |
41019 **               |              V                |
41020 **               +<------WRITER_FINISHED-------->+
41021 **
41022 **
41023 ** List of state transitions and the C [function] that performs each:
41024 **
41025 **   OPEN              -> READER              [sqlite3PagerSharedLock]
41026 **   READER            -> OPEN                [pager_unlock]
41027 **
41028 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
41029 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
41030 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
41031 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
41032 **   WRITER_***        -> READER              [pager_end_transaction]
41033 **
41034 **   WRITER_***        -> ERROR               [pager_error]
41035 **   ERROR             -> OPEN                [pager_unlock]
41036 **
41037 **
41038 **  OPEN:
41039 **
41040 **    The pager starts up in this state. Nothing is guaranteed in this
41041 **    state - the file may or may not be locked and the database size is
41042 **    unknown. The database may not be read or written.
41043 **
41044 **    * No read or write transaction is active.
41045 **    * Any lock, or no lock at all, may be held on the database file.
41046 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
41047 **
41048 **  READER:
41049 **
41050 **    In this state all the requirements for reading the database in
41051 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
41052 **    was) in exclusive-locking mode, a user-level read transaction is
41053 **    open. The database size is known in this state.
41054 **
41055 **    A connection running with locking_mode=normal enters this state when
41056 **    it opens a read-transaction on the database and returns to state
41057 **    OPEN after the read-transaction is completed. However a connection
41058 **    running in locking_mode=exclusive (including temp databases) remains in
41059 **    this state even after the read-transaction is closed. The only way
41060 **    a locking_mode=exclusive connection can transition from READER to OPEN
41061 **    is via the ERROR state (see below).
41062 **
41063 **    * A read transaction may be active (but a write-transaction cannot).
41064 **    * A SHARED or greater lock is held on the database file.
41065 **    * The dbSize variable may be trusted (even if a user-level read
41066 **      transaction is not active). The dbOrigSize and dbFileSize variables
41067 **      may not be trusted at this point.
41068 **    * If the database is a WAL database, then the WAL connection is open.
41069 **    * Even if a read-transaction is not open, it is guaranteed that
41070 **      there is no hot-journal in the file-system.
41071 **
41072 **  WRITER_LOCKED:
41073 **
41074 **    The pager moves to this state from READER when a write-transaction
41075 **    is first opened on the database. In WRITER_LOCKED state, all locks
41076 **    required to start a write-transaction are held, but no actual
41077 **    modifications to the cache or database have taken place.
41078 **
41079 **    In rollback mode, a RESERVED or (if the transaction was opened with
41080 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
41081 **    moving to this state, but the journal file is not written to or opened
41082 **    to in this state. If the transaction is committed or rolled back while
41083 **    in WRITER_LOCKED state, all that is required is to unlock the database
41084 **    file.
41085 **
41086 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
41087 **    If the connection is running with locking_mode=exclusive, an attempt
41088 **    is made to obtain an EXCLUSIVE lock on the database file.
41089 **
41090 **    * A write transaction is active.
41091 **    * If the connection is open in rollback-mode, a RESERVED or greater
41092 **      lock is held on the database file.
41093 **    * If the connection is open in WAL-mode, a WAL write transaction
41094 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
41095 **      called).
41096 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
41097 **    * The contents of the pager cache have not been modified.
41098 **    * The journal file may or may not be open.
41099 **    * Nothing (not even the first header) has been written to the journal.
41100 **
41101 **  WRITER_CACHEMOD:
41102 **
41103 **    A pager moves from WRITER_LOCKED state to this state when a page is
41104 **    first modified by the upper layer. In rollback mode the journal file
41105 **    is opened (if it is not already open) and a header written to the
41106 **    start of it. The database file on disk has not been modified.
41107 **
41108 **    * A write transaction is active.
41109 **    * A RESERVED or greater lock is held on the database file.
41110 **    * The journal file is open and the first header has been written
41111 **      to it, but the header has not been synced to disk.
41112 **    * The contents of the page cache have been modified.
41113 **
41114 **  WRITER_DBMOD:
41115 **
41116 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
41117 **    when it modifies the contents of the database file. WAL connections
41118 **    never enter this state (since they do not modify the database file,
41119 **    just the log file).
41120 **
41121 **    * A write transaction is active.
41122 **    * An EXCLUSIVE or greater lock is held on the database file.
41123 **    * The journal file is open and the first header has been written
41124 **      and synced to disk.
41125 **    * The contents of the page cache have been modified (and possibly
41126 **      written to disk).
41127 **
41128 **  WRITER_FINISHED:
41129 **
41130 **    It is not possible for a WAL connection to enter this state.
41131 **
41132 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
41133 **    state after the entire transaction has been successfully written into the
41134 **    database file. In this state the transaction may be committed simply
41135 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is
41136 **    not possible to modify the database further. At this point, the upper
41137 **    layer must either commit or rollback the transaction.
41138 **
41139 **    * A write transaction is active.
41140 **    * An EXCLUSIVE or greater lock is held on the database file.
41141 **    * All writing and syncing of journal and database data has finished.
41142 **      If no error occurred, all that remains is to finalize the journal to
41143 **      commit the transaction. If an error did occur, the caller will need
41144 **      to rollback the transaction.
41145 **
41146 **  ERROR:
41147 **
41148 **    The ERROR state is entered when an IO or disk-full error (including
41149 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
41150 **    difficult to be sure that the in-memory pager state (cache contents,
41151 **    db size etc.) are consistent with the contents of the file-system.
41152 **
41153 **    Temporary pager files may enter the ERROR state, but in-memory pagers
41154 **    cannot.
41155 **
41156 **    For example, if an IO error occurs while performing a rollback,
41157 **    the contents of the page-cache may be left in an inconsistent state.
41158 **    At this point it would be dangerous to change back to READER state
41159 **    (as usually happens after a rollback). Any subsequent readers might
41160 **    report database corruption (due to the inconsistent cache), and if
41161 **    they upgrade to writers, they may inadvertently corrupt the database
41162 **    file. To avoid this hazard, the pager switches into the ERROR state
41163 **    instead of READER following such an error.
41164 **
41165 **    Once it has entered the ERROR state, any attempt to use the pager
41166 **    to read or write data returns an error. Eventually, once all
41167 **    outstanding transactions have been abandoned, the pager is able to
41168 **    transition back to OPEN state, discarding the contents of the
41169 **    page-cache and any other in-memory state at the same time. Everything
41170 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
41171 **    when a read-transaction is next opened on the pager (transitioning
41172 **    the pager into READER state). At that point the system has recovered
41173 **    from the error.
41174 **
41175 **    Specifically, the pager jumps into the ERROR state if:
41176 **
41177 **      1. An error occurs while attempting a rollback. This happens in
41178 **         function sqlite3PagerRollback().
41179 **
41180 **      2. An error occurs while attempting to finalize a journal file
41181 **         following a commit in function sqlite3PagerCommitPhaseTwo().
41182 **
41183 **      3. An error occurs while attempting to write to the journal or
41184 **         database file in function pagerStress() in order to free up
41185 **         memory.
41186 **
41187 **    In other cases, the error is returned to the b-tree layer. The b-tree
41188 **    layer then attempts a rollback operation. If the error condition
41189 **    persists, the pager enters the ERROR state via condition (1) above.
41190 **
41191 **    Condition (3) is necessary because it can be triggered by a read-only
41192 **    statement executed within a transaction. In this case, if the error
41193 **    code were simply returned to the user, the b-tree layer would not
41194 **    automatically attempt a rollback, as it assumes that an error in a
41195 **    read-only statement cannot leave the pager in an internally inconsistent
41196 **    state.
41197 **
41198 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
41199 **    * There are one or more outstanding references to pages (after the
41200 **      last reference is dropped the pager should move back to OPEN state).
41201 **    * The pager is not an in-memory pager.
41202 **
41203 **
41204 ** Notes:
41205 **
41206 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
41207 **     connection is open in WAL mode. A WAL connection is always in one
41208 **     of the first four states.
41209 **
41210 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
41211 **     state. There are two exceptions: immediately after exclusive-mode has
41212 **     been turned on (and before any read or write transactions are
41213 **     executed), and when the pager is leaving the "error state".
41214 **
41215 **   * See also: assert_pager_state().
41216 */
41217 #define PAGER_OPEN                  0
41218 #define PAGER_READER                1
41219 #define PAGER_WRITER_LOCKED         2
41220 #define PAGER_WRITER_CACHEMOD       3
41221 #define PAGER_WRITER_DBMOD          4
41222 #define PAGER_WRITER_FINISHED       5
41223 #define PAGER_ERROR                 6
41224 
41225 /*
41226 ** The Pager.eLock variable is almost always set to one of the
41227 ** following locking-states, according to the lock currently held on
41228 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
41229 ** This variable is kept up to date as locks are taken and released by
41230 ** the pagerLockDb() and pagerUnlockDb() wrappers.
41231 **
41232 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
41233 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
41234 ** the operation was successful. In these circumstances pagerLockDb() and
41235 ** pagerUnlockDb() take a conservative approach - eLock is always updated
41236 ** when unlocking the file, and only updated when locking the file if the
41237 ** VFS call is successful. This way, the Pager.eLock variable may be set
41238 ** to a less exclusive (lower) value than the lock that is actually held
41239 ** at the system level, but it is never set to a more exclusive value.
41240 **
41241 ** This is usually safe. If an xUnlock fails or appears to fail, there may
41242 ** be a few redundant xLock() calls or a lock may be held for longer than
41243 ** required, but nothing really goes wrong.
41244 **
41245 ** The exception is when the database file is unlocked as the pager moves
41246 ** from ERROR to OPEN state. At this point there may be a hot-journal file
41247 ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
41248 ** transition, by the same pager or any other). If the call to xUnlock()
41249 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
41250 ** can confuse the call to xCheckReservedLock() call made later as part
41251 ** of hot-journal detection.
41252 **
41253 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
41254 ** lock held by this process or any others". So xCheckReservedLock may
41255 ** return true because the caller itself is holding an EXCLUSIVE lock (but
41256 ** doesn't know it because of a previous error in xUnlock). If this happens
41257 ** a hot-journal may be mistaken for a journal being created by an active
41258 ** transaction in another process, causing SQLite to read from the database
41259 ** without rolling it back.
41260 **
41261 ** To work around this, if a call to xUnlock() fails when unlocking the
41262 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
41263 ** is only changed back to a real locking state after a successful call
41264 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
41265 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
41266 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
41267 ** lock on the database file before attempting to roll it back. See function
41268 ** PagerSharedLock() for more detail.
41269 **
41270 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
41271 ** PAGER_OPEN state.
41272 */
41273 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
41274 
41275 /*
41276 ** A macro used for invoking the codec if there is one
41277 */
41278 #ifdef SQLITE_HAS_CODEC
41279 # define CODEC1(P,D,N,X,E) \
41280     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
41281 # define CODEC2(P,D,N,X,E,O) \
41282     if( P->xCodec==0 ){ O=(char*)D; }else \
41283     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
41284 #else
41285 # define CODEC1(P,D,N,X,E)   /* NO-OP */
41286 # define CODEC2(P,D,N,X,E,O) O=(char*)D
41287 #endif
41288 
41289 /*
41290 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
41291 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
41292 ** This could conceivably cause corruption following a power failure on
41293 ** such a system. This is currently an undocumented limit.
41294 */
41295 #define MAX_SECTOR_SIZE 0x10000
41296 
41297 /*
41298 ** An instance of the following structure is allocated for each active
41299 ** savepoint and statement transaction in the system. All such structures
41300 ** are stored in the Pager.aSavepoint[] array, which is allocated and
41301 ** resized using sqlite3Realloc().
41302 **
41303 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
41304 ** set to 0. If a journal-header is written into the main journal while
41305 ** the savepoint is active, then iHdrOffset is set to the byte offset
41306 ** immediately following the last journal record written into the main
41307 ** journal before the journal-header. This is required during savepoint
41308 ** rollback (see pagerPlaybackSavepoint()).
41309 */
41310 typedef struct PagerSavepoint PagerSavepoint;
41311 struct PagerSavepoint {
41312   i64 iOffset;                 /* Starting offset in main journal */
41313   i64 iHdrOffset;              /* See above */
41314   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
41315   Pgno nOrig;                  /* Original number of pages in file */
41316   Pgno iSubRec;                /* Index of first record in sub-journal */
41317 #ifndef SQLITE_OMIT_WAL
41318   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
41319 #endif
41320 };
41321 
41322 /*
41323 ** Bits of the Pager.doNotSpill flag.  See further description below.
41324 */
41325 #define SPILLFLAG_OFF         0x01      /* Never spill cache.  Set via pragma */
41326 #define SPILLFLAG_ROLLBACK    0x02      /* Current rolling back, so do not spill */
41327 #define SPILLFLAG_NOSYNC      0x04      /* Spill is ok, but do not sync */
41328 
41329 /*
41330 ** An open page cache is an instance of struct Pager. A description of
41331 ** some of the more important member variables follows:
41332 **
41333 ** eState
41334 **
41335 **   The current 'state' of the pager object. See the comment and state
41336 **   diagram above for a description of the pager state.
41337 **
41338 ** eLock
41339 **
41340 **   For a real on-disk database, the current lock held on the database file -
41341 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
41342 **
41343 **   For a temporary or in-memory database (neither of which require any
41344 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
41345 **   databases always have Pager.exclusiveMode==1, this tricks the pager
41346 **   logic into thinking that it already has all the locks it will ever
41347 **   need (and no reason to release them).
41348 **
41349 **   In some (obscure) circumstances, this variable may also be set to
41350 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
41351 **   details.
41352 **
41353 ** changeCountDone
41354 **
41355 **   This boolean variable is used to make sure that the change-counter
41356 **   (the 4-byte header field at byte offset 24 of the database file) is
41357 **   not updated more often than necessary.
41358 **
41359 **   It is set to true when the change-counter field is updated, which
41360 **   can only happen if an exclusive lock is held on the database file.
41361 **   It is cleared (set to false) whenever an exclusive lock is
41362 **   relinquished on the database file. Each time a transaction is committed,
41363 **   The changeCountDone flag is inspected. If it is true, the work of
41364 **   updating the change-counter is omitted for the current transaction.
41365 **
41366 **   This mechanism means that when running in exclusive mode, a connection
41367 **   need only update the change-counter once, for the first transaction
41368 **   committed.
41369 **
41370 ** setMaster
41371 **
41372 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
41373 **   (or may not) specify a master-journal name to be written into the
41374 **   journal file before it is synced to disk.
41375 **
41376 **   Whether or not a journal file contains a master-journal pointer affects
41377 **   the way in which the journal file is finalized after the transaction is
41378 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
41379 **   If a journal file does not contain a master-journal pointer, it is
41380 **   finalized by overwriting the first journal header with zeroes. If
41381 **   it does contain a master-journal pointer the journal file is finalized
41382 **   by truncating it to zero bytes, just as if the connection were
41383 **   running in "journal_mode=truncate" mode.
41384 **
41385 **   Journal files that contain master journal pointers cannot be finalized
41386 **   simply by overwriting the first journal-header with zeroes, as the
41387 **   master journal pointer could interfere with hot-journal rollback of any
41388 **   subsequently interrupted transaction that reuses the journal file.
41389 **
41390 **   The flag is cleared as soon as the journal file is finalized (either
41391 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
41392 **   journal file from being successfully finalized, the setMaster flag
41393 **   is cleared anyway (and the pager will move to ERROR state).
41394 **
41395 ** doNotSpill
41396 **
41397 **   This variables control the behavior of cache-spills  (calls made by
41398 **   the pcache module to the pagerStress() routine to write cached data
41399 **   to the file-system in order to free up memory).
41400 **
41401 **   When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
41402 **   writing to the database from pagerStress() is disabled altogether.
41403 **   The SPILLFLAG_ROLLBACK case is done in a very obscure case that
41404 **   comes up during savepoint rollback that requires the pcache module
41405 **   to allocate a new page to prevent the journal file from being written
41406 **   while it is being traversed by code in pager_playback().  The SPILLFLAG_OFF
41407 **   case is a user preference.
41408 **
41409 **   If the SPILLFLAG_NOSYNC bit is set, writing to the database from pagerStress()
41410 **   is permitted, but syncing the journal file is not. This flag is set
41411 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
41412 **   the database page-size in order to prevent a journal sync from happening
41413 **   in between the journalling of two pages on the same sector.
41414 **
41415 ** subjInMemory
41416 **
41417 **   This is a boolean variable. If true, then any required sub-journal
41418 **   is opened as an in-memory journal file. If false, then in-memory
41419 **   sub-journals are only used for in-memory pager files.
41420 **
41421 **   This variable is updated by the upper layer each time a new
41422 **   write-transaction is opened.
41423 **
41424 ** dbSize, dbOrigSize, dbFileSize
41425 **
41426 **   Variable dbSize is set to the number of pages in the database file.
41427 **   It is valid in PAGER_READER and higher states (all states except for
41428 **   OPEN and ERROR).
41429 **
41430 **   dbSize is set based on the size of the database file, which may be
41431 **   larger than the size of the database (the value stored at offset
41432 **   28 of the database header by the btree). If the size of the file
41433 **   is not an integer multiple of the page-size, the value stored in
41434 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
41435 **   Except, any file that is greater than 0 bytes in size is considered
41436 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
41437 **   to dbSize==1).
41438 **
41439 **   During a write-transaction, if pages with page-numbers greater than
41440 **   dbSize are modified in the cache, dbSize is updated accordingly.
41441 **   Similarly, if the database is truncated using PagerTruncateImage(),
41442 **   dbSize is updated.
41443 **
41444 **   Variables dbOrigSize and dbFileSize are valid in states
41445 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
41446 **   variable at the start of the transaction. It is used during rollback,
41447 **   and to determine whether or not pages need to be journalled before
41448 **   being modified.
41449 **
41450 **   Throughout a write-transaction, dbFileSize contains the size of
41451 **   the file on disk in pages. It is set to a copy of dbSize when the
41452 **   write-transaction is first opened, and updated when VFS calls are made
41453 **   to write or truncate the database file on disk.
41454 **
41455 **   The only reason the dbFileSize variable is required is to suppress
41456 **   unnecessary calls to xTruncate() after committing a transaction. If,
41457 **   when a transaction is committed, the dbFileSize variable indicates
41458 **   that the database file is larger than the database image (Pager.dbSize),
41459 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
41460 **   to measure the database file on disk, and then truncates it if required.
41461 **   dbFileSize is not used when rolling back a transaction. In this case
41462 **   pager_truncate() is called unconditionally (which means there may be
41463 **   a call to xFilesize() that is not strictly required). In either case,
41464 **   pager_truncate() may cause the file to become smaller or larger.
41465 **
41466 ** dbHintSize
41467 **
41468 **   The dbHintSize variable is used to limit the number of calls made to
41469 **   the VFS xFileControl(FCNTL_SIZE_HINT) method.
41470 **
41471 **   dbHintSize is set to a copy of the dbSize variable when a
41472 **   write-transaction is opened (at the same time as dbFileSize and
41473 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
41474 **   dbHintSize is increased to the number of pages that correspond to the
41475 **   size-hint passed to the method call. See pager_write_pagelist() for
41476 **   details.
41477 **
41478 ** errCode
41479 **
41480 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
41481 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
41482 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
41483 **   sub-codes.
41484 */
41485 struct Pager {
41486   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
41487   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
41488   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
41489   u8 useJournal;              /* Use a rollback journal on this file */
41490   u8 noSync;                  /* Do not sync the journal if true */
41491   u8 fullSync;                /* Do extra syncs of the journal for robustness */
41492   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
41493   u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
41494   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
41495   u8 tempFile;                /* zFilename is a temporary or immutable file */
41496   u8 noLock;                  /* Do not lock (except in WAL mode) */
41497   u8 readOnly;                /* True for a read-only database */
41498   u8 memDb;                   /* True to inhibit all file I/O */
41499 
41500   /**************************************************************************
41501   ** The following block contains those class members that change during
41502   ** routine operation.  Class members not in this block are either fixed
41503   ** when the pager is first created or else only change when there is a
41504   ** significant mode change (such as changing the page_size, locking_mode,
41505   ** or the journal_mode).  From another view, these class members describe
41506   ** the "state" of the pager, while other class members describe the
41507   ** "configuration" of the pager.
41508   */
41509   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
41510   u8 eLock;                   /* Current lock held on database file */
41511   u8 changeCountDone;         /* Set after incrementing the change-counter */
41512   u8 setMaster;               /* True if a m-j name has been written to jrnl */
41513   u8 doNotSpill;              /* Do not spill the cache when non-zero */
41514   u8 subjInMemory;            /* True to use in-memory sub-journals */
41515   Pgno dbSize;                /* Number of pages in the database */
41516   Pgno dbOrigSize;            /* dbSize before the current transaction */
41517   Pgno dbFileSize;            /* Number of pages in the database file */
41518   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
41519   int errCode;                /* One of several kinds of errors */
41520   int nRec;                   /* Pages journalled since last j-header written */
41521   u32 cksumInit;              /* Quasi-random value added to every checksum */
41522   u32 nSubRec;                /* Number of records written to sub-journal */
41523   Bitvec *pInJournal;         /* One bit for each page in the database file */
41524   sqlite3_file *fd;           /* File descriptor for database */
41525   sqlite3_file *jfd;          /* File descriptor for main journal */
41526   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
41527   i64 journalOff;             /* Current write offset in the journal file */
41528   i64 journalHdr;             /* Byte offset to previous journal header */
41529   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
41530   PagerSavepoint *aSavepoint; /* Array of active savepoints */
41531   int nSavepoint;             /* Number of elements in aSavepoint[] */
41532   char dbFileVers[16];        /* Changes whenever database file changes */
41533 
41534   u8 bUseFetch;               /* True to use xFetch() */
41535   int nMmapOut;               /* Number of mmap pages currently outstanding */
41536   sqlite3_int64 szMmap;       /* Desired maximum mmap size */
41537   PgHdr *pMmapFreelist;       /* List of free mmap page headers (pDirty) */
41538   /*
41539   ** End of the routinely-changing class members
41540   ***************************************************************************/
41541 
41542   u16 nExtra;                 /* Add this many bytes to each in-memory page */
41543   i16 nReserve;               /* Number of unused bytes at end of each page */
41544   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
41545   u32 sectorSize;             /* Assumed sector size during rollback */
41546   int pageSize;               /* Number of bytes in a page */
41547   Pgno mxPgno;                /* Maximum allowed size of the database */
41548   i64 journalSizeLimit;       /* Size limit for persistent journal files */
41549   char *zFilename;            /* Name of the database file */
41550   char *zJournal;             /* Name of the journal file */
41551   int (*xBusyHandler)(void*); /* Function to call when busy */
41552   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
41553   int aStat[3];               /* Total cache hits, misses and writes */
41554 #ifdef SQLITE_TEST
41555   int nRead;                  /* Database pages read */
41556 #endif
41557   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
41558 #ifdef SQLITE_HAS_CODEC
41559   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
41560   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
41561   void (*xCodecFree)(void*);             /* Destructor for the codec */
41562   void *pCodec;               /* First argument to xCodec... methods */
41563 #endif
41564   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
41565   PCache *pPCache;            /* Pointer to page cache object */
41566 #ifndef SQLITE_OMIT_WAL
41567   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
41568   char *zWal;                 /* File name for write-ahead log */
41569 #endif
41570 };
41571 
41572 /*
41573 ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
41574 ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
41575 ** or CACHE_WRITE to sqlite3_db_status().
41576 */
41577 #define PAGER_STAT_HIT   0
41578 #define PAGER_STAT_MISS  1
41579 #define PAGER_STAT_WRITE 2
41580 
41581 /*
41582 ** The following global variables hold counters used for
41583 ** testing purposes only.  These variables do not exist in
41584 ** a non-testing build.  These variables are not thread-safe.
41585 */
41586 #ifdef SQLITE_TEST
41587 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
41588 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
41589 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
41590 # define PAGER_INCR(v)  v++
41591 #else
41592 # define PAGER_INCR(v)
41593 #endif
41594 
41595 
41596 
41597 /*
41598 ** Journal files begin with the following magic string.  The data
41599 ** was obtained from /dev/random.  It is used only as a sanity check.
41600 **
41601 ** Since version 2.8.0, the journal format contains additional sanity
41602 ** checking information.  If the power fails while the journal is being
41603 ** written, semi-random garbage data might appear in the journal
41604 ** file after power is restored.  If an attempt is then made
41605 ** to roll the journal back, the database could be corrupted.  The additional
41606 ** sanity checking data is an attempt to discover the garbage in the
41607 ** journal and ignore it.
41608 **
41609 ** The sanity checking information for the new journal format consists
41610 ** of a 32-bit checksum on each page of data.  The checksum covers both
41611 ** the page number and the pPager->pageSize bytes of data for the page.
41612 ** This cksum is initialized to a 32-bit random value that appears in the
41613 ** journal file right after the header.  The random initializer is important,
41614 ** because garbage data that appears at the end of a journal is likely
41615 ** data that was once in other files that have now been deleted.  If the
41616 ** garbage data came from an obsolete journal file, the checksums might
41617 ** be correct.  But by initializing the checksum to random value which
41618 ** is different for every journal, we minimize that risk.
41619 */
41620 static const unsigned char aJournalMagic[] = {
41621   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
41622 };
41623 
41624 /*
41625 ** The size of the of each page record in the journal is given by
41626 ** the following macro.
41627 */
41628 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
41629 
41630 /*
41631 ** The journal header size for this pager. This is usually the same
41632 ** size as a single disk sector. See also setSectorSize().
41633 */
41634 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
41635 
41636 /*
41637 ** The macro MEMDB is true if we are dealing with an in-memory database.
41638 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
41639 ** the value of MEMDB will be a constant and the compiler will optimize
41640 ** out code that would never execute.
41641 */
41642 #ifdef SQLITE_OMIT_MEMORYDB
41643 # define MEMDB 0
41644 #else
41645 # define MEMDB pPager->memDb
41646 #endif
41647 
41648 /*
41649 ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
41650 ** interfaces to access the database using memory-mapped I/O.
41651 */
41652 #if SQLITE_MAX_MMAP_SIZE>0
41653 # define USEFETCH(x) ((x)->bUseFetch)
41654 #else
41655 # define USEFETCH(x) 0
41656 #endif
41657 
41658 /*
41659 ** The maximum legal page number is (2^31 - 1).
41660 */
41661 #define PAGER_MAX_PGNO 2147483647
41662 
41663 /*
41664 ** The argument to this macro is a file descriptor (type sqlite3_file*).
41665 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
41666 **
41667 ** This is so that expressions can be written as:
41668 **
41669 **   if( isOpen(pPager->jfd) ){ ...
41670 **
41671 ** instead of
41672 **
41673 **   if( pPager->jfd->pMethods ){ ...
41674 */
41675 #define isOpen(pFd) ((pFd)->pMethods)
41676 
41677 /*
41678 ** Return true if this pager uses a write-ahead log instead of the usual
41679 ** rollback journal. Otherwise false.
41680 */
41681 #ifndef SQLITE_OMIT_WAL
41682 static int pagerUseWal(Pager *pPager){
41683   return (pPager->pWal!=0);
41684 }
41685 #else
41686 # define pagerUseWal(x) 0
41687 # define pagerRollbackWal(x) 0
41688 # define pagerWalFrames(v,w,x,y) 0
41689 # define pagerOpenWalIfPresent(z) SQLITE_OK
41690 # define pagerBeginReadTransaction(z) SQLITE_OK
41691 #endif
41692 
41693 #ifndef NDEBUG
41694 /*
41695 ** Usage:
41696 **
41697 **   assert( assert_pager_state(pPager) );
41698 **
41699 ** This function runs many asserts to try to find inconsistencies in
41700 ** the internal state of the Pager object.
41701 */
41702 static int assert_pager_state(Pager *p){
41703   Pager *pPager = p;
41704 
41705   /* State must be valid. */
41706   assert( p->eState==PAGER_OPEN
41707        || p->eState==PAGER_READER
41708        || p->eState==PAGER_WRITER_LOCKED
41709        || p->eState==PAGER_WRITER_CACHEMOD
41710        || p->eState==PAGER_WRITER_DBMOD
41711        || p->eState==PAGER_WRITER_FINISHED
41712        || p->eState==PAGER_ERROR
41713   );
41714 
41715   /* Regardless of the current state, a temp-file connection always behaves
41716   ** as if it has an exclusive lock on the database file. It never updates
41717   ** the change-counter field, so the changeCountDone flag is always set.
41718   */
41719   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
41720   assert( p->tempFile==0 || pPager->changeCountDone );
41721 
41722   /* If the useJournal flag is clear, the journal-mode must be "OFF".
41723   ** And if the journal-mode is "OFF", the journal file must not be open.
41724   */
41725   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
41726   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
41727 
41728   /* Check that MEMDB implies noSync. And an in-memory journal. Since
41729   ** this means an in-memory pager performs no IO at all, it cannot encounter
41730   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
41731   ** a journal file. (although the in-memory journal implementation may
41732   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
41733   ** is therefore not possible for an in-memory pager to enter the ERROR
41734   ** state.
41735   */
41736   if( MEMDB ){
41737     assert( p->noSync );
41738     assert( p->journalMode==PAGER_JOURNALMODE_OFF
41739          || p->journalMode==PAGER_JOURNALMODE_MEMORY
41740     );
41741     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
41742     assert( pagerUseWal(p)==0 );
41743   }
41744 
41745   /* If changeCountDone is set, a RESERVED lock or greater must be held
41746   ** on the file.
41747   */
41748   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
41749   assert( p->eLock!=PENDING_LOCK );
41750 
41751   switch( p->eState ){
41752     case PAGER_OPEN:
41753       assert( !MEMDB );
41754       assert( pPager->errCode==SQLITE_OK );
41755       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
41756       break;
41757 
41758     case PAGER_READER:
41759       assert( pPager->errCode==SQLITE_OK );
41760       assert( p->eLock!=UNKNOWN_LOCK );
41761       assert( p->eLock>=SHARED_LOCK );
41762       break;
41763 
41764     case PAGER_WRITER_LOCKED:
41765       assert( p->eLock!=UNKNOWN_LOCK );
41766       assert( pPager->errCode==SQLITE_OK );
41767       if( !pagerUseWal(pPager) ){
41768         assert( p->eLock>=RESERVED_LOCK );
41769       }
41770       assert( pPager->dbSize==pPager->dbOrigSize );
41771       assert( pPager->dbOrigSize==pPager->dbFileSize );
41772       assert( pPager->dbOrigSize==pPager->dbHintSize );
41773       assert( pPager->setMaster==0 );
41774       break;
41775 
41776     case PAGER_WRITER_CACHEMOD:
41777       assert( p->eLock!=UNKNOWN_LOCK );
41778       assert( pPager->errCode==SQLITE_OK );
41779       if( !pagerUseWal(pPager) ){
41780         /* It is possible that if journal_mode=wal here that neither the
41781         ** journal file nor the WAL file are open. This happens during
41782         ** a rollback transaction that switches from journal_mode=off
41783         ** to journal_mode=wal.
41784         */
41785         assert( p->eLock>=RESERVED_LOCK );
41786         assert( isOpen(p->jfd)
41787              || p->journalMode==PAGER_JOURNALMODE_OFF
41788              || p->journalMode==PAGER_JOURNALMODE_WAL
41789         );
41790       }
41791       assert( pPager->dbOrigSize==pPager->dbFileSize );
41792       assert( pPager->dbOrigSize==pPager->dbHintSize );
41793       break;
41794 
41795     case PAGER_WRITER_DBMOD:
41796       assert( p->eLock==EXCLUSIVE_LOCK );
41797       assert( pPager->errCode==SQLITE_OK );
41798       assert( !pagerUseWal(pPager) );
41799       assert( p->eLock>=EXCLUSIVE_LOCK );
41800       assert( isOpen(p->jfd)
41801            || p->journalMode==PAGER_JOURNALMODE_OFF
41802            || p->journalMode==PAGER_JOURNALMODE_WAL
41803       );
41804       assert( pPager->dbOrigSize<=pPager->dbHintSize );
41805       break;
41806 
41807     case PAGER_WRITER_FINISHED:
41808       assert( p->eLock==EXCLUSIVE_LOCK );
41809       assert( pPager->errCode==SQLITE_OK );
41810       assert( !pagerUseWal(pPager) );
41811       assert( isOpen(p->jfd)
41812            || p->journalMode==PAGER_JOURNALMODE_OFF
41813            || p->journalMode==PAGER_JOURNALMODE_WAL
41814       );
41815       break;
41816 
41817     case PAGER_ERROR:
41818       /* There must be at least one outstanding reference to the pager if
41819       ** in ERROR state. Otherwise the pager should have already dropped
41820       ** back to OPEN state.
41821       */
41822       assert( pPager->errCode!=SQLITE_OK );
41823       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
41824       break;
41825   }
41826 
41827   return 1;
41828 }
41829 #endif /* ifndef NDEBUG */
41830 
41831 #ifdef SQLITE_DEBUG
41832 /*
41833 ** Return a pointer to a human readable string in a static buffer
41834 ** containing the state of the Pager object passed as an argument. This
41835 ** is intended to be used within debuggers. For example, as an alternative
41836 ** to "print *pPager" in gdb:
41837 **
41838 ** (gdb) printf "%s", print_pager_state(pPager)
41839 */
41840 static char *print_pager_state(Pager *p){
41841   static char zRet[1024];
41842 
41843   sqlite3_snprintf(1024, zRet,
41844       "Filename:      %s\n"
41845       "State:         %s errCode=%d\n"
41846       "Lock:          %s\n"
41847       "Locking mode:  locking_mode=%s\n"
41848       "Journal mode:  journal_mode=%s\n"
41849       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
41850       "Journal:       journalOff=%lld journalHdr=%lld\n"
41851       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
41852       , p->zFilename
41853       , p->eState==PAGER_OPEN            ? "OPEN" :
41854         p->eState==PAGER_READER          ? "READER" :
41855         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
41856         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
41857         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
41858         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
41859         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
41860       , (int)p->errCode
41861       , p->eLock==NO_LOCK         ? "NO_LOCK" :
41862         p->eLock==RESERVED_LOCK   ? "RESERVED" :
41863         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
41864         p->eLock==SHARED_LOCK     ? "SHARED" :
41865         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
41866       , p->exclusiveMode ? "exclusive" : "normal"
41867       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
41868         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
41869         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
41870         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
41871         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
41872         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
41873       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
41874       , p->journalOff, p->journalHdr
41875       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
41876   );
41877 
41878   return zRet;
41879 }
41880 #endif
41881 
41882 /*
41883 ** Return true if it is necessary to write page *pPg into the sub-journal.
41884 ** A page needs to be written into the sub-journal if there exists one
41885 ** or more open savepoints for which:
41886 **
41887 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
41888 **   * The bit corresponding to the page-number is not set in
41889 **     PagerSavepoint.pInSavepoint.
41890 */
41891 static int subjRequiresPage(PgHdr *pPg){
41892   Pager *pPager = pPg->pPager;
41893   PagerSavepoint *p;
41894   Pgno pgno = pPg->pgno;
41895   int i;
41896   for(i=0; i<pPager->nSavepoint; i++){
41897     p = &pPager->aSavepoint[i];
41898     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
41899       return 1;
41900     }
41901   }
41902   return 0;
41903 }
41904 
41905 /*
41906 ** Return true if the page is already in the journal file.
41907 */
41908 static int pageInJournal(Pager *pPager, PgHdr *pPg){
41909   return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
41910 }
41911 
41912 /*
41913 ** Read a 32-bit integer from the given file descriptor.  Store the integer
41914 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
41915 ** error code is something goes wrong.
41916 **
41917 ** All values are stored on disk as big-endian.
41918 */
41919 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
41920   unsigned char ac[4];
41921   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
41922   if( rc==SQLITE_OK ){
41923     *pRes = sqlite3Get4byte(ac);
41924   }
41925   return rc;
41926 }
41927 
41928 /*
41929 ** Write a 32-bit integer into a string buffer in big-endian byte order.
41930 */
41931 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
41932 
41933 
41934 /*
41935 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
41936 ** on success or an error code is something goes wrong.
41937 */
41938 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
41939   char ac[4];
41940   put32bits(ac, val);
41941   return sqlite3OsWrite(fd, ac, 4, offset);
41942 }
41943 
41944 /*
41945 ** Unlock the database file to level eLock, which must be either NO_LOCK
41946 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
41947 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
41948 **
41949 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
41950 ** called, do not modify it. See the comment above the #define of
41951 ** UNKNOWN_LOCK for an explanation of this.
41952 */
41953 static int pagerUnlockDb(Pager *pPager, int eLock){
41954   int rc = SQLITE_OK;
41955 
41956   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
41957   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
41958   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
41959   if( isOpen(pPager->fd) ){
41960     assert( pPager->eLock>=eLock );
41961     rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
41962     if( pPager->eLock!=UNKNOWN_LOCK ){
41963       pPager->eLock = (u8)eLock;
41964     }
41965     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
41966   }
41967   return rc;
41968 }
41969 
41970 /*
41971 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
41972 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
41973 ** Pager.eLock variable to the new locking state.
41974 **
41975 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
41976 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
41977 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
41978 ** of this.
41979 */
41980 static int pagerLockDb(Pager *pPager, int eLock){
41981   int rc = SQLITE_OK;
41982 
41983   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
41984   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
41985     rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
41986     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
41987       pPager->eLock = (u8)eLock;
41988       IOTRACE(("LOCK %p %d\n", pPager, eLock))
41989     }
41990   }
41991   return rc;
41992 }
41993 
41994 /*
41995 ** This function determines whether or not the atomic-write optimization
41996 ** can be used with this pager. The optimization can be used if:
41997 **
41998 **  (a) the value returned by OsDeviceCharacteristics() indicates that
41999 **      a database page may be written atomically, and
42000 **  (b) the value returned by OsSectorSize() is less than or equal
42001 **      to the page size.
42002 **
42003 ** The optimization is also always enabled for temporary files. It is
42004 ** an error to call this function if pPager is opened on an in-memory
42005 ** database.
42006 **
42007 ** If the optimization cannot be used, 0 is returned. If it can be used,
42008 ** then the value returned is the size of the journal file when it
42009 ** contains rollback data for exactly one page.
42010 */
42011 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
42012 static int jrnlBufferSize(Pager *pPager){
42013   assert( !MEMDB );
42014   if( !pPager->tempFile ){
42015     int dc;                           /* Device characteristics */
42016     int nSector;                      /* Sector size */
42017     int szPage;                       /* Page size */
42018 
42019     assert( isOpen(pPager->fd) );
42020     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
42021     nSector = pPager->sectorSize;
42022     szPage = pPager->pageSize;
42023 
42024     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
42025     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
42026     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
42027       return 0;
42028     }
42029   }
42030 
42031   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
42032 }
42033 #endif
42034 
42035 /*
42036 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
42037 ** on the cache using a hash function.  This is used for testing
42038 ** and debugging only.
42039 */
42040 #ifdef SQLITE_CHECK_PAGES
42041 /*
42042 ** Return a 32-bit hash of the page data for pPage.
42043 */
42044 static u32 pager_datahash(int nByte, unsigned char *pData){
42045   u32 hash = 0;
42046   int i;
42047   for(i=0; i<nByte; i++){
42048     hash = (hash*1039) + pData[i];
42049   }
42050   return hash;
42051 }
42052 static u32 pager_pagehash(PgHdr *pPage){
42053   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
42054 }
42055 static void pager_set_pagehash(PgHdr *pPage){
42056   pPage->pageHash = pager_pagehash(pPage);
42057 }
42058 
42059 /*
42060 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
42061 ** is defined, and NDEBUG is not defined, an assert() statement checks
42062 ** that the page is either dirty or still matches the calculated page-hash.
42063 */
42064 #define CHECK_PAGE(x) checkPage(x)
42065 static void checkPage(PgHdr *pPg){
42066   Pager *pPager = pPg->pPager;
42067   assert( pPager->eState!=PAGER_ERROR );
42068   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
42069 }
42070 
42071 #else
42072 #define pager_datahash(X,Y)  0
42073 #define pager_pagehash(X)  0
42074 #define pager_set_pagehash(X)
42075 #define CHECK_PAGE(x)
42076 #endif  /* SQLITE_CHECK_PAGES */
42077 
42078 /*
42079 ** When this is called the journal file for pager pPager must be open.
42080 ** This function attempts to read a master journal file name from the
42081 ** end of the file and, if successful, copies it into memory supplied
42082 ** by the caller. See comments above writeMasterJournal() for the format
42083 ** used to store a master journal file name at the end of a journal file.
42084 **
42085 ** zMaster must point to a buffer of at least nMaster bytes allocated by
42086 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
42087 ** enough space to write the master journal name). If the master journal
42088 ** name in the journal is longer than nMaster bytes (including a
42089 ** nul-terminator), then this is handled as if no master journal name
42090 ** were present in the journal.
42091 **
42092 ** If a master journal file name is present at the end of the journal
42093 ** file, then it is copied into the buffer pointed to by zMaster. A
42094 ** nul-terminator byte is appended to the buffer following the master
42095 ** journal file name.
42096 **
42097 ** If it is determined that no master journal file name is present
42098 ** zMaster[0] is set to 0 and SQLITE_OK returned.
42099 **
42100 ** If an error occurs while reading from the journal file, an SQLite
42101 ** error code is returned.
42102 */
42103 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
42104   int rc;                    /* Return code */
42105   u32 len;                   /* Length in bytes of master journal name */
42106   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
42107   u32 cksum;                 /* MJ checksum value read from journal */
42108   u32 u;                     /* Unsigned loop counter */
42109   unsigned char aMagic[8];   /* A buffer to hold the magic header */
42110   zMaster[0] = '\0';
42111 
42112   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
42113    || szJ<16
42114    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
42115    || len>=nMaster
42116    || len==0
42117    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
42118    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
42119    || memcmp(aMagic, aJournalMagic, 8)
42120    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
42121   ){
42122     return rc;
42123   }
42124 
42125   /* See if the checksum matches the master journal name */
42126   for(u=0; u<len; u++){
42127     cksum -= zMaster[u];
42128   }
42129   if( cksum ){
42130     /* If the checksum doesn't add up, then one or more of the disk sectors
42131     ** containing the master journal filename is corrupted. This means
42132     ** definitely roll back, so just return SQLITE_OK and report a (nul)
42133     ** master-journal filename.
42134     */
42135     len = 0;
42136   }
42137   zMaster[len] = '\0';
42138 
42139   return SQLITE_OK;
42140 }
42141 
42142 /*
42143 ** Return the offset of the sector boundary at or immediately
42144 ** following the value in pPager->journalOff, assuming a sector
42145 ** size of pPager->sectorSize bytes.
42146 **
42147 ** i.e for a sector size of 512:
42148 **
42149 **   Pager.journalOff          Return value
42150 **   ---------------------------------------
42151 **   0                         0
42152 **   512                       512
42153 **   100                       512
42154 **   2000                      2048
42155 **
42156 */
42157 static i64 journalHdrOffset(Pager *pPager){
42158   i64 offset = 0;
42159   i64 c = pPager->journalOff;
42160   if( c ){
42161     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
42162   }
42163   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
42164   assert( offset>=c );
42165   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
42166   return offset;
42167 }
42168 
42169 /*
42170 ** The journal file must be open when this function is called.
42171 **
42172 ** This function is a no-op if the journal file has not been written to
42173 ** within the current transaction (i.e. if Pager.journalOff==0).
42174 **
42175 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
42176 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
42177 ** zero the 28-byte header at the start of the journal file. In either case,
42178 ** if the pager is not in no-sync mode, sync the journal file immediately
42179 ** after writing or truncating it.
42180 **
42181 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
42182 ** following the truncation or zeroing described above the size of the
42183 ** journal file in bytes is larger than this value, then truncate the
42184 ** journal file to Pager.journalSizeLimit bytes. The journal file does
42185 ** not need to be synced following this operation.
42186 **
42187 ** If an IO error occurs, abandon processing and return the IO error code.
42188 ** Otherwise, return SQLITE_OK.
42189 */
42190 static int zeroJournalHdr(Pager *pPager, int doTruncate){
42191   int rc = SQLITE_OK;                               /* Return code */
42192   assert( isOpen(pPager->jfd) );
42193   if( pPager->journalOff ){
42194     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
42195 
42196     IOTRACE(("JZEROHDR %p\n", pPager))
42197     if( doTruncate || iLimit==0 ){
42198       rc = sqlite3OsTruncate(pPager->jfd, 0);
42199     }else{
42200       static const char zeroHdr[28] = {0};
42201       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
42202     }
42203     if( rc==SQLITE_OK && !pPager->noSync ){
42204       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
42205     }
42206 
42207     /* At this point the transaction is committed but the write lock
42208     ** is still held on the file. If there is a size limit configured for
42209     ** the persistent journal and the journal file currently consumes more
42210     ** space than that limit allows for, truncate it now. There is no need
42211     ** to sync the file following this operation.
42212     */
42213     if( rc==SQLITE_OK && iLimit>0 ){
42214       i64 sz;
42215       rc = sqlite3OsFileSize(pPager->jfd, &sz);
42216       if( rc==SQLITE_OK && sz>iLimit ){
42217         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
42218       }
42219     }
42220   }
42221   return rc;
42222 }
42223 
42224 /*
42225 ** The journal file must be open when this routine is called. A journal
42226 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
42227 ** current location.
42228 **
42229 ** The format for the journal header is as follows:
42230 ** - 8 bytes: Magic identifying journal format.
42231 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
42232 ** - 4 bytes: Random number used for page hash.
42233 ** - 4 bytes: Initial database page count.
42234 ** - 4 bytes: Sector size used by the process that wrote this journal.
42235 ** - 4 bytes: Database page size.
42236 **
42237 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
42238 */
42239 static int writeJournalHdr(Pager *pPager){
42240   int rc = SQLITE_OK;                 /* Return code */
42241   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
42242   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
42243   u32 nWrite;                         /* Bytes of header sector written */
42244   int ii;                             /* Loop counter */
42245 
42246   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
42247 
42248   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
42249     nHeader = JOURNAL_HDR_SZ(pPager);
42250   }
42251 
42252   /* If there are active savepoints and any of them were created
42253   ** since the most recent journal header was written, update the
42254   ** PagerSavepoint.iHdrOffset fields now.
42255   */
42256   for(ii=0; ii<pPager->nSavepoint; ii++){
42257     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
42258       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
42259     }
42260   }
42261 
42262   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
42263 
42264   /*
42265   ** Write the nRec Field - the number of page records that follow this
42266   ** journal header. Normally, zero is written to this value at this time.
42267   ** After the records are added to the journal (and the journal synced,
42268   ** if in full-sync mode), the zero is overwritten with the true number
42269   ** of records (see syncJournal()).
42270   **
42271   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
42272   ** reading the journal this value tells SQLite to assume that the
42273   ** rest of the journal file contains valid page records. This assumption
42274   ** is dangerous, as if a failure occurred whilst writing to the journal
42275   ** file it may contain some garbage data. There are two scenarios
42276   ** where this risk can be ignored:
42277   **
42278   **   * When the pager is in no-sync mode. Corruption can follow a
42279   **     power failure in this case anyway.
42280   **
42281   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
42282   **     that garbage data is never appended to the journal file.
42283   */
42284   assert( isOpen(pPager->fd) || pPager->noSync );
42285   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
42286    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
42287   ){
42288     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
42289     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
42290   }else{
42291     memset(zHeader, 0, sizeof(aJournalMagic)+4);
42292   }
42293 
42294   /* The random check-hash initializer */
42295   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
42296   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
42297   /* The initial database size */
42298   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
42299   /* The assumed sector size for this process */
42300   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
42301 
42302   /* The page size */
42303   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
42304 
42305   /* Initializing the tail of the buffer is not necessary.  Everything
42306   ** works find if the following memset() is omitted.  But initializing
42307   ** the memory prevents valgrind from complaining, so we are willing to
42308   ** take the performance hit.
42309   */
42310   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
42311          nHeader-(sizeof(aJournalMagic)+20));
42312 
42313   /* In theory, it is only necessary to write the 28 bytes that the
42314   ** journal header consumes to the journal file here. Then increment the
42315   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
42316   ** record is written to the following sector (leaving a gap in the file
42317   ** that will be implicitly filled in by the OS).
42318   **
42319   ** However it has been discovered that on some systems this pattern can
42320   ** be significantly slower than contiguously writing data to the file,
42321   ** even if that means explicitly writing data to the block of
42322   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
42323   ** is done.
42324   **
42325   ** The loop is required here in case the sector-size is larger than the
42326   ** database page size. Since the zHeader buffer is only Pager.pageSize
42327   ** bytes in size, more than one call to sqlite3OsWrite() may be required
42328   ** to populate the entire journal header sector.
42329   */
42330   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
42331     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
42332     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
42333     assert( pPager->journalHdr <= pPager->journalOff );
42334     pPager->journalOff += nHeader;
42335   }
42336 
42337   return rc;
42338 }
42339 
42340 /*
42341 ** The journal file must be open when this is called. A journal header file
42342 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
42343 ** file. The current location in the journal file is given by
42344 ** pPager->journalOff. See comments above function writeJournalHdr() for
42345 ** a description of the journal header format.
42346 **
42347 ** If the header is read successfully, *pNRec is set to the number of
42348 ** page records following this header and *pDbSize is set to the size of the
42349 ** database before the transaction began, in pages. Also, pPager->cksumInit
42350 ** is set to the value read from the journal header. SQLITE_OK is returned
42351 ** in this case.
42352 **
42353 ** If the journal header file appears to be corrupted, SQLITE_DONE is
42354 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
42355 ** cannot be read from the journal file an error code is returned.
42356 */
42357 static int readJournalHdr(
42358   Pager *pPager,               /* Pager object */
42359   int isHot,
42360   i64 journalSize,             /* Size of the open journal file in bytes */
42361   u32 *pNRec,                  /* OUT: Value read from the nRec field */
42362   u32 *pDbSize                 /* OUT: Value of original database size field */
42363 ){
42364   int rc;                      /* Return code */
42365   unsigned char aMagic[8];     /* A buffer to hold the magic header */
42366   i64 iHdrOff;                 /* Offset of journal header being read */
42367 
42368   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
42369 
42370   /* Advance Pager.journalOff to the start of the next sector. If the
42371   ** journal file is too small for there to be a header stored at this
42372   ** point, return SQLITE_DONE.
42373   */
42374   pPager->journalOff = journalHdrOffset(pPager);
42375   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
42376     return SQLITE_DONE;
42377   }
42378   iHdrOff = pPager->journalOff;
42379 
42380   /* Read in the first 8 bytes of the journal header. If they do not match
42381   ** the  magic string found at the start of each journal header, return
42382   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
42383   ** proceed.
42384   */
42385   if( isHot || iHdrOff!=pPager->journalHdr ){
42386     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
42387     if( rc ){
42388       return rc;
42389     }
42390     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
42391       return SQLITE_DONE;
42392     }
42393   }
42394 
42395   /* Read the first three 32-bit fields of the journal header: The nRec
42396   ** field, the checksum-initializer and the database size at the start
42397   ** of the transaction. Return an error code if anything goes wrong.
42398   */
42399   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
42400    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
42401    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
42402   ){
42403     return rc;
42404   }
42405 
42406   if( pPager->journalOff==0 ){
42407     u32 iPageSize;               /* Page-size field of journal header */
42408     u32 iSectorSize;             /* Sector-size field of journal header */
42409 
42410     /* Read the page-size and sector-size journal header fields. */
42411     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
42412      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
42413     ){
42414       return rc;
42415     }
42416 
42417     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
42418     ** journal header to zero. In this case, assume that the Pager.pageSize
42419     ** variable is already set to the correct page size.
42420     */
42421     if( iPageSize==0 ){
42422       iPageSize = pPager->pageSize;
42423     }
42424 
42425     /* Check that the values read from the page-size and sector-size fields
42426     ** are within range. To be 'in range', both values need to be a power
42427     ** of two greater than or equal to 512 or 32, and not greater than their
42428     ** respective compile time maximum limits.
42429     */
42430     if( iPageSize<512                  || iSectorSize<32
42431      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
42432      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
42433     ){
42434       /* If the either the page-size or sector-size in the journal-header is
42435       ** invalid, then the process that wrote the journal-header must have
42436       ** crashed before the header was synced. In this case stop reading
42437       ** the journal file here.
42438       */
42439       return SQLITE_DONE;
42440     }
42441 
42442     /* Update the page-size to match the value read from the journal.
42443     ** Use a testcase() macro to make sure that malloc failure within
42444     ** PagerSetPagesize() is tested.
42445     */
42446     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
42447     testcase( rc!=SQLITE_OK );
42448 
42449     /* Update the assumed sector-size to match the value used by
42450     ** the process that created this journal. If this journal was
42451     ** created by a process other than this one, then this routine
42452     ** is being called from within pager_playback(). The local value
42453     ** of Pager.sectorSize is restored at the end of that routine.
42454     */
42455     pPager->sectorSize = iSectorSize;
42456   }
42457 
42458   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
42459   return rc;
42460 }
42461 
42462 
42463 /*
42464 ** Write the supplied master journal name into the journal file for pager
42465 ** pPager at the current location. The master journal name must be the last
42466 ** thing written to a journal file. If the pager is in full-sync mode, the
42467 ** journal file descriptor is advanced to the next sector boundary before
42468 ** anything is written. The format is:
42469 **
42470 **   + 4 bytes: PAGER_MJ_PGNO.
42471 **   + N bytes: Master journal filename in utf-8.
42472 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
42473 **   + 4 bytes: Master journal name checksum.
42474 **   + 8 bytes: aJournalMagic[].
42475 **
42476 ** The master journal page checksum is the sum of the bytes in the master
42477 ** journal name, where each byte is interpreted as a signed 8-bit integer.
42478 **
42479 ** If zMaster is a NULL pointer (occurs for a single database transaction),
42480 ** this call is a no-op.
42481 */
42482 static int writeMasterJournal(Pager *pPager, const char *zMaster){
42483   int rc;                          /* Return code */
42484   int nMaster;                     /* Length of string zMaster */
42485   i64 iHdrOff;                     /* Offset of header in journal file */
42486   i64 jrnlSize;                    /* Size of journal file on disk */
42487   u32 cksum = 0;                   /* Checksum of string zMaster */
42488 
42489   assert( pPager->setMaster==0 );
42490   assert( !pagerUseWal(pPager) );
42491 
42492   if( !zMaster
42493    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
42494    || !isOpen(pPager->jfd)
42495   ){
42496     return SQLITE_OK;
42497   }
42498   pPager->setMaster = 1;
42499   assert( pPager->journalHdr <= pPager->journalOff );
42500 
42501   /* Calculate the length in bytes and the checksum of zMaster */
42502   for(nMaster=0; zMaster[nMaster]; nMaster++){
42503     cksum += zMaster[nMaster];
42504   }
42505 
42506   /* If in full-sync mode, advance to the next disk sector before writing
42507   ** the master journal name. This is in case the previous page written to
42508   ** the journal has already been synced.
42509   */
42510   if( pPager->fullSync ){
42511     pPager->journalOff = journalHdrOffset(pPager);
42512   }
42513   iHdrOff = pPager->journalOff;
42514 
42515   /* Write the master journal data to the end of the journal file. If
42516   ** an error occurs, return the error code to the caller.
42517   */
42518   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
42519    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
42520    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
42521    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
42522    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
42523   ){
42524     return rc;
42525   }
42526   pPager->journalOff += (nMaster+20);
42527 
42528   /* If the pager is in peristent-journal mode, then the physical
42529   ** journal-file may extend past the end of the master-journal name
42530   ** and 8 bytes of magic data just written to the file. This is
42531   ** dangerous because the code to rollback a hot-journal file
42532   ** will not be able to find the master-journal name to determine
42533   ** whether or not the journal is hot.
42534   **
42535   ** Easiest thing to do in this scenario is to truncate the journal
42536   ** file to the required size.
42537   */
42538   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
42539    && jrnlSize>pPager->journalOff
42540   ){
42541     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
42542   }
42543   return rc;
42544 }
42545 
42546 /*
42547 ** Discard the entire contents of the in-memory page-cache.
42548 */
42549 static void pager_reset(Pager *pPager){
42550   sqlite3BackupRestart(pPager->pBackup);
42551   sqlite3PcacheClear(pPager->pPCache);
42552 }
42553 
42554 /*
42555 ** Free all structures in the Pager.aSavepoint[] array and set both
42556 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
42557 ** if it is open and the pager is not in exclusive mode.
42558 */
42559 static void releaseAllSavepoints(Pager *pPager){
42560   int ii;               /* Iterator for looping through Pager.aSavepoint */
42561   for(ii=0; ii<pPager->nSavepoint; ii++){
42562     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
42563   }
42564   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
42565     sqlite3OsClose(pPager->sjfd);
42566   }
42567   sqlite3_free(pPager->aSavepoint);
42568   pPager->aSavepoint = 0;
42569   pPager->nSavepoint = 0;
42570   pPager->nSubRec = 0;
42571 }
42572 
42573 /*
42574 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
42575 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
42576 ** or SQLITE_NOMEM if a malloc failure occurs.
42577 */
42578 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
42579   int ii;                   /* Loop counter */
42580   int rc = SQLITE_OK;       /* Result code */
42581 
42582   for(ii=0; ii<pPager->nSavepoint; ii++){
42583     PagerSavepoint *p = &pPager->aSavepoint[ii];
42584     if( pgno<=p->nOrig ){
42585       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
42586       testcase( rc==SQLITE_NOMEM );
42587       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
42588     }
42589   }
42590   return rc;
42591 }
42592 
42593 /*
42594 ** This function is a no-op if the pager is in exclusive mode and not
42595 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
42596 ** state.
42597 **
42598 ** If the pager is not in exclusive-access mode, the database file is
42599 ** completely unlocked. If the file is unlocked and the file-system does
42600 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
42601 ** closed (if it is open).
42602 **
42603 ** If the pager is in ERROR state when this function is called, the
42604 ** contents of the pager cache are discarded before switching back to
42605 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
42606 ** or not, any journal file left in the file-system will be treated
42607 ** as a hot-journal and rolled back the next time a read-transaction
42608 ** is opened (by this or by any other connection).
42609 */
42610 static void pager_unlock(Pager *pPager){
42611 
42612   assert( pPager->eState==PAGER_READER
42613        || pPager->eState==PAGER_OPEN
42614        || pPager->eState==PAGER_ERROR
42615   );
42616 
42617   sqlite3BitvecDestroy(pPager->pInJournal);
42618   pPager->pInJournal = 0;
42619   releaseAllSavepoints(pPager);
42620 
42621   if( pagerUseWal(pPager) ){
42622     assert( !isOpen(pPager->jfd) );
42623     sqlite3WalEndReadTransaction(pPager->pWal);
42624     pPager->eState = PAGER_OPEN;
42625   }else if( !pPager->exclusiveMode ){
42626     int rc;                       /* Error code returned by pagerUnlockDb() */
42627     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
42628 
42629     /* If the operating system support deletion of open files, then
42630     ** close the journal file when dropping the database lock.  Otherwise
42631     ** another connection with journal_mode=delete might delete the file
42632     ** out from under us.
42633     */
42634     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
42635     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
42636     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
42637     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
42638     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
42639     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
42640     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
42641      || 1!=(pPager->journalMode & 5)
42642     ){
42643       sqlite3OsClose(pPager->jfd);
42644     }
42645 
42646     /* If the pager is in the ERROR state and the call to unlock the database
42647     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
42648     ** above the #define for UNKNOWN_LOCK for an explanation of why this
42649     ** is necessary.
42650     */
42651     rc = pagerUnlockDb(pPager, NO_LOCK);
42652     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
42653       pPager->eLock = UNKNOWN_LOCK;
42654     }
42655 
42656     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
42657     ** without clearing the error code. This is intentional - the error
42658     ** code is cleared and the cache reset in the block below.
42659     */
42660     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
42661     pPager->changeCountDone = 0;
42662     pPager->eState = PAGER_OPEN;
42663   }
42664 
42665   /* If Pager.errCode is set, the contents of the pager cache cannot be
42666   ** trusted. Now that there are no outstanding references to the pager,
42667   ** it can safely move back to PAGER_OPEN state. This happens in both
42668   ** normal and exclusive-locking mode.
42669   */
42670   if( pPager->errCode ){
42671     assert( !MEMDB );
42672     pager_reset(pPager);
42673     pPager->changeCountDone = pPager->tempFile;
42674     pPager->eState = PAGER_OPEN;
42675     pPager->errCode = SQLITE_OK;
42676     if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
42677   }
42678 
42679   pPager->journalOff = 0;
42680   pPager->journalHdr = 0;
42681   pPager->setMaster = 0;
42682 }
42683 
42684 /*
42685 ** This function is called whenever an IOERR or FULL error that requires
42686 ** the pager to transition into the ERROR state may ahve occurred.
42687 ** The first argument is a pointer to the pager structure, the second
42688 ** the error-code about to be returned by a pager API function. The
42689 ** value returned is a copy of the second argument to this function.
42690 **
42691 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
42692 ** IOERR sub-codes, the pager enters the ERROR state and the error code
42693 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
42694 ** all major API calls on the Pager will immediately return Pager.errCode.
42695 **
42696 ** The ERROR state indicates that the contents of the pager-cache
42697 ** cannot be trusted. This state can be cleared by completely discarding
42698 ** the contents of the pager-cache. If a transaction was active when
42699 ** the persistent error occurred, then the rollback journal may need
42700 ** to be replayed to restore the contents of the database file (as if
42701 ** it were a hot-journal).
42702 */
42703 static int pager_error(Pager *pPager, int rc){
42704   int rc2 = rc & 0xff;
42705   assert( rc==SQLITE_OK || !MEMDB );
42706   assert(
42707        pPager->errCode==SQLITE_FULL ||
42708        pPager->errCode==SQLITE_OK ||
42709        (pPager->errCode & 0xff)==SQLITE_IOERR
42710   );
42711   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
42712     pPager->errCode = rc;
42713     pPager->eState = PAGER_ERROR;
42714   }
42715   return rc;
42716 }
42717 
42718 static int pager_truncate(Pager *pPager, Pgno nPage);
42719 
42720 /*
42721 ** This routine ends a transaction. A transaction is usually ended by
42722 ** either a COMMIT or a ROLLBACK operation. This routine may be called
42723 ** after rollback of a hot-journal, or if an error occurs while opening
42724 ** the journal file or writing the very first journal-header of a
42725 ** database transaction.
42726 **
42727 ** This routine is never called in PAGER_ERROR state. If it is called
42728 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
42729 ** exclusive than a RESERVED lock, it is a no-op.
42730 **
42731 ** Otherwise, any active savepoints are released.
42732 **
42733 ** If the journal file is open, then it is "finalized". Once a journal
42734 ** file has been finalized it is not possible to use it to roll back a
42735 ** transaction. Nor will it be considered to be a hot-journal by this
42736 ** or any other database connection. Exactly how a journal is finalized
42737 ** depends on whether or not the pager is running in exclusive mode and
42738 ** the current journal-mode (Pager.journalMode value), as follows:
42739 **
42740 **   journalMode==MEMORY
42741 **     Journal file descriptor is simply closed. This destroys an
42742 **     in-memory journal.
42743 **
42744 **   journalMode==TRUNCATE
42745 **     Journal file is truncated to zero bytes in size.
42746 **
42747 **   journalMode==PERSIST
42748 **     The first 28 bytes of the journal file are zeroed. This invalidates
42749 **     the first journal header in the file, and hence the entire journal
42750 **     file. An invalid journal file cannot be rolled back.
42751 **
42752 **   journalMode==DELETE
42753 **     The journal file is closed and deleted using sqlite3OsDelete().
42754 **
42755 **     If the pager is running in exclusive mode, this method of finalizing
42756 **     the journal file is never used. Instead, if the journalMode is
42757 **     DELETE and the pager is in exclusive mode, the method described under
42758 **     journalMode==PERSIST is used instead.
42759 **
42760 ** After the journal is finalized, the pager moves to PAGER_READER state.
42761 ** If running in non-exclusive rollback mode, the lock on the file is
42762 ** downgraded to a SHARED_LOCK.
42763 **
42764 ** SQLITE_OK is returned if no error occurs. If an error occurs during
42765 ** any of the IO operations to finalize the journal file or unlock the
42766 ** database then the IO error code is returned to the user. If the
42767 ** operation to finalize the journal file fails, then the code still
42768 ** tries to unlock the database file if not in exclusive mode. If the
42769 ** unlock operation fails as well, then the first error code related
42770 ** to the first error encountered (the journal finalization one) is
42771 ** returned.
42772 */
42773 static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
42774   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
42775   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
42776 
42777   /* Do nothing if the pager does not have an open write transaction
42778   ** or at least a RESERVED lock. This function may be called when there
42779   ** is no write-transaction active but a RESERVED or greater lock is
42780   ** held under two circumstances:
42781   **
42782   **   1. After a successful hot-journal rollback, it is called with
42783   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
42784   **
42785   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
42786   **      lock switches back to locking_mode=normal and then executes a
42787   **      read-transaction, this function is called with eState==PAGER_READER
42788   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
42789   */
42790   assert( assert_pager_state(pPager) );
42791   assert( pPager->eState!=PAGER_ERROR );
42792   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
42793     return SQLITE_OK;
42794   }
42795 
42796   releaseAllSavepoints(pPager);
42797   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
42798   if( isOpen(pPager->jfd) ){
42799     assert( !pagerUseWal(pPager) );
42800 
42801     /* Finalize the journal file. */
42802     if( sqlite3IsMemJournal(pPager->jfd) ){
42803       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
42804       sqlite3OsClose(pPager->jfd);
42805     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
42806       if( pPager->journalOff==0 ){
42807         rc = SQLITE_OK;
42808       }else{
42809         rc = sqlite3OsTruncate(pPager->jfd, 0);
42810         if( rc==SQLITE_OK && pPager->fullSync ){
42811           /* Make sure the new file size is written into the inode right away.
42812           ** Otherwise the journal might resurrect following a power loss and
42813           ** cause the last transaction to roll back.  See
42814           ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
42815           */
42816           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
42817         }
42818       }
42819       pPager->journalOff = 0;
42820     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
42821       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
42822     ){
42823       rc = zeroJournalHdr(pPager, hasMaster);
42824       pPager->journalOff = 0;
42825     }else{
42826       /* This branch may be executed with Pager.journalMode==MEMORY if
42827       ** a hot-journal was just rolled back. In this case the journal
42828       ** file should be closed and deleted. If this connection writes to
42829       ** the database file, it will do so using an in-memory journal.
42830       */
42831       int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
42832       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
42833            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
42834            || pPager->journalMode==PAGER_JOURNALMODE_WAL
42835       );
42836       sqlite3OsClose(pPager->jfd);
42837       if( bDelete ){
42838         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
42839       }
42840     }
42841   }
42842 
42843 #ifdef SQLITE_CHECK_PAGES
42844   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
42845   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
42846     PgHdr *p = sqlite3PagerLookup(pPager, 1);
42847     if( p ){
42848       p->pageHash = 0;
42849       sqlite3PagerUnrefNotNull(p);
42850     }
42851   }
42852 #endif
42853 
42854   sqlite3BitvecDestroy(pPager->pInJournal);
42855   pPager->pInJournal = 0;
42856   pPager->nRec = 0;
42857   sqlite3PcacheCleanAll(pPager->pPCache);
42858   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
42859 
42860   if( pagerUseWal(pPager) ){
42861     /* Drop the WAL write-lock, if any. Also, if the connection was in
42862     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
42863     ** lock held on the database file.
42864     */
42865     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
42866     assert( rc2==SQLITE_OK );
42867   }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
42868     /* This branch is taken when committing a transaction in rollback-journal
42869     ** mode if the database file on disk is larger than the database image.
42870     ** At this point the journal has been finalized and the transaction
42871     ** successfully committed, but the EXCLUSIVE lock is still held on the
42872     ** file. So it is safe to truncate the database file to its minimum
42873     ** required size.  */
42874     assert( pPager->eLock==EXCLUSIVE_LOCK );
42875     rc = pager_truncate(pPager, pPager->dbSize);
42876   }
42877 
42878   if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
42879     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
42880     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
42881   }
42882 
42883   if( !pPager->exclusiveMode
42884    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
42885   ){
42886     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
42887     pPager->changeCountDone = 0;
42888   }
42889   pPager->eState = PAGER_READER;
42890   pPager->setMaster = 0;
42891 
42892   return (rc==SQLITE_OK?rc2:rc);
42893 }
42894 
42895 /*
42896 ** Execute a rollback if a transaction is active and unlock the
42897 ** database file.
42898 **
42899 ** If the pager has already entered the ERROR state, do not attempt
42900 ** the rollback at this time. Instead, pager_unlock() is called. The
42901 ** call to pager_unlock() will discard all in-memory pages, unlock
42902 ** the database file and move the pager back to OPEN state. If this
42903 ** means that there is a hot-journal left in the file-system, the next
42904 ** connection to obtain a shared lock on the pager (which may be this one)
42905 ** will roll it back.
42906 **
42907 ** If the pager has not already entered the ERROR state, but an IO or
42908 ** malloc error occurs during a rollback, then this will itself cause
42909 ** the pager to enter the ERROR state. Which will be cleared by the
42910 ** call to pager_unlock(), as described above.
42911 */
42912 static void pagerUnlockAndRollback(Pager *pPager){
42913   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
42914     assert( assert_pager_state(pPager) );
42915     if( pPager->eState>=PAGER_WRITER_LOCKED ){
42916       sqlite3BeginBenignMalloc();
42917       sqlite3PagerRollback(pPager);
42918       sqlite3EndBenignMalloc();
42919     }else if( !pPager->exclusiveMode ){
42920       assert( pPager->eState==PAGER_READER );
42921       pager_end_transaction(pPager, 0, 0);
42922     }
42923   }
42924   pager_unlock(pPager);
42925 }
42926 
42927 /*
42928 ** Parameter aData must point to a buffer of pPager->pageSize bytes
42929 ** of data. Compute and return a checksum based ont the contents of the
42930 ** page of data and the current value of pPager->cksumInit.
42931 **
42932 ** This is not a real checksum. It is really just the sum of the
42933 ** random initial value (pPager->cksumInit) and every 200th byte
42934 ** of the page data, starting with byte offset (pPager->pageSize%200).
42935 ** Each byte is interpreted as an 8-bit unsigned integer.
42936 **
42937 ** Changing the formula used to compute this checksum results in an
42938 ** incompatible journal file format.
42939 **
42940 ** If journal corruption occurs due to a power failure, the most likely
42941 ** scenario is that one end or the other of the record will be changed.
42942 ** It is much less likely that the two ends of the journal record will be
42943 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
42944 ** though fast and simple, catches the mostly likely kind of corruption.
42945 */
42946 static u32 pager_cksum(Pager *pPager, const u8 *aData){
42947   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
42948   int i = pPager->pageSize-200;          /* Loop counter */
42949   while( i>0 ){
42950     cksum += aData[i];
42951     i -= 200;
42952   }
42953   return cksum;
42954 }
42955 
42956 /*
42957 ** Report the current page size and number of reserved bytes back
42958 ** to the codec.
42959 */
42960 #ifdef SQLITE_HAS_CODEC
42961 static void pagerReportSize(Pager *pPager){
42962   if( pPager->xCodecSizeChng ){
42963     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
42964                            (int)pPager->nReserve);
42965   }
42966 }
42967 #else
42968 # define pagerReportSize(X)     /* No-op if we do not support a codec */
42969 #endif
42970 
42971 /*
42972 ** Read a single page from either the journal file (if isMainJrnl==1) or
42973 ** from the sub-journal (if isMainJrnl==0) and playback that page.
42974 ** The page begins at offset *pOffset into the file. The *pOffset
42975 ** value is increased to the start of the next page in the journal.
42976 **
42977 ** The main rollback journal uses checksums - the statement journal does
42978 ** not.
42979 **
42980 ** If the page number of the page record read from the (sub-)journal file
42981 ** is greater than the current value of Pager.dbSize, then playback is
42982 ** skipped and SQLITE_OK is returned.
42983 **
42984 ** If pDone is not NULL, then it is a record of pages that have already
42985 ** been played back.  If the page at *pOffset has already been played back
42986 ** (if the corresponding pDone bit is set) then skip the playback.
42987 ** Make sure the pDone bit corresponding to the *pOffset page is set
42988 ** prior to returning.
42989 **
42990 ** If the page record is successfully read from the (sub-)journal file
42991 ** and played back, then SQLITE_OK is returned. If an IO error occurs
42992 ** while reading the record from the (sub-)journal file or while writing
42993 ** to the database file, then the IO error code is returned. If data
42994 ** is successfully read from the (sub-)journal file but appears to be
42995 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
42996 ** two circumstances:
42997 **
42998 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
42999 **   * If the record is being rolled back from the main journal file
43000 **     and the checksum field does not match the record content.
43001 **
43002 ** Neither of these two scenarios are possible during a savepoint rollback.
43003 **
43004 ** If this is a savepoint rollback, then memory may have to be dynamically
43005 ** allocated by this function. If this is the case and an allocation fails,
43006 ** SQLITE_NOMEM is returned.
43007 */
43008 static int pager_playback_one_page(
43009   Pager *pPager,                /* The pager being played back */
43010   i64 *pOffset,                 /* Offset of record to playback */
43011   Bitvec *pDone,                /* Bitvec of pages already played back */
43012   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
43013   int isSavepnt                 /* True for a savepoint rollback */
43014 ){
43015   int rc;
43016   PgHdr *pPg;                   /* An existing page in the cache */
43017   Pgno pgno;                    /* The page number of a page in journal */
43018   u32 cksum;                    /* Checksum used for sanity checking */
43019   char *aData;                  /* Temporary storage for the page */
43020   sqlite3_file *jfd;            /* The file descriptor for the journal file */
43021   int isSynced;                 /* True if journal page is synced */
43022 
43023   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
43024   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
43025   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
43026   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
43027 
43028   aData = pPager->pTmpSpace;
43029   assert( aData );         /* Temp storage must have already been allocated */
43030   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
43031 
43032   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
43033   ** or savepoint rollback done at the request of the caller) or this is
43034   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
43035   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
43036   ** only reads from the main journal, not the sub-journal.
43037   */
43038   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
43039        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
43040   );
43041   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
43042 
43043   /* Read the page number and page data from the journal or sub-journal
43044   ** file. Return an error code to the caller if an IO error occurs.
43045   */
43046   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
43047   rc = read32bits(jfd, *pOffset, &pgno);
43048   if( rc!=SQLITE_OK ) return rc;
43049   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
43050   if( rc!=SQLITE_OK ) return rc;
43051   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
43052 
43053   /* Sanity checking on the page.  This is more important that I originally
43054   ** thought.  If a power failure occurs while the journal is being written,
43055   ** it could cause invalid data to be written into the journal.  We need to
43056   ** detect this invalid data (with high probability) and ignore it.
43057   */
43058   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
43059     assert( !isSavepnt );
43060     return SQLITE_DONE;
43061   }
43062   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
43063     return SQLITE_OK;
43064   }
43065   if( isMainJrnl ){
43066     rc = read32bits(jfd, (*pOffset)-4, &cksum);
43067     if( rc ) return rc;
43068     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
43069       return SQLITE_DONE;
43070     }
43071   }
43072 
43073   /* If this page has already been played by before during the current
43074   ** rollback, then don't bother to play it back again.
43075   */
43076   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
43077     return rc;
43078   }
43079 
43080   /* When playing back page 1, restore the nReserve setting
43081   */
43082   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
43083     pPager->nReserve = ((u8*)aData)[20];
43084     pagerReportSize(pPager);
43085   }
43086 
43087   /* If the pager is in CACHEMOD state, then there must be a copy of this
43088   ** page in the pager cache. In this case just update the pager cache,
43089   ** not the database file. The page is left marked dirty in this case.
43090   **
43091   ** An exception to the above rule: If the database is in no-sync mode
43092   ** and a page is moved during an incremental vacuum then the page may
43093   ** not be in the pager cache. Later: if a malloc() or IO error occurs
43094   ** during a Movepage() call, then the page may not be in the cache
43095   ** either. So the condition described in the above paragraph is not
43096   ** assert()able.
43097   **
43098   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
43099   ** pager cache if it exists and the main file. The page is then marked
43100   ** not dirty. Since this code is only executed in PAGER_OPEN state for
43101   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
43102   ** if the pager is in OPEN state.
43103   **
43104   ** Ticket #1171:  The statement journal might contain page content that is
43105   ** different from the page content at the start of the transaction.
43106   ** This occurs when a page is changed prior to the start of a statement
43107   ** then changed again within the statement.  When rolling back such a
43108   ** statement we must not write to the original database unless we know
43109   ** for certain that original page contents are synced into the main rollback
43110   ** journal.  Otherwise, a power loss might leave modified data in the
43111   ** database file without an entry in the rollback journal that can
43112   ** restore the database to its original form.  Two conditions must be
43113   ** met before writing to the database files. (1) the database must be
43114   ** locked.  (2) we know that the original page content is fully synced
43115   ** in the main journal either because the page is not in cache or else
43116   ** the page is marked as needSync==0.
43117   **
43118   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
43119   ** is possible to fail a statement on a database that does not yet exist.
43120   ** Do not attempt to write if database file has never been opened.
43121   */
43122   if( pagerUseWal(pPager) ){
43123     pPg = 0;
43124   }else{
43125     pPg = sqlite3PagerLookup(pPager, pgno);
43126   }
43127   assert( pPg || !MEMDB );
43128   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
43129   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
43130            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
43131            (isMainJrnl?"main-journal":"sub-journal")
43132   ));
43133   if( isMainJrnl ){
43134     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
43135   }else{
43136     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
43137   }
43138   if( isOpen(pPager->fd)
43139    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
43140    && isSynced
43141   ){
43142     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
43143     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
43144     assert( !pagerUseWal(pPager) );
43145     rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
43146     if( pgno>pPager->dbFileSize ){
43147       pPager->dbFileSize = pgno;
43148     }
43149     if( pPager->pBackup ){
43150       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
43151       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
43152       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
43153     }
43154   }else if( !isMainJrnl && pPg==0 ){
43155     /* If this is a rollback of a savepoint and data was not written to
43156     ** the database and the page is not in-memory, there is a potential
43157     ** problem. When the page is next fetched by the b-tree layer, it
43158     ** will be read from the database file, which may or may not be
43159     ** current.
43160     **
43161     ** There are a couple of different ways this can happen. All are quite
43162     ** obscure. When running in synchronous mode, this can only happen
43163     ** if the page is on the free-list at the start of the transaction, then
43164     ** populated, then moved using sqlite3PagerMovepage().
43165     **
43166     ** The solution is to add an in-memory page to the cache containing
43167     ** the data just read from the sub-journal. Mark the page as dirty
43168     ** and if the pager requires a journal-sync, then mark the page as
43169     ** requiring a journal-sync before it is written.
43170     */
43171     assert( isSavepnt );
43172     assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
43173     pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
43174     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
43175     assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
43176     pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
43177     if( rc!=SQLITE_OK ) return rc;
43178     pPg->flags &= ~PGHDR_NEED_READ;
43179     sqlite3PcacheMakeDirty(pPg);
43180   }
43181   if( pPg ){
43182     /* No page should ever be explicitly rolled back that is in use, except
43183     ** for page 1 which is held in use in order to keep the lock on the
43184     ** database active. However such a page may be rolled back as a result
43185     ** of an internal error resulting in an automatic call to
43186     ** sqlite3PagerRollback().
43187     */
43188     void *pData;
43189     pData = pPg->pData;
43190     memcpy(pData, (u8*)aData, pPager->pageSize);
43191     pPager->xReiniter(pPg);
43192     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
43193       /* If the contents of this page were just restored from the main
43194       ** journal file, then its content must be as they were when the
43195       ** transaction was first opened. In this case we can mark the page
43196       ** as clean, since there will be no need to write it out to the
43197       ** database.
43198       **
43199       ** There is one exception to this rule. If the page is being rolled
43200       ** back as part of a savepoint (or statement) rollback from an
43201       ** unsynced portion of the main journal file, then it is not safe
43202       ** to mark the page as clean. This is because marking the page as
43203       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
43204       ** already in the journal file (recorded in Pager.pInJournal) and
43205       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
43206       ** again within this transaction, it will be marked as dirty but
43207       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
43208       ** be written out into the database file before its journal file
43209       ** segment is synced. If a crash occurs during or following this,
43210       ** database corruption may ensue.
43211       */
43212       assert( !pagerUseWal(pPager) );
43213       sqlite3PcacheMakeClean(pPg);
43214     }
43215     pager_set_pagehash(pPg);
43216 
43217     /* If this was page 1, then restore the value of Pager.dbFileVers.
43218     ** Do this before any decoding. */
43219     if( pgno==1 ){
43220       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
43221     }
43222 
43223     /* Decode the page just read from disk */
43224     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
43225     sqlite3PcacheRelease(pPg);
43226   }
43227   return rc;
43228 }
43229 
43230 /*
43231 ** Parameter zMaster is the name of a master journal file. A single journal
43232 ** file that referred to the master journal file has just been rolled back.
43233 ** This routine checks if it is possible to delete the master journal file,
43234 ** and does so if it is.
43235 **
43236 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
43237 ** available for use within this function.
43238 **
43239 ** When a master journal file is created, it is populated with the names
43240 ** of all of its child journals, one after another, formatted as utf-8
43241 ** encoded text. The end of each child journal file is marked with a
43242 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
43243 ** file for a transaction involving two databases might be:
43244 **
43245 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
43246 **
43247 ** A master journal file may only be deleted once all of its child
43248 ** journals have been rolled back.
43249 **
43250 ** This function reads the contents of the master-journal file into
43251 ** memory and loops through each of the child journal names. For
43252 ** each child journal, it checks if:
43253 **
43254 **   * if the child journal exists, and if so
43255 **   * if the child journal contains a reference to master journal
43256 **     file zMaster
43257 **
43258 ** If a child journal can be found that matches both of the criteria
43259 ** above, this function returns without doing anything. Otherwise, if
43260 ** no such child journal can be found, file zMaster is deleted from
43261 ** the file-system using sqlite3OsDelete().
43262 **
43263 ** If an IO error within this function, an error code is returned. This
43264 ** function allocates memory by calling sqlite3Malloc(). If an allocation
43265 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
43266 ** occur, SQLITE_OK is returned.
43267 **
43268 ** TODO: This function allocates a single block of memory to load
43269 ** the entire contents of the master journal file. This could be
43270 ** a couple of kilobytes or so - potentially larger than the page
43271 ** size.
43272 */
43273 static int pager_delmaster(Pager *pPager, const char *zMaster){
43274   sqlite3_vfs *pVfs = pPager->pVfs;
43275   int rc;                   /* Return code */
43276   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
43277   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
43278   char *zMasterJournal = 0; /* Contents of master journal file */
43279   i64 nMasterJournal;       /* Size of master journal file */
43280   char *zJournal;           /* Pointer to one journal within MJ file */
43281   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
43282   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
43283 
43284   /* Allocate space for both the pJournal and pMaster file descriptors.
43285   ** If successful, open the master journal file for reading.
43286   */
43287   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
43288   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
43289   if( !pMaster ){
43290     rc = SQLITE_NOMEM;
43291   }else{
43292     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
43293     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
43294   }
43295   if( rc!=SQLITE_OK ) goto delmaster_out;
43296 
43297   /* Load the entire master journal file into space obtained from
43298   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
43299   ** sufficient space (in zMasterPtr) to hold the names of master
43300   ** journal files extracted from regular rollback-journals.
43301   */
43302   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
43303   if( rc!=SQLITE_OK ) goto delmaster_out;
43304   nMasterPtr = pVfs->mxPathname+1;
43305   zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
43306   if( !zMasterJournal ){
43307     rc = SQLITE_NOMEM;
43308     goto delmaster_out;
43309   }
43310   zMasterPtr = &zMasterJournal[nMasterJournal+1];
43311   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
43312   if( rc!=SQLITE_OK ) goto delmaster_out;
43313   zMasterJournal[nMasterJournal] = 0;
43314 
43315   zJournal = zMasterJournal;
43316   while( (zJournal-zMasterJournal)<nMasterJournal ){
43317     int exists;
43318     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
43319     if( rc!=SQLITE_OK ){
43320       goto delmaster_out;
43321     }
43322     if( exists ){
43323       /* One of the journals pointed to by the master journal exists.
43324       ** Open it and check if it points at the master journal. If
43325       ** so, return without deleting the master journal file.
43326       */
43327       int c;
43328       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
43329       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
43330       if( rc!=SQLITE_OK ){
43331         goto delmaster_out;
43332       }
43333 
43334       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
43335       sqlite3OsClose(pJournal);
43336       if( rc!=SQLITE_OK ){
43337         goto delmaster_out;
43338       }
43339 
43340       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
43341       if( c ){
43342         /* We have a match. Do not delete the master journal file. */
43343         goto delmaster_out;
43344       }
43345     }
43346     zJournal += (sqlite3Strlen30(zJournal)+1);
43347   }
43348 
43349   sqlite3OsClose(pMaster);
43350   rc = sqlite3OsDelete(pVfs, zMaster, 0);
43351 
43352 delmaster_out:
43353   sqlite3_free(zMasterJournal);
43354   if( pMaster ){
43355     sqlite3OsClose(pMaster);
43356     assert( !isOpen(pJournal) );
43357     sqlite3_free(pMaster);
43358   }
43359   return rc;
43360 }
43361 
43362 
43363 /*
43364 ** This function is used to change the actual size of the database
43365 ** file in the file-system. This only happens when committing a transaction,
43366 ** or rolling back a transaction (including rolling back a hot-journal).
43367 **
43368 ** If the main database file is not open, or the pager is not in either
43369 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
43370 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
43371 ** If the file on disk is currently larger than nPage pages, then use the VFS
43372 ** xTruncate() method to truncate it.
43373 **
43374 ** Or, it might be the case that the file on disk is smaller than
43375 ** nPage pages. Some operating system implementations can get confused if
43376 ** you try to truncate a file to some size that is larger than it
43377 ** currently is, so detect this case and write a single zero byte to
43378 ** the end of the new file instead.
43379 **
43380 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
43381 ** the database file, return the error code to the caller.
43382 */
43383 static int pager_truncate(Pager *pPager, Pgno nPage){
43384   int rc = SQLITE_OK;
43385   assert( pPager->eState!=PAGER_ERROR );
43386   assert( pPager->eState!=PAGER_READER );
43387 
43388   if( isOpen(pPager->fd)
43389    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
43390   ){
43391     i64 currentSize, newSize;
43392     int szPage = pPager->pageSize;
43393     assert( pPager->eLock==EXCLUSIVE_LOCK );
43394     /* TODO: Is it safe to use Pager.dbFileSize here? */
43395     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
43396     newSize = szPage*(i64)nPage;
43397     if( rc==SQLITE_OK && currentSize!=newSize ){
43398       if( currentSize>newSize ){
43399         rc = sqlite3OsTruncate(pPager->fd, newSize);
43400       }else if( (currentSize+szPage)<=newSize ){
43401         char *pTmp = pPager->pTmpSpace;
43402         memset(pTmp, 0, szPage);
43403         testcase( (newSize-szPage) == currentSize );
43404         testcase( (newSize-szPage) >  currentSize );
43405         rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
43406       }
43407       if( rc==SQLITE_OK ){
43408         pPager->dbFileSize = nPage;
43409       }
43410     }
43411   }
43412   return rc;
43413 }
43414 
43415 /*
43416 ** Return a sanitized version of the sector-size of OS file pFile. The
43417 ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
43418 */
43419 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
43420   int iRet = sqlite3OsSectorSize(pFile);
43421   if( iRet<32 ){
43422     iRet = 512;
43423   }else if( iRet>MAX_SECTOR_SIZE ){
43424     assert( MAX_SECTOR_SIZE>=512 );
43425     iRet = MAX_SECTOR_SIZE;
43426   }
43427   return iRet;
43428 }
43429 
43430 /*
43431 ** Set the value of the Pager.sectorSize variable for the given
43432 ** pager based on the value returned by the xSectorSize method
43433 ** of the open database file. The sector size will be used
43434 ** to determine the size and alignment of journal header and
43435 ** master journal pointers within created journal files.
43436 **
43437 ** For temporary files the effective sector size is always 512 bytes.
43438 **
43439 ** Otherwise, for non-temporary files, the effective sector size is
43440 ** the value returned by the xSectorSize() method rounded up to 32 if
43441 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
43442 ** is greater than MAX_SECTOR_SIZE.
43443 **
43444 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
43445 ** the effective sector size to its minimum value (512).  The purpose of
43446 ** pPager->sectorSize is to define the "blast radius" of bytes that
43447 ** might change if a crash occurs while writing to a single byte in
43448 ** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
43449 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
43450 ** size.  For backwards compatibility of the rollback journal file format,
43451 ** we cannot reduce the effective sector size below 512.
43452 */
43453 static void setSectorSize(Pager *pPager){
43454   assert( isOpen(pPager->fd) || pPager->tempFile );
43455 
43456   if( pPager->tempFile
43457    || (sqlite3OsDeviceCharacteristics(pPager->fd) &
43458               SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
43459   ){
43460     /* Sector size doesn't matter for temporary files. Also, the file
43461     ** may not have been opened yet, in which case the OsSectorSize()
43462     ** call will segfault. */
43463     pPager->sectorSize = 512;
43464   }else{
43465     pPager->sectorSize = sqlite3SectorSize(pPager->fd);
43466   }
43467 }
43468 
43469 /*
43470 ** Playback the journal and thus restore the database file to
43471 ** the state it was in before we started making changes.
43472 **
43473 ** The journal file format is as follows:
43474 **
43475 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
43476 **  (2)  4 byte big-endian integer which is the number of valid page records
43477 **       in the journal.  If this value is 0xffffffff, then compute the
43478 **       number of page records from the journal size.
43479 **  (3)  4 byte big-endian integer which is the initial value for the
43480 **       sanity checksum.
43481 **  (4)  4 byte integer which is the number of pages to truncate the
43482 **       database to during a rollback.
43483 **  (5)  4 byte big-endian integer which is the sector size.  The header
43484 **       is this many bytes in size.
43485 **  (6)  4 byte big-endian integer which is the page size.
43486 **  (7)  zero padding out to the next sector size.
43487 **  (8)  Zero or more pages instances, each as follows:
43488 **        +  4 byte page number.
43489 **        +  pPager->pageSize bytes of data.
43490 **        +  4 byte checksum
43491 **
43492 ** When we speak of the journal header, we mean the first 7 items above.
43493 ** Each entry in the journal is an instance of the 8th item.
43494 **
43495 ** Call the value from the second bullet "nRec".  nRec is the number of
43496 ** valid page entries in the journal.  In most cases, you can compute the
43497 ** value of nRec from the size of the journal file.  But if a power
43498 ** failure occurred while the journal was being written, it could be the
43499 ** case that the size of the journal file had already been increased but
43500 ** the extra entries had not yet made it safely to disk.  In such a case,
43501 ** the value of nRec computed from the file size would be too large.  For
43502 ** that reason, we always use the nRec value in the header.
43503 **
43504 ** If the nRec value is 0xffffffff it means that nRec should be computed
43505 ** from the file size.  This value is used when the user selects the
43506 ** no-sync option for the journal.  A power failure could lead to corruption
43507 ** in this case.  But for things like temporary table (which will be
43508 ** deleted when the power is restored) we don't care.
43509 **
43510 ** If the file opened as the journal file is not a well-formed
43511 ** journal file then all pages up to the first corrupted page are rolled
43512 ** back (or no pages if the journal header is corrupted). The journal file
43513 ** is then deleted and SQLITE_OK returned, just as if no corruption had
43514 ** been encountered.
43515 **
43516 ** If an I/O or malloc() error occurs, the journal-file is not deleted
43517 ** and an error code is returned.
43518 **
43519 ** The isHot parameter indicates that we are trying to rollback a journal
43520 ** that might be a hot journal.  Or, it could be that the journal is
43521 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
43522 ** If the journal really is hot, reset the pager cache prior rolling
43523 ** back any content.  If the journal is merely persistent, no reset is
43524 ** needed.
43525 */
43526 static int pager_playback(Pager *pPager, int isHot){
43527   sqlite3_vfs *pVfs = pPager->pVfs;
43528   i64 szJ;                 /* Size of the journal file in bytes */
43529   u32 nRec;                /* Number of Records in the journal */
43530   u32 u;                   /* Unsigned loop counter */
43531   Pgno mxPg = 0;           /* Size of the original file in pages */
43532   int rc;                  /* Result code of a subroutine */
43533   int res = 1;             /* Value returned by sqlite3OsAccess() */
43534   char *zMaster = 0;       /* Name of master journal file if any */
43535   int needPagerReset;      /* True to reset page prior to first page rollback */
43536   int nPlayback = 0;       /* Total number of pages restored from journal */
43537 
43538   /* Figure out how many records are in the journal.  Abort early if
43539   ** the journal is empty.
43540   */
43541   assert( isOpen(pPager->jfd) );
43542   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
43543   if( rc!=SQLITE_OK ){
43544     goto end_playback;
43545   }
43546 
43547   /* Read the master journal name from the journal, if it is present.
43548   ** If a master journal file name is specified, but the file is not
43549   ** present on disk, then the journal is not hot and does not need to be
43550   ** played back.
43551   **
43552   ** TODO: Technically the following is an error because it assumes that
43553   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
43554   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
43555   **  mxPathname is 512, which is the same as the minimum allowable value
43556   ** for pageSize.
43557   */
43558   zMaster = pPager->pTmpSpace;
43559   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
43560   if( rc==SQLITE_OK && zMaster[0] ){
43561     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
43562   }
43563   zMaster = 0;
43564   if( rc!=SQLITE_OK || !res ){
43565     goto end_playback;
43566   }
43567   pPager->journalOff = 0;
43568   needPagerReset = isHot;
43569 
43570   /* This loop terminates either when a readJournalHdr() or
43571   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
43572   ** occurs.
43573   */
43574   while( 1 ){
43575     /* Read the next journal header from the journal file.  If there are
43576     ** not enough bytes left in the journal file for a complete header, or
43577     ** it is corrupted, then a process must have failed while writing it.
43578     ** This indicates nothing more needs to be rolled back.
43579     */
43580     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
43581     if( rc!=SQLITE_OK ){
43582       if( rc==SQLITE_DONE ){
43583         rc = SQLITE_OK;
43584       }
43585       goto end_playback;
43586     }
43587 
43588     /* If nRec is 0xffffffff, then this journal was created by a process
43589     ** working in no-sync mode. This means that the rest of the journal
43590     ** file consists of pages, there are no more journal headers. Compute
43591     ** the value of nRec based on this assumption.
43592     */
43593     if( nRec==0xffffffff ){
43594       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
43595       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
43596     }
43597 
43598     /* If nRec is 0 and this rollback is of a transaction created by this
43599     ** process and if this is the final header in the journal, then it means
43600     ** that this part of the journal was being filled but has not yet been
43601     ** synced to disk.  Compute the number of pages based on the remaining
43602     ** size of the file.
43603     **
43604     ** The third term of the test was added to fix ticket #2565.
43605     ** When rolling back a hot journal, nRec==0 always means that the next
43606     ** chunk of the journal contains zero pages to be rolled back.  But
43607     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
43608     ** the journal, it means that the journal might contain additional
43609     ** pages that need to be rolled back and that the number of pages
43610     ** should be computed based on the journal file size.
43611     */
43612     if( nRec==0 && !isHot &&
43613         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
43614       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
43615     }
43616 
43617     /* If this is the first header read from the journal, truncate the
43618     ** database file back to its original size.
43619     */
43620     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
43621       rc = pager_truncate(pPager, mxPg);
43622       if( rc!=SQLITE_OK ){
43623         goto end_playback;
43624       }
43625       pPager->dbSize = mxPg;
43626     }
43627 
43628     /* Copy original pages out of the journal and back into the
43629     ** database file and/or page cache.
43630     */
43631     for(u=0; u<nRec; u++){
43632       if( needPagerReset ){
43633         pager_reset(pPager);
43634         needPagerReset = 0;
43635       }
43636       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
43637       if( rc==SQLITE_OK ){
43638         nPlayback++;
43639       }else{
43640         if( rc==SQLITE_DONE ){
43641           pPager->journalOff = szJ;
43642           break;
43643         }else if( rc==SQLITE_IOERR_SHORT_READ ){
43644           /* If the journal has been truncated, simply stop reading and
43645           ** processing the journal. This might happen if the journal was
43646           ** not completely written and synced prior to a crash.  In that
43647           ** case, the database should have never been written in the
43648           ** first place so it is OK to simply abandon the rollback. */
43649           rc = SQLITE_OK;
43650           goto end_playback;
43651         }else{
43652           /* If we are unable to rollback, quit and return the error
43653           ** code.  This will cause the pager to enter the error state
43654           ** so that no further harm will be done.  Perhaps the next
43655           ** process to come along will be able to rollback the database.
43656           */
43657           goto end_playback;
43658         }
43659       }
43660     }
43661   }
43662   /*NOTREACHED*/
43663   assert( 0 );
43664 
43665 end_playback:
43666   /* Following a rollback, the database file should be back in its original
43667   ** state prior to the start of the transaction, so invoke the
43668   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
43669   ** assertion that the transaction counter was modified.
43670   */
43671 #ifdef SQLITE_DEBUG
43672   if( pPager->fd->pMethods ){
43673     sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
43674   }
43675 #endif
43676 
43677   /* If this playback is happening automatically as a result of an IO or
43678   ** malloc error that occurred after the change-counter was updated but
43679   ** before the transaction was committed, then the change-counter
43680   ** modification may just have been reverted. If this happens in exclusive
43681   ** mode, then subsequent transactions performed by the connection will not
43682   ** update the change-counter at all. This may lead to cache inconsistency
43683   ** problems for other processes at some point in the future. So, just
43684   ** in case this has happened, clear the changeCountDone flag now.
43685   */
43686   pPager->changeCountDone = pPager->tempFile;
43687 
43688   if( rc==SQLITE_OK ){
43689     zMaster = pPager->pTmpSpace;
43690     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
43691     testcase( rc!=SQLITE_OK );
43692   }
43693   if( rc==SQLITE_OK
43694    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
43695   ){
43696     rc = sqlite3PagerSync(pPager, 0);
43697   }
43698   if( rc==SQLITE_OK ){
43699     rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
43700     testcase( rc!=SQLITE_OK );
43701   }
43702   if( rc==SQLITE_OK && zMaster[0] && res ){
43703     /* If there was a master journal and this routine will return success,
43704     ** see if it is possible to delete the master journal.
43705     */
43706     rc = pager_delmaster(pPager, zMaster);
43707     testcase( rc!=SQLITE_OK );
43708   }
43709   if( isHot && nPlayback ){
43710     sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
43711                 nPlayback, pPager->zJournal);
43712   }
43713 
43714   /* The Pager.sectorSize variable may have been updated while rolling
43715   ** back a journal created by a process with a different sector size
43716   ** value. Reset it to the correct value for this process.
43717   */
43718   setSectorSize(pPager);
43719   return rc;
43720 }
43721 
43722 
43723 /*
43724 ** Read the content for page pPg out of the database file and into
43725 ** pPg->pData. A shared lock or greater must be held on the database
43726 ** file before this function is called.
43727 **
43728 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
43729 ** the value read from the database file.
43730 **
43731 ** If an IO error occurs, then the IO error is returned to the caller.
43732 ** Otherwise, SQLITE_OK is returned.
43733 */
43734 static int readDbPage(PgHdr *pPg, u32 iFrame){
43735   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
43736   Pgno pgno = pPg->pgno;       /* Page number to read */
43737   int rc = SQLITE_OK;          /* Return code */
43738   int pgsz = pPager->pageSize; /* Number of bytes to read */
43739 
43740   assert( pPager->eState>=PAGER_READER && !MEMDB );
43741   assert( isOpen(pPager->fd) );
43742 
43743 #ifndef SQLITE_OMIT_WAL
43744   if( iFrame ){
43745     /* Try to pull the page from the write-ahead log. */
43746     rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
43747   }else
43748 #endif
43749   {
43750     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
43751     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
43752     if( rc==SQLITE_IOERR_SHORT_READ ){
43753       rc = SQLITE_OK;
43754     }
43755   }
43756 
43757   if( pgno==1 ){
43758     if( rc ){
43759       /* If the read is unsuccessful, set the dbFileVers[] to something
43760       ** that will never be a valid file version.  dbFileVers[] is a copy
43761       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
43762       ** zero or the size of the database in page. Bytes 32..35 and 35..39
43763       ** should be page numbers which are never 0xffffffff.  So filling
43764       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
43765       **
43766       ** For an encrypted database, the situation is more complex:  bytes
43767       ** 24..39 of the database are white noise.  But the probability of
43768       ** white noising equaling 16 bytes of 0xff is vanishingly small so
43769       ** we should still be ok.
43770       */
43771       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
43772     }else{
43773       u8 *dbFileVers = &((u8*)pPg->pData)[24];
43774       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
43775     }
43776   }
43777   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
43778 
43779   PAGER_INCR(sqlite3_pager_readdb_count);
43780   PAGER_INCR(pPager->nRead);
43781   IOTRACE(("PGIN %p %d\n", pPager, pgno));
43782   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
43783                PAGERID(pPager), pgno, pager_pagehash(pPg)));
43784 
43785   return rc;
43786 }
43787 
43788 /*
43789 ** Update the value of the change-counter at offsets 24 and 92 in
43790 ** the header and the sqlite version number at offset 96.
43791 **
43792 ** This is an unconditional update.  See also the pager_incr_changecounter()
43793 ** routine which only updates the change-counter if the update is actually
43794 ** needed, as determined by the pPager->changeCountDone state variable.
43795 */
43796 static void pager_write_changecounter(PgHdr *pPg){
43797   u32 change_counter;
43798 
43799   /* Increment the value just read and write it back to byte 24. */
43800   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
43801   put32bits(((char*)pPg->pData)+24, change_counter);
43802 
43803   /* Also store the SQLite version number in bytes 96..99 and in
43804   ** bytes 92..95 store the change counter for which the version number
43805   ** is valid. */
43806   put32bits(((char*)pPg->pData)+92, change_counter);
43807   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
43808 }
43809 
43810 #ifndef SQLITE_OMIT_WAL
43811 /*
43812 ** This function is invoked once for each page that has already been
43813 ** written into the log file when a WAL transaction is rolled back.
43814 ** Parameter iPg is the page number of said page. The pCtx argument
43815 ** is actually a pointer to the Pager structure.
43816 **
43817 ** If page iPg is present in the cache, and has no outstanding references,
43818 ** it is discarded. Otherwise, if there are one or more outstanding
43819 ** references, the page content is reloaded from the database. If the
43820 ** attempt to reload content from the database is required and fails,
43821 ** return an SQLite error code. Otherwise, SQLITE_OK.
43822 */
43823 static int pagerUndoCallback(void *pCtx, Pgno iPg){
43824   int rc = SQLITE_OK;
43825   Pager *pPager = (Pager *)pCtx;
43826   PgHdr *pPg;
43827 
43828   assert( pagerUseWal(pPager) );
43829   pPg = sqlite3PagerLookup(pPager, iPg);
43830   if( pPg ){
43831     if( sqlite3PcachePageRefcount(pPg)==1 ){
43832       sqlite3PcacheDrop(pPg);
43833     }else{
43834       u32 iFrame = 0;
43835       rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
43836       if( rc==SQLITE_OK ){
43837         rc = readDbPage(pPg, iFrame);
43838       }
43839       if( rc==SQLITE_OK ){
43840         pPager->xReiniter(pPg);
43841       }
43842       sqlite3PagerUnrefNotNull(pPg);
43843     }
43844   }
43845 
43846   /* Normally, if a transaction is rolled back, any backup processes are
43847   ** updated as data is copied out of the rollback journal and into the
43848   ** database. This is not generally possible with a WAL database, as
43849   ** rollback involves simply truncating the log file. Therefore, if one
43850   ** or more frames have already been written to the log (and therefore
43851   ** also copied into the backup databases) as part of this transaction,
43852   ** the backups must be restarted.
43853   */
43854   sqlite3BackupRestart(pPager->pBackup);
43855 
43856   return rc;
43857 }
43858 
43859 /*
43860 ** This function is called to rollback a transaction on a WAL database.
43861 */
43862 static int pagerRollbackWal(Pager *pPager){
43863   int rc;                         /* Return Code */
43864   PgHdr *pList;                   /* List of dirty pages to revert */
43865 
43866   /* For all pages in the cache that are currently dirty or have already
43867   ** been written (but not committed) to the log file, do one of the
43868   ** following:
43869   **
43870   **   + Discard the cached page (if refcount==0), or
43871   **   + Reload page content from the database (if refcount>0).
43872   */
43873   pPager->dbSize = pPager->dbOrigSize;
43874   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
43875   pList = sqlite3PcacheDirtyList(pPager->pPCache);
43876   while( pList && rc==SQLITE_OK ){
43877     PgHdr *pNext = pList->pDirty;
43878     rc = pagerUndoCallback((void *)pPager, pList->pgno);
43879     pList = pNext;
43880   }
43881 
43882   return rc;
43883 }
43884 
43885 /*
43886 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
43887 ** the contents of the list of pages headed by pList (connected by pDirty),
43888 ** this function notifies any active backup processes that the pages have
43889 ** changed.
43890 **
43891 ** The list of pages passed into this routine is always sorted by page number.
43892 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
43893 */
43894 static int pagerWalFrames(
43895   Pager *pPager,                  /* Pager object */
43896   PgHdr *pList,                   /* List of frames to log */
43897   Pgno nTruncate,                 /* Database size after this commit */
43898   int isCommit                    /* True if this is a commit */
43899 ){
43900   int rc;                         /* Return code */
43901   int nList;                      /* Number of pages in pList */
43902 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
43903   PgHdr *p;                       /* For looping over pages */
43904 #endif
43905 
43906   assert( pPager->pWal );
43907   assert( pList );
43908 #ifdef SQLITE_DEBUG
43909   /* Verify that the page list is in accending order */
43910   for(p=pList; p && p->pDirty; p=p->pDirty){
43911     assert( p->pgno < p->pDirty->pgno );
43912   }
43913 #endif
43914 
43915   assert( pList->pDirty==0 || isCommit );
43916   if( isCommit ){
43917     /* If a WAL transaction is being committed, there is no point in writing
43918     ** any pages with page numbers greater than nTruncate into the WAL file.
43919     ** They will never be read by any client. So remove them from the pDirty
43920     ** list here. */
43921     PgHdr *p;
43922     PgHdr **ppNext = &pList;
43923     nList = 0;
43924     for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
43925       if( p->pgno<=nTruncate ){
43926         ppNext = &p->pDirty;
43927         nList++;
43928       }
43929     }
43930     assert( pList );
43931   }else{
43932     nList = 1;
43933   }
43934   pPager->aStat[PAGER_STAT_WRITE] += nList;
43935 
43936   if( pList->pgno==1 ) pager_write_changecounter(pList);
43937   rc = sqlite3WalFrames(pPager->pWal,
43938       pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
43939   );
43940   if( rc==SQLITE_OK && pPager->pBackup ){
43941     PgHdr *p;
43942     for(p=pList; p; p=p->pDirty){
43943       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
43944     }
43945   }
43946 
43947 #ifdef SQLITE_CHECK_PAGES
43948   pList = sqlite3PcacheDirtyList(pPager->pPCache);
43949   for(p=pList; p; p=p->pDirty){
43950     pager_set_pagehash(p);
43951   }
43952 #endif
43953 
43954   return rc;
43955 }
43956 
43957 /*
43958 ** Begin a read transaction on the WAL.
43959 **
43960 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
43961 ** makes a snapshot of the database at the current point in time and preserves
43962 ** that snapshot for use by the reader in spite of concurrently changes by
43963 ** other writers or checkpointers.
43964 */
43965 static int pagerBeginReadTransaction(Pager *pPager){
43966   int rc;                         /* Return code */
43967   int changed = 0;                /* True if cache must be reset */
43968 
43969   assert( pagerUseWal(pPager) );
43970   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
43971 
43972   /* sqlite3WalEndReadTransaction() was not called for the previous
43973   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
43974   ** are in locking_mode=NORMAL and EndRead() was previously called,
43975   ** the duplicate call is harmless.
43976   */
43977   sqlite3WalEndReadTransaction(pPager->pWal);
43978 
43979   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
43980   if( rc!=SQLITE_OK || changed ){
43981     pager_reset(pPager);
43982     if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
43983   }
43984 
43985   return rc;
43986 }
43987 #endif
43988 
43989 /*
43990 ** This function is called as part of the transition from PAGER_OPEN
43991 ** to PAGER_READER state to determine the size of the database file
43992 ** in pages (assuming the page size currently stored in Pager.pageSize).
43993 **
43994 ** If no error occurs, SQLITE_OK is returned and the size of the database
43995 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
43996 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
43997 */
43998 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
43999   Pgno nPage;                     /* Value to return via *pnPage */
44000 
44001   /* Query the WAL sub-system for the database size. The WalDbsize()
44002   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
44003   ** if the database size is not available. The database size is not
44004   ** available from the WAL sub-system if the log file is empty or
44005   ** contains no valid committed transactions.
44006   */
44007   assert( pPager->eState==PAGER_OPEN );
44008   assert( pPager->eLock>=SHARED_LOCK );
44009   nPage = sqlite3WalDbsize(pPager->pWal);
44010 
44011   /* If the database size was not available from the WAL sub-system,
44012   ** determine it based on the size of the database file. If the size
44013   ** of the database file is not an integer multiple of the page-size,
44014   ** round down to the nearest page. Except, any file larger than 0
44015   ** bytes in size is considered to contain at least one page.
44016   */
44017   if( nPage==0 ){
44018     i64 n = 0;                    /* Size of db file in bytes */
44019     assert( isOpen(pPager->fd) || pPager->tempFile );
44020     if( isOpen(pPager->fd) ){
44021       int rc = sqlite3OsFileSize(pPager->fd, &n);
44022       if( rc!=SQLITE_OK ){
44023         return rc;
44024       }
44025     }
44026     nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
44027   }
44028 
44029   /* If the current number of pages in the file is greater than the
44030   ** configured maximum pager number, increase the allowed limit so
44031   ** that the file can be read.
44032   */
44033   if( nPage>pPager->mxPgno ){
44034     pPager->mxPgno = (Pgno)nPage;
44035   }
44036 
44037   *pnPage = nPage;
44038   return SQLITE_OK;
44039 }
44040 
44041 #ifndef SQLITE_OMIT_WAL
44042 /*
44043 ** Check if the *-wal file that corresponds to the database opened by pPager
44044 ** exists if the database is not empy, or verify that the *-wal file does
44045 ** not exist (by deleting it) if the database file is empty.
44046 **
44047 ** If the database is not empty and the *-wal file exists, open the pager
44048 ** in WAL mode.  If the database is empty or if no *-wal file exists and
44049 ** if no error occurs, make sure Pager.journalMode is not set to
44050 ** PAGER_JOURNALMODE_WAL.
44051 **
44052 ** Return SQLITE_OK or an error code.
44053 **
44054 ** The caller must hold a SHARED lock on the database file to call this
44055 ** function. Because an EXCLUSIVE lock on the db file is required to delete
44056 ** a WAL on a none-empty database, this ensures there is no race condition
44057 ** between the xAccess() below and an xDelete() being executed by some
44058 ** other connection.
44059 */
44060 static int pagerOpenWalIfPresent(Pager *pPager){
44061   int rc = SQLITE_OK;
44062   assert( pPager->eState==PAGER_OPEN );
44063   assert( pPager->eLock>=SHARED_LOCK );
44064 
44065   if( !pPager->tempFile ){
44066     int isWal;                    /* True if WAL file exists */
44067     Pgno nPage;                   /* Size of the database file */
44068 
44069     rc = pagerPagecount(pPager, &nPage);
44070     if( rc ) return rc;
44071     if( nPage==0 ){
44072       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
44073       if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
44074       isWal = 0;
44075     }else{
44076       rc = sqlite3OsAccess(
44077           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
44078       );
44079     }
44080     if( rc==SQLITE_OK ){
44081       if( isWal ){
44082         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
44083         rc = sqlite3PagerOpenWal(pPager, 0);
44084       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
44085         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
44086       }
44087     }
44088   }
44089   return rc;
44090 }
44091 #endif
44092 
44093 /*
44094 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
44095 ** the entire master journal file. The case pSavepoint==NULL occurs when
44096 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
44097 ** savepoint.
44098 **
44099 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
44100 ** being rolled back), then the rollback consists of up to three stages,
44101 ** performed in the order specified:
44102 **
44103 **   * Pages are played back from the main journal starting at byte
44104 **     offset PagerSavepoint.iOffset and continuing to
44105 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
44106 **     file if PagerSavepoint.iHdrOffset is zero.
44107 **
44108 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
44109 **     back starting from the journal header immediately following
44110 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
44111 **
44112 **   * Pages are then played back from the sub-journal file, starting
44113 **     with the PagerSavepoint.iSubRec and continuing to the end of
44114 **     the journal file.
44115 **
44116 ** Throughout the rollback process, each time a page is rolled back, the
44117 ** corresponding bit is set in a bitvec structure (variable pDone in the
44118 ** implementation below). This is used to ensure that a page is only
44119 ** rolled back the first time it is encountered in either journal.
44120 **
44121 ** If pSavepoint is NULL, then pages are only played back from the main
44122 ** journal file. There is no need for a bitvec in this case.
44123 **
44124 ** In either case, before playback commences the Pager.dbSize variable
44125 ** is reset to the value that it held at the start of the savepoint
44126 ** (or transaction). No page with a page-number greater than this value
44127 ** is played back. If one is encountered it is simply skipped.
44128 */
44129 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
44130   i64 szJ;                 /* Effective size of the main journal */
44131   i64 iHdrOff;             /* End of first segment of main-journal records */
44132   int rc = SQLITE_OK;      /* Return code */
44133   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
44134 
44135   assert( pPager->eState!=PAGER_ERROR );
44136   assert( pPager->eState>=PAGER_WRITER_LOCKED );
44137 
44138   /* Allocate a bitvec to use to store the set of pages rolled back */
44139   if( pSavepoint ){
44140     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
44141     if( !pDone ){
44142       return SQLITE_NOMEM;
44143     }
44144   }
44145 
44146   /* Set the database size back to the value it was before the savepoint
44147   ** being reverted was opened.
44148   */
44149   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
44150   pPager->changeCountDone = pPager->tempFile;
44151 
44152   if( !pSavepoint && pagerUseWal(pPager) ){
44153     return pagerRollbackWal(pPager);
44154   }
44155 
44156   /* Use pPager->journalOff as the effective size of the main rollback
44157   ** journal.  The actual file might be larger than this in
44158   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
44159   ** past pPager->journalOff is off-limits to us.
44160   */
44161   szJ = pPager->journalOff;
44162   assert( pagerUseWal(pPager)==0 || szJ==0 );
44163 
44164   /* Begin by rolling back records from the main journal starting at
44165   ** PagerSavepoint.iOffset and continuing to the next journal header.
44166   ** There might be records in the main journal that have a page number
44167   ** greater than the current database size (pPager->dbSize) but those
44168   ** will be skipped automatically.  Pages are added to pDone as they
44169   ** are played back.
44170   */
44171   if( pSavepoint && !pagerUseWal(pPager) ){
44172     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
44173     pPager->journalOff = pSavepoint->iOffset;
44174     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
44175       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
44176     }
44177     assert( rc!=SQLITE_DONE );
44178   }else{
44179     pPager->journalOff = 0;
44180   }
44181 
44182   /* Continue rolling back records out of the main journal starting at
44183   ** the first journal header seen and continuing until the effective end
44184   ** of the main journal file.  Continue to skip out-of-range pages and
44185   ** continue adding pages rolled back to pDone.
44186   */
44187   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
44188     u32 ii;            /* Loop counter */
44189     u32 nJRec = 0;     /* Number of Journal Records */
44190     u32 dummy;
44191     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
44192     assert( rc!=SQLITE_DONE );
44193 
44194     /*
44195     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
44196     ** test is related to ticket #2565.  See the discussion in the
44197     ** pager_playback() function for additional information.
44198     */
44199     if( nJRec==0
44200      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
44201     ){
44202       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
44203     }
44204     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
44205       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
44206     }
44207     assert( rc!=SQLITE_DONE );
44208   }
44209   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
44210 
44211   /* Finally,  rollback pages from the sub-journal.  Page that were
44212   ** previously rolled back out of the main journal (and are hence in pDone)
44213   ** will be skipped.  Out-of-range pages are also skipped.
44214   */
44215   if( pSavepoint ){
44216     u32 ii;            /* Loop counter */
44217     i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
44218 
44219     if( pagerUseWal(pPager) ){
44220       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
44221     }
44222     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
44223       assert( offset==(i64)ii*(4+pPager->pageSize) );
44224       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
44225     }
44226     assert( rc!=SQLITE_DONE );
44227   }
44228 
44229   sqlite3BitvecDestroy(pDone);
44230   if( rc==SQLITE_OK ){
44231     pPager->journalOff = szJ;
44232   }
44233 
44234   return rc;
44235 }
44236 
44237 /*
44238 ** Change the maximum number of in-memory pages that are allowed.
44239 */
44240 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
44241   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
44242 }
44243 
44244 /*
44245 ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
44246 */
44247 static void pagerFixMaplimit(Pager *pPager){
44248 #if SQLITE_MAX_MMAP_SIZE>0
44249   sqlite3_file *fd = pPager->fd;
44250   if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
44251     sqlite3_int64 sz;
44252     sz = pPager->szMmap;
44253     pPager->bUseFetch = (sz>0);
44254     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
44255   }
44256 #endif
44257 }
44258 
44259 /*
44260 ** Change the maximum size of any memory mapping made of the database file.
44261 */
44262 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
44263   pPager->szMmap = szMmap;
44264   pagerFixMaplimit(pPager);
44265 }
44266 
44267 /*
44268 ** Free as much memory as possible from the pager.
44269 */
44270 SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
44271   sqlite3PcacheShrink(pPager->pPCache);
44272 }
44273 
44274 /*
44275 ** Adjust settings of the pager to those specified in the pgFlags parameter.
44276 **
44277 ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
44278 ** of the database to damage due to OS crashes or power failures by
44279 ** changing the number of syncs()s when writing the journals.
44280 ** There are three levels:
44281 **
44282 **    OFF       sqlite3OsSync() is never called.  This is the default
44283 **              for temporary and transient files.
44284 **
44285 **    NORMAL    The journal is synced once before writes begin on the
44286 **              database.  This is normally adequate protection, but
44287 **              it is theoretically possible, though very unlikely,
44288 **              that an inopertune power failure could leave the journal
44289 **              in a state which would cause damage to the database
44290 **              when it is rolled back.
44291 **
44292 **    FULL      The journal is synced twice before writes begin on the
44293 **              database (with some additional information - the nRec field
44294 **              of the journal header - being written in between the two
44295 **              syncs).  If we assume that writing a
44296 **              single disk sector is atomic, then this mode provides
44297 **              assurance that the journal will not be corrupted to the
44298 **              point of causing damage to the database during rollback.
44299 **
44300 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
44301 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
44302 ** prior to the start of checkpoint and that the database file is synced
44303 ** at the conclusion of the checkpoint if the entire content of the WAL
44304 ** was written back into the database.  But no sync operations occur for
44305 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
44306 ** file is synced following each commit operation, in addition to the
44307 ** syncs associated with NORMAL.
44308 **
44309 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
44310 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
44311 ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
44312 ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
44313 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
44314 ** synchronous=FULL versus synchronous=NORMAL setting determines when
44315 ** the xSync primitive is called and is relevant to all platforms.
44316 **
44317 ** Numeric values associated with these states are OFF==1, NORMAL=2,
44318 ** and FULL=3.
44319 */
44320 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
44321 SQLITE_PRIVATE void sqlite3PagerSetFlags(
44322   Pager *pPager,        /* The pager to set safety level for */
44323   unsigned pgFlags      /* Various flags */
44324 ){
44325   unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
44326   assert( level>=1 && level<=3 );
44327   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
44328   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
44329   if( pPager->noSync ){
44330     pPager->syncFlags = 0;
44331     pPager->ckptSyncFlags = 0;
44332   }else if( pgFlags & PAGER_FULLFSYNC ){
44333     pPager->syncFlags = SQLITE_SYNC_FULL;
44334     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
44335   }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
44336     pPager->syncFlags = SQLITE_SYNC_NORMAL;
44337     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
44338   }else{
44339     pPager->syncFlags = SQLITE_SYNC_NORMAL;
44340     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
44341   }
44342   pPager->walSyncFlags = pPager->syncFlags;
44343   if( pPager->fullSync ){
44344     pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
44345   }
44346   if( pgFlags & PAGER_CACHESPILL ){
44347     pPager->doNotSpill &= ~SPILLFLAG_OFF;
44348   }else{
44349     pPager->doNotSpill |= SPILLFLAG_OFF;
44350   }
44351 }
44352 #endif
44353 
44354 /*
44355 ** The following global variable is incremented whenever the library
44356 ** attempts to open a temporary file.  This information is used for
44357 ** testing and analysis only.
44358 */
44359 #ifdef SQLITE_TEST
44360 SQLITE_API int sqlite3_opentemp_count = 0;
44361 #endif
44362 
44363 /*
44364 ** Open a temporary file.
44365 **
44366 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
44367 ** or some other error code if we fail. The OS will automatically
44368 ** delete the temporary file when it is closed.
44369 **
44370 ** The flags passed to the VFS layer xOpen() call are those specified
44371 ** by parameter vfsFlags ORed with the following:
44372 **
44373 **     SQLITE_OPEN_READWRITE
44374 **     SQLITE_OPEN_CREATE
44375 **     SQLITE_OPEN_EXCLUSIVE
44376 **     SQLITE_OPEN_DELETEONCLOSE
44377 */
44378 static int pagerOpentemp(
44379   Pager *pPager,        /* The pager object */
44380   sqlite3_file *pFile,  /* Write the file descriptor here */
44381   int vfsFlags          /* Flags passed through to the VFS */
44382 ){
44383   int rc;               /* Return code */
44384 
44385 #ifdef SQLITE_TEST
44386   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
44387 #endif
44388 
44389   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
44390             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
44391   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
44392   assert( rc!=SQLITE_OK || isOpen(pFile) );
44393   return rc;
44394 }
44395 
44396 /*
44397 ** Set the busy handler function.
44398 **
44399 ** The pager invokes the busy-handler if sqlite3OsLock() returns
44400 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
44401 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
44402 ** lock. It does *not* invoke the busy handler when upgrading from
44403 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
44404 ** (which occurs during hot-journal rollback). Summary:
44405 **
44406 **   Transition                        | Invokes xBusyHandler
44407 **   --------------------------------------------------------
44408 **   NO_LOCK       -> SHARED_LOCK      | Yes
44409 **   SHARED_LOCK   -> RESERVED_LOCK    | No
44410 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
44411 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
44412 **
44413 ** If the busy-handler callback returns non-zero, the lock is
44414 ** retried. If it returns zero, then the SQLITE_BUSY error is
44415 ** returned to the caller of the pager API function.
44416 */
44417 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
44418   Pager *pPager,                       /* Pager object */
44419   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
44420   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
44421 ){
44422   pPager->xBusyHandler = xBusyHandler;
44423   pPager->pBusyHandlerArg = pBusyHandlerArg;
44424 
44425   if( isOpen(pPager->fd) ){
44426     void **ap = (void **)&pPager->xBusyHandler;
44427     assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
44428     assert( ap[1]==pBusyHandlerArg );
44429     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
44430   }
44431 }
44432 
44433 /*
44434 ** Change the page size used by the Pager object. The new page size
44435 ** is passed in *pPageSize.
44436 **
44437 ** If the pager is in the error state when this function is called, it
44438 ** is a no-op. The value returned is the error state error code (i.e.
44439 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
44440 **
44441 ** Otherwise, if all of the following are true:
44442 **
44443 **   * the new page size (value of *pPageSize) is valid (a power
44444 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
44445 **
44446 **   * there are no outstanding page references, and
44447 **
44448 **   * the database is either not an in-memory database or it is
44449 **     an in-memory database that currently consists of zero pages.
44450 **
44451 ** then the pager object page size is set to *pPageSize.
44452 **
44453 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
44454 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
44455 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
44456 ** In all other cases, SQLITE_OK is returned.
44457 **
44458 ** If the page size is not changed, either because one of the enumerated
44459 ** conditions above is not true, the pager was in error state when this
44460 ** function was called, or because the memory allocation attempt failed,
44461 ** then *pPageSize is set to the old, retained page size before returning.
44462 */
44463 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
44464   int rc = SQLITE_OK;
44465 
44466   /* It is not possible to do a full assert_pager_state() here, as this
44467   ** function may be called from within PagerOpen(), before the state
44468   ** of the Pager object is internally consistent.
44469   **
44470   ** At one point this function returned an error if the pager was in
44471   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
44472   ** there is at least one outstanding page reference, this function
44473   ** is a no-op for that case anyhow.
44474   */
44475 
44476   u32 pageSize = *pPageSize;
44477   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
44478   if( (pPager->memDb==0 || pPager->dbSize==0)
44479    && sqlite3PcacheRefCount(pPager->pPCache)==0
44480    && pageSize && pageSize!=(u32)pPager->pageSize
44481   ){
44482     char *pNew = NULL;             /* New temp space */
44483     i64 nByte = 0;
44484 
44485     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
44486       rc = sqlite3OsFileSize(pPager->fd, &nByte);
44487     }
44488     if( rc==SQLITE_OK ){
44489       pNew = (char *)sqlite3PageMalloc(pageSize);
44490       if( !pNew ) rc = SQLITE_NOMEM;
44491     }
44492 
44493     if( rc==SQLITE_OK ){
44494       pager_reset(pPager);
44495       rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
44496     }
44497     if( rc==SQLITE_OK ){
44498       sqlite3PageFree(pPager->pTmpSpace);
44499       pPager->pTmpSpace = pNew;
44500       pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
44501       pPager->pageSize = pageSize;
44502     }else{
44503       sqlite3PageFree(pNew);
44504     }
44505   }
44506 
44507   *pPageSize = pPager->pageSize;
44508   if( rc==SQLITE_OK ){
44509     if( nReserve<0 ) nReserve = pPager->nReserve;
44510     assert( nReserve>=0 && nReserve<1000 );
44511     pPager->nReserve = (i16)nReserve;
44512     pagerReportSize(pPager);
44513     pagerFixMaplimit(pPager);
44514   }
44515   return rc;
44516 }
44517 
44518 /*
44519 ** Return a pointer to the "temporary page" buffer held internally
44520 ** by the pager.  This is a buffer that is big enough to hold the
44521 ** entire content of a database page.  This buffer is used internally
44522 ** during rollback and will be overwritten whenever a rollback
44523 ** occurs.  But other modules are free to use it too, as long as
44524 ** no rollbacks are happening.
44525 */
44526 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
44527   return pPager->pTmpSpace;
44528 }
44529 
44530 /*
44531 ** Attempt to set the maximum database page count if mxPage is positive.
44532 ** Make no changes if mxPage is zero or negative.  And never reduce the
44533 ** maximum page count below the current size of the database.
44534 **
44535 ** Regardless of mxPage, return the current maximum page count.
44536 */
44537 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
44538   if( mxPage>0 ){
44539     pPager->mxPgno = mxPage;
44540   }
44541   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
44542   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
44543   return pPager->mxPgno;
44544 }
44545 
44546 /*
44547 ** The following set of routines are used to disable the simulated
44548 ** I/O error mechanism.  These routines are used to avoid simulated
44549 ** errors in places where we do not care about errors.
44550 **
44551 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
44552 ** and generate no code.
44553 */
44554 #ifdef SQLITE_TEST
44555 SQLITE_API extern int sqlite3_io_error_pending;
44556 SQLITE_API extern int sqlite3_io_error_hit;
44557 static int saved_cnt;
44558 void disable_simulated_io_errors(void){
44559   saved_cnt = sqlite3_io_error_pending;
44560   sqlite3_io_error_pending = -1;
44561 }
44562 void enable_simulated_io_errors(void){
44563   sqlite3_io_error_pending = saved_cnt;
44564 }
44565 #else
44566 # define disable_simulated_io_errors()
44567 # define enable_simulated_io_errors()
44568 #endif
44569 
44570 /*
44571 ** Read the first N bytes from the beginning of the file into memory
44572 ** that pDest points to.
44573 **
44574 ** If the pager was opened on a transient file (zFilename==""), or
44575 ** opened on a file less than N bytes in size, the output buffer is
44576 ** zeroed and SQLITE_OK returned. The rationale for this is that this
44577 ** function is used to read database headers, and a new transient or
44578 ** zero sized database has a header than consists entirely of zeroes.
44579 **
44580 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
44581 ** the error code is returned to the caller and the contents of the
44582 ** output buffer undefined.
44583 */
44584 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
44585   int rc = SQLITE_OK;
44586   memset(pDest, 0, N);
44587   assert( isOpen(pPager->fd) || pPager->tempFile );
44588 
44589   /* This routine is only called by btree immediately after creating
44590   ** the Pager object.  There has not been an opportunity to transition
44591   ** to WAL mode yet.
44592   */
44593   assert( !pagerUseWal(pPager) );
44594 
44595   if( isOpen(pPager->fd) ){
44596     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
44597     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
44598     if( rc==SQLITE_IOERR_SHORT_READ ){
44599       rc = SQLITE_OK;
44600     }
44601   }
44602   return rc;
44603 }
44604 
44605 /*
44606 ** This function may only be called when a read-transaction is open on
44607 ** the pager. It returns the total number of pages in the database.
44608 **
44609 ** However, if the file is between 1 and <page-size> bytes in size, then
44610 ** this is considered a 1 page file.
44611 */
44612 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
44613   assert( pPager->eState>=PAGER_READER );
44614   assert( pPager->eState!=PAGER_WRITER_FINISHED );
44615   *pnPage = (int)pPager->dbSize;
44616 }
44617 
44618 
44619 /*
44620 ** Try to obtain a lock of type locktype on the database file. If
44621 ** a similar or greater lock is already held, this function is a no-op
44622 ** (returning SQLITE_OK immediately).
44623 **
44624 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
44625 ** the busy callback if the lock is currently not available. Repeat
44626 ** until the busy callback returns false or until the attempt to
44627 ** obtain the lock succeeds.
44628 **
44629 ** Return SQLITE_OK on success and an error code if we cannot obtain
44630 ** the lock. If the lock is obtained successfully, set the Pager.state
44631 ** variable to locktype before returning.
44632 */
44633 static int pager_wait_on_lock(Pager *pPager, int locktype){
44634   int rc;                              /* Return code */
44635 
44636   /* Check that this is either a no-op (because the requested lock is
44637   ** already held), or one of the transitions that the busy-handler
44638   ** may be invoked during, according to the comment above
44639   ** sqlite3PagerSetBusyhandler().
44640   */
44641   assert( (pPager->eLock>=locktype)
44642        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
44643        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
44644   );
44645 
44646   do {
44647     rc = pagerLockDb(pPager, locktype);
44648   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
44649   return rc;
44650 }
44651 
44652 /*
44653 ** Function assertTruncateConstraint(pPager) checks that one of the
44654 ** following is true for all dirty pages currently in the page-cache:
44655 **
44656 **   a) The page number is less than or equal to the size of the
44657 **      current database image, in pages, OR
44658 **
44659 **   b) if the page content were written at this time, it would not
44660 **      be necessary to write the current content out to the sub-journal
44661 **      (as determined by function subjRequiresPage()).
44662 **
44663 ** If the condition asserted by this function were not true, and the
44664 ** dirty page were to be discarded from the cache via the pagerStress()
44665 ** routine, pagerStress() would not write the current page content to
44666 ** the database file. If a savepoint transaction were rolled back after
44667 ** this happened, the correct behavior would be to restore the current
44668 ** content of the page. However, since this content is not present in either
44669 ** the database file or the portion of the rollback journal and
44670 ** sub-journal rolled back the content could not be restored and the
44671 ** database image would become corrupt. It is therefore fortunate that
44672 ** this circumstance cannot arise.
44673 */
44674 #if defined(SQLITE_DEBUG)
44675 static void assertTruncateConstraintCb(PgHdr *pPg){
44676   assert( pPg->flags&PGHDR_DIRTY );
44677   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
44678 }
44679 static void assertTruncateConstraint(Pager *pPager){
44680   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
44681 }
44682 #else
44683 # define assertTruncateConstraint(pPager)
44684 #endif
44685 
44686 /*
44687 ** Truncate the in-memory database file image to nPage pages. This
44688 ** function does not actually modify the database file on disk. It
44689 ** just sets the internal state of the pager object so that the
44690 ** truncation will be done when the current transaction is committed.
44691 **
44692 ** This function is only called right before committing a transaction.
44693 ** Once this function has been called, the transaction must either be
44694 ** rolled back or committed. It is not safe to call this function and
44695 ** then continue writing to the database.
44696 */
44697 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
44698   assert( pPager->dbSize>=nPage );
44699   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
44700   pPager->dbSize = nPage;
44701 
44702   /* At one point the code here called assertTruncateConstraint() to
44703   ** ensure that all pages being truncated away by this operation are,
44704   ** if one or more savepoints are open, present in the savepoint
44705   ** journal so that they can be restored if the savepoint is rolled
44706   ** back. This is no longer necessary as this function is now only
44707   ** called right before committing a transaction. So although the
44708   ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
44709   ** they cannot be rolled back. So the assertTruncateConstraint() call
44710   ** is no longer correct. */
44711 }
44712 
44713 
44714 /*
44715 ** This function is called before attempting a hot-journal rollback. It
44716 ** syncs the journal file to disk, then sets pPager->journalHdr to the
44717 ** size of the journal file so that the pager_playback() routine knows
44718 ** that the entire journal file has been synced.
44719 **
44720 ** Syncing a hot-journal to disk before attempting to roll it back ensures
44721 ** that if a power-failure occurs during the rollback, the process that
44722 ** attempts rollback following system recovery sees the same journal
44723 ** content as this process.
44724 **
44725 ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
44726 ** an SQLite error code.
44727 */
44728 static int pagerSyncHotJournal(Pager *pPager){
44729   int rc = SQLITE_OK;
44730   if( !pPager->noSync ){
44731     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
44732   }
44733   if( rc==SQLITE_OK ){
44734     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
44735   }
44736   return rc;
44737 }
44738 
44739 /*
44740 ** Obtain a reference to a memory mapped page object for page number pgno.
44741 ** The new object will use the pointer pData, obtained from xFetch().
44742 ** If successful, set *ppPage to point to the new page reference
44743 ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
44744 ** *ppPage to zero.
44745 **
44746 ** Page references obtained by calling this function should be released
44747 ** by calling pagerReleaseMapPage().
44748 */
44749 static int pagerAcquireMapPage(
44750   Pager *pPager,                  /* Pager object */
44751   Pgno pgno,                      /* Page number */
44752   void *pData,                    /* xFetch()'d data for this page */
44753   PgHdr **ppPage                  /* OUT: Acquired page object */
44754 ){
44755   PgHdr *p;                       /* Memory mapped page to return */
44756 
44757   if( pPager->pMmapFreelist ){
44758     *ppPage = p = pPager->pMmapFreelist;
44759     pPager->pMmapFreelist = p->pDirty;
44760     p->pDirty = 0;
44761     memset(p->pExtra, 0, pPager->nExtra);
44762   }else{
44763     *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
44764     if( p==0 ){
44765       sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
44766       return SQLITE_NOMEM;
44767     }
44768     p->pExtra = (void *)&p[1];
44769     p->flags = PGHDR_MMAP;
44770     p->nRef = 1;
44771     p->pPager = pPager;
44772   }
44773 
44774   assert( p->pExtra==(void *)&p[1] );
44775   assert( p->pPage==0 );
44776   assert( p->flags==PGHDR_MMAP );
44777   assert( p->pPager==pPager );
44778   assert( p->nRef==1 );
44779 
44780   p->pgno = pgno;
44781   p->pData = pData;
44782   pPager->nMmapOut++;
44783 
44784   return SQLITE_OK;
44785 }
44786 
44787 /*
44788 ** Release a reference to page pPg. pPg must have been returned by an
44789 ** earlier call to pagerAcquireMapPage().
44790 */
44791 static void pagerReleaseMapPage(PgHdr *pPg){
44792   Pager *pPager = pPg->pPager;
44793   pPager->nMmapOut--;
44794   pPg->pDirty = pPager->pMmapFreelist;
44795   pPager->pMmapFreelist = pPg;
44796 
44797   assert( pPager->fd->pMethods->iVersion>=3 );
44798   sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
44799 }
44800 
44801 /*
44802 ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
44803 */
44804 static void pagerFreeMapHdrs(Pager *pPager){
44805   PgHdr *p;
44806   PgHdr *pNext;
44807   for(p=pPager->pMmapFreelist; p; p=pNext){
44808     pNext = p->pDirty;
44809     sqlite3_free(p);
44810   }
44811 }
44812 
44813 
44814 /*
44815 ** Shutdown the page cache.  Free all memory and close all files.
44816 **
44817 ** If a transaction was in progress when this routine is called, that
44818 ** transaction is rolled back.  All outstanding pages are invalidated
44819 ** and their memory is freed.  Any attempt to use a page associated
44820 ** with this page cache after this function returns will likely
44821 ** result in a coredump.
44822 **
44823 ** This function always succeeds. If a transaction is active an attempt
44824 ** is made to roll it back. If an error occurs during the rollback
44825 ** a hot journal may be left in the filesystem but no error is returned
44826 ** to the caller.
44827 */
44828 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
44829   u8 *pTmp = (u8 *)pPager->pTmpSpace;
44830 
44831   assert( assert_pager_state(pPager) );
44832   disable_simulated_io_errors();
44833   sqlite3BeginBenignMalloc();
44834   pagerFreeMapHdrs(pPager);
44835   /* pPager->errCode = 0; */
44836   pPager->exclusiveMode = 0;
44837 #ifndef SQLITE_OMIT_WAL
44838   sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
44839   pPager->pWal = 0;
44840 #endif
44841   pager_reset(pPager);
44842   if( MEMDB ){
44843     pager_unlock(pPager);
44844   }else{
44845     /* If it is open, sync the journal file before calling UnlockAndRollback.
44846     ** If this is not done, then an unsynced portion of the open journal
44847     ** file may be played back into the database. If a power failure occurs
44848     ** while this is happening, the database could become corrupt.
44849     **
44850     ** If an error occurs while trying to sync the journal, shift the pager
44851     ** into the ERROR state. This causes UnlockAndRollback to unlock the
44852     ** database and close the journal file without attempting to roll it
44853     ** back or finalize it. The next database user will have to do hot-journal
44854     ** rollback before accessing the database file.
44855     */
44856     if( isOpen(pPager->jfd) ){
44857       pager_error(pPager, pagerSyncHotJournal(pPager));
44858     }
44859     pagerUnlockAndRollback(pPager);
44860   }
44861   sqlite3EndBenignMalloc();
44862   enable_simulated_io_errors();
44863   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
44864   IOTRACE(("CLOSE %p\n", pPager))
44865   sqlite3OsClose(pPager->jfd);
44866   sqlite3OsClose(pPager->fd);
44867   sqlite3PageFree(pTmp);
44868   sqlite3PcacheClose(pPager->pPCache);
44869 
44870 #ifdef SQLITE_HAS_CODEC
44871   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
44872 #endif
44873 
44874   assert( !pPager->aSavepoint && !pPager->pInJournal );
44875   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
44876 
44877   sqlite3_free(pPager);
44878   return SQLITE_OK;
44879 }
44880 
44881 #if !defined(NDEBUG) || defined(SQLITE_TEST)
44882 /*
44883 ** Return the page number for page pPg.
44884 */
44885 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
44886   return pPg->pgno;
44887 }
44888 #endif
44889 
44890 /*
44891 ** Increment the reference count for page pPg.
44892 */
44893 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
44894   sqlite3PcacheRef(pPg);
44895 }
44896 
44897 /*
44898 ** Sync the journal. In other words, make sure all the pages that have
44899 ** been written to the journal have actually reached the surface of the
44900 ** disk and can be restored in the event of a hot-journal rollback.
44901 **
44902 ** If the Pager.noSync flag is set, then this function is a no-op.
44903 ** Otherwise, the actions required depend on the journal-mode and the
44904 ** device characteristics of the file-system, as follows:
44905 **
44906 **   * If the journal file is an in-memory journal file, no action need
44907 **     be taken.
44908 **
44909 **   * Otherwise, if the device does not support the SAFE_APPEND property,
44910 **     then the nRec field of the most recently written journal header
44911 **     is updated to contain the number of journal records that have
44912 **     been written following it. If the pager is operating in full-sync
44913 **     mode, then the journal file is synced before this field is updated.
44914 **
44915 **   * If the device does not support the SEQUENTIAL property, then
44916 **     journal file is synced.
44917 **
44918 ** Or, in pseudo-code:
44919 **
44920 **   if( NOT <in-memory journal> ){
44921 **     if( NOT SAFE_APPEND ){
44922 **       if( <full-sync mode> ) xSync(<journal file>);
44923 **       <update nRec field>
44924 **     }
44925 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
44926 **   }
44927 **
44928 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
44929 ** page currently held in memory before returning SQLITE_OK. If an IO
44930 ** error is encountered, then the IO error code is returned to the caller.
44931 */
44932 static int syncJournal(Pager *pPager, int newHdr){
44933   int rc;                         /* Return code */
44934 
44935   assert( pPager->eState==PAGER_WRITER_CACHEMOD
44936        || pPager->eState==PAGER_WRITER_DBMOD
44937   );
44938   assert( assert_pager_state(pPager) );
44939   assert( !pagerUseWal(pPager) );
44940 
44941   rc = sqlite3PagerExclusiveLock(pPager);
44942   if( rc!=SQLITE_OK ) return rc;
44943 
44944   if( !pPager->noSync ){
44945     assert( !pPager->tempFile );
44946     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
44947       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
44948       assert( isOpen(pPager->jfd) );
44949 
44950       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
44951         /* This block deals with an obscure problem. If the last connection
44952         ** that wrote to this database was operating in persistent-journal
44953         ** mode, then the journal file may at this point actually be larger
44954         ** than Pager.journalOff bytes. If the next thing in the journal
44955         ** file happens to be a journal-header (written as part of the
44956         ** previous connection's transaction), and a crash or power-failure
44957         ** occurs after nRec is updated but before this connection writes
44958         ** anything else to the journal file (or commits/rolls back its
44959         ** transaction), then SQLite may become confused when doing the
44960         ** hot-journal rollback following recovery. It may roll back all
44961         ** of this connections data, then proceed to rolling back the old,
44962         ** out-of-date data that follows it. Database corruption.
44963         **
44964         ** To work around this, if the journal file does appear to contain
44965         ** a valid header following Pager.journalOff, then write a 0x00
44966         ** byte to the start of it to prevent it from being recognized.
44967         **
44968         ** Variable iNextHdrOffset is set to the offset at which this
44969         ** problematic header will occur, if it exists. aMagic is used
44970         ** as a temporary buffer to inspect the first couple of bytes of
44971         ** the potential journal header.
44972         */
44973         i64 iNextHdrOffset;
44974         u8 aMagic[8];
44975         u8 zHeader[sizeof(aJournalMagic)+4];
44976 
44977         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
44978         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
44979 
44980         iNextHdrOffset = journalHdrOffset(pPager);
44981         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
44982         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
44983           static const u8 zerobyte = 0;
44984           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
44985         }
44986         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
44987           return rc;
44988         }
44989 
44990         /* Write the nRec value into the journal file header. If in
44991         ** full-synchronous mode, sync the journal first. This ensures that
44992         ** all data has really hit the disk before nRec is updated to mark
44993         ** it as a candidate for rollback.
44994         **
44995         ** This is not required if the persistent media supports the
44996         ** SAFE_APPEND property. Because in this case it is not possible
44997         ** for garbage data to be appended to the file, the nRec field
44998         ** is populated with 0xFFFFFFFF when the journal header is written
44999         ** and never needs to be updated.
45000         */
45001         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
45002           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
45003           IOTRACE(("JSYNC %p\n", pPager))
45004           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
45005           if( rc!=SQLITE_OK ) return rc;
45006         }
45007         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
45008         rc = sqlite3OsWrite(
45009             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
45010         );
45011         if( rc!=SQLITE_OK ) return rc;
45012       }
45013       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
45014         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
45015         IOTRACE(("JSYNC %p\n", pPager))
45016         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
45017           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
45018         );
45019         if( rc!=SQLITE_OK ) return rc;
45020       }
45021 
45022       pPager->journalHdr = pPager->journalOff;
45023       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
45024         pPager->nRec = 0;
45025         rc = writeJournalHdr(pPager);
45026         if( rc!=SQLITE_OK ) return rc;
45027       }
45028     }else{
45029       pPager->journalHdr = pPager->journalOff;
45030     }
45031   }
45032 
45033   /* Unless the pager is in noSync mode, the journal file was just
45034   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
45035   ** all pages.
45036   */
45037   sqlite3PcacheClearSyncFlags(pPager->pPCache);
45038   pPager->eState = PAGER_WRITER_DBMOD;
45039   assert( assert_pager_state(pPager) );
45040   return SQLITE_OK;
45041 }
45042 
45043 /*
45044 ** The argument is the first in a linked list of dirty pages connected
45045 ** by the PgHdr.pDirty pointer. This function writes each one of the
45046 ** in-memory pages in the list to the database file. The argument may
45047 ** be NULL, representing an empty list. In this case this function is
45048 ** a no-op.
45049 **
45050 ** The pager must hold at least a RESERVED lock when this function
45051 ** is called. Before writing anything to the database file, this lock
45052 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
45053 ** SQLITE_BUSY is returned and no data is written to the database file.
45054 **
45055 ** If the pager is a temp-file pager and the actual file-system file
45056 ** is not yet open, it is created and opened before any data is
45057 ** written out.
45058 **
45059 ** Once the lock has been upgraded and, if necessary, the file opened,
45060 ** the pages are written out to the database file in list order. Writing
45061 ** a page is skipped if it meets either of the following criteria:
45062 **
45063 **   * The page number is greater than Pager.dbSize, or
45064 **   * The PGHDR_DONT_WRITE flag is set on the page.
45065 **
45066 ** If writing out a page causes the database file to grow, Pager.dbFileSize
45067 ** is updated accordingly. If page 1 is written out, then the value cached
45068 ** in Pager.dbFileVers[] is updated to match the new value stored in
45069 ** the database file.
45070 **
45071 ** If everything is successful, SQLITE_OK is returned. If an IO error
45072 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
45073 ** be obtained, SQLITE_BUSY is returned.
45074 */
45075 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
45076   int rc = SQLITE_OK;                  /* Return code */
45077 
45078   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
45079   assert( !pagerUseWal(pPager) );
45080   assert( pPager->eState==PAGER_WRITER_DBMOD );
45081   assert( pPager->eLock==EXCLUSIVE_LOCK );
45082 
45083   /* If the file is a temp-file has not yet been opened, open it now. It
45084   ** is not possible for rc to be other than SQLITE_OK if this branch
45085   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
45086   */
45087   if( !isOpen(pPager->fd) ){
45088     assert( pPager->tempFile && rc==SQLITE_OK );
45089     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
45090   }
45091 
45092   /* Before the first write, give the VFS a hint of what the final
45093   ** file size will be.
45094   */
45095   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
45096   if( rc==SQLITE_OK
45097    && pPager->dbHintSize<pPager->dbSize
45098    && (pList->pDirty || pList->pgno>pPager->dbHintSize)
45099   ){
45100     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
45101     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
45102     pPager->dbHintSize = pPager->dbSize;
45103   }
45104 
45105   while( rc==SQLITE_OK && pList ){
45106     Pgno pgno = pList->pgno;
45107 
45108     /* If there are dirty pages in the page cache with page numbers greater
45109     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
45110     ** make the file smaller (presumably by auto-vacuum code). Do not write
45111     ** any such pages to the file.
45112     **
45113     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
45114     ** set (set by sqlite3PagerDontWrite()).
45115     */
45116     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
45117       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
45118       char *pData;                                   /* Data to write */
45119 
45120       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
45121       if( pList->pgno==1 ) pager_write_changecounter(pList);
45122 
45123       /* Encode the database */
45124       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
45125 
45126       /* Write out the page data. */
45127       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
45128 
45129       /* If page 1 was just written, update Pager.dbFileVers to match
45130       ** the value now stored in the database file. If writing this
45131       ** page caused the database file to grow, update dbFileSize.
45132       */
45133       if( pgno==1 ){
45134         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
45135       }
45136       if( pgno>pPager->dbFileSize ){
45137         pPager->dbFileSize = pgno;
45138       }
45139       pPager->aStat[PAGER_STAT_WRITE]++;
45140 
45141       /* Update any backup objects copying the contents of this pager. */
45142       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
45143 
45144       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
45145                    PAGERID(pPager), pgno, pager_pagehash(pList)));
45146       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
45147       PAGER_INCR(sqlite3_pager_writedb_count);
45148     }else{
45149       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
45150     }
45151     pager_set_pagehash(pList);
45152     pList = pList->pDirty;
45153   }
45154 
45155   return rc;
45156 }
45157 
45158 /*
45159 ** Ensure that the sub-journal file is open. If it is already open, this
45160 ** function is a no-op.
45161 **
45162 ** SQLITE_OK is returned if everything goes according to plan. An
45163 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
45164 ** fails.
45165 */
45166 static int openSubJournal(Pager *pPager){
45167   int rc = SQLITE_OK;
45168   if( !isOpen(pPager->sjfd) ){
45169     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
45170       sqlite3MemJournalOpen(pPager->sjfd);
45171     }else{
45172       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
45173     }
45174   }
45175   return rc;
45176 }
45177 
45178 /*
45179 ** Append a record of the current state of page pPg to the sub-journal.
45180 ** It is the callers responsibility to use subjRequiresPage() to check
45181 ** that it is really required before calling this function.
45182 **
45183 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
45184 ** for all open savepoints before returning.
45185 **
45186 ** This function returns SQLITE_OK if everything is successful, an IO
45187 ** error code if the attempt to write to the sub-journal fails, or
45188 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
45189 ** bitvec.
45190 */
45191 static int subjournalPage(PgHdr *pPg){
45192   int rc = SQLITE_OK;
45193   Pager *pPager = pPg->pPager;
45194   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
45195 
45196     /* Open the sub-journal, if it has not already been opened */
45197     assert( pPager->useJournal );
45198     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
45199     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
45200     assert( pagerUseWal(pPager)
45201          || pageInJournal(pPager, pPg)
45202          || pPg->pgno>pPager->dbOrigSize
45203     );
45204     rc = openSubJournal(pPager);
45205 
45206     /* If the sub-journal was opened successfully (or was already open),
45207     ** write the journal record into the file.  */
45208     if( rc==SQLITE_OK ){
45209       void *pData = pPg->pData;
45210       i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
45211       char *pData2;
45212 
45213       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
45214       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
45215       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
45216       if( rc==SQLITE_OK ){
45217         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
45218       }
45219     }
45220   }
45221   if( rc==SQLITE_OK ){
45222     pPager->nSubRec++;
45223     assert( pPager->nSavepoint>0 );
45224     rc = addToSavepointBitvecs(pPager, pPg->pgno);
45225   }
45226   return rc;
45227 }
45228 
45229 /*
45230 ** This function is called by the pcache layer when it has reached some
45231 ** soft memory limit. The first argument is a pointer to a Pager object
45232 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
45233 ** database). The second argument is a reference to a page that is
45234 ** currently dirty but has no outstanding references. The page
45235 ** is always associated with the Pager object passed as the first
45236 ** argument.
45237 **
45238 ** The job of this function is to make pPg clean by writing its contents
45239 ** out to the database file, if possible. This may involve syncing the
45240 ** journal file.
45241 **
45242 ** If successful, sqlite3PcacheMakeClean() is called on the page and
45243 ** SQLITE_OK returned. If an IO error occurs while trying to make the
45244 ** page clean, the IO error code is returned. If the page cannot be
45245 ** made clean for some other reason, but no error occurs, then SQLITE_OK
45246 ** is returned by sqlite3PcacheMakeClean() is not called.
45247 */
45248 static int pagerStress(void *p, PgHdr *pPg){
45249   Pager *pPager = (Pager *)p;
45250   int rc = SQLITE_OK;
45251 
45252   assert( pPg->pPager==pPager );
45253   assert( pPg->flags&PGHDR_DIRTY );
45254 
45255   /* The doNotSpill NOSYNC bit is set during times when doing a sync of
45256   ** journal (and adding a new header) is not allowed.  This occurs
45257   ** during calls to sqlite3PagerWrite() while trying to journal multiple
45258   ** pages belonging to the same sector.
45259   **
45260   ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
45261   ** regardless of whether or not a sync is required.  This is set during
45262   ** a rollback or by user request, respectively.
45263   **
45264   ** Spilling is also prohibited when in an error state since that could
45265   ** lead to database corruption.   In the current implementation it
45266   ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
45267   ** while in the error state, hence it is impossible for this routine to
45268   ** be called in the error state.  Nevertheless, we include a NEVER()
45269   ** test for the error state as a safeguard against future changes.
45270   */
45271   if( NEVER(pPager->errCode) ) return SQLITE_OK;
45272   testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
45273   testcase( pPager->doNotSpill & SPILLFLAG_OFF );
45274   testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
45275   if( pPager->doNotSpill
45276    && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
45277       || (pPg->flags & PGHDR_NEED_SYNC)!=0)
45278   ){
45279     return SQLITE_OK;
45280   }
45281 
45282   pPg->pDirty = 0;
45283   if( pagerUseWal(pPager) ){
45284     /* Write a single frame for this page to the log. */
45285     if( subjRequiresPage(pPg) ){
45286       rc = subjournalPage(pPg);
45287     }
45288     if( rc==SQLITE_OK ){
45289       rc = pagerWalFrames(pPager, pPg, 0, 0);
45290     }
45291   }else{
45292 
45293     /* Sync the journal file if required. */
45294     if( pPg->flags&PGHDR_NEED_SYNC
45295      || pPager->eState==PAGER_WRITER_CACHEMOD
45296     ){
45297       rc = syncJournal(pPager, 1);
45298     }
45299 
45300     /* If the page number of this page is larger than the current size of
45301     ** the database image, it may need to be written to the sub-journal.
45302     ** This is because the call to pager_write_pagelist() below will not
45303     ** actually write data to the file in this case.
45304     **
45305     ** Consider the following sequence of events:
45306     **
45307     **   BEGIN;
45308     **     <journal page X>
45309     **     <modify page X>
45310     **     SAVEPOINT sp;
45311     **       <shrink database file to Y pages>
45312     **       pagerStress(page X)
45313     **     ROLLBACK TO sp;
45314     **
45315     ** If (X>Y), then when pagerStress is called page X will not be written
45316     ** out to the database file, but will be dropped from the cache. Then,
45317     ** following the "ROLLBACK TO sp" statement, reading page X will read
45318     ** data from the database file. This will be the copy of page X as it
45319     ** was when the transaction started, not as it was when "SAVEPOINT sp"
45320     ** was executed.
45321     **
45322     ** The solution is to write the current data for page X into the
45323     ** sub-journal file now (if it is not already there), so that it will
45324     ** be restored to its current value when the "ROLLBACK TO sp" is
45325     ** executed.
45326     */
45327     if( NEVER(
45328         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
45329     ) ){
45330       rc = subjournalPage(pPg);
45331     }
45332 
45333     /* Write the contents of the page out to the database file. */
45334     if( rc==SQLITE_OK ){
45335       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
45336       rc = pager_write_pagelist(pPager, pPg);
45337     }
45338   }
45339 
45340   /* Mark the page as clean. */
45341   if( rc==SQLITE_OK ){
45342     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
45343     sqlite3PcacheMakeClean(pPg);
45344   }
45345 
45346   return pager_error(pPager, rc);
45347 }
45348 
45349 
45350 /*
45351 ** Allocate and initialize a new Pager object and put a pointer to it
45352 ** in *ppPager. The pager should eventually be freed by passing it
45353 ** to sqlite3PagerClose().
45354 **
45355 ** The zFilename argument is the path to the database file to open.
45356 ** If zFilename is NULL then a randomly-named temporary file is created
45357 ** and used as the file to be cached. Temporary files are be deleted
45358 ** automatically when they are closed. If zFilename is ":memory:" then
45359 ** all information is held in cache. It is never written to disk.
45360 ** This can be used to implement an in-memory database.
45361 **
45362 ** The nExtra parameter specifies the number of bytes of space allocated
45363 ** along with each page reference. This space is available to the user
45364 ** via the sqlite3PagerGetExtra() API.
45365 **
45366 ** The flags argument is used to specify properties that affect the
45367 ** operation of the pager. It should be passed some bitwise combination
45368 ** of the PAGER_* flags.
45369 **
45370 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
45371 ** of the xOpen() method of the supplied VFS when opening files.
45372 **
45373 ** If the pager object is allocated and the specified file opened
45374 ** successfully, SQLITE_OK is returned and *ppPager set to point to
45375 ** the new pager object. If an error occurs, *ppPager is set to NULL
45376 ** and error code returned. This function may return SQLITE_NOMEM
45377 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
45378 ** various SQLITE_IO_XXX errors.
45379 */
45380 SQLITE_PRIVATE int sqlite3PagerOpen(
45381   sqlite3_vfs *pVfs,       /* The virtual file system to use */
45382   Pager **ppPager,         /* OUT: Return the Pager structure here */
45383   const char *zFilename,   /* Name of the database file to open */
45384   int nExtra,              /* Extra bytes append to each in-memory page */
45385   int flags,               /* flags controlling this file */
45386   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
45387   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
45388 ){
45389   u8 *pPtr;
45390   Pager *pPager = 0;       /* Pager object to allocate and return */
45391   int rc = SQLITE_OK;      /* Return code */
45392   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
45393   int memDb = 0;           /* True if this is an in-memory file */
45394   int readOnly = 0;        /* True if this is a read-only file */
45395   int journalFileSize;     /* Bytes to allocate for each journal fd */
45396   char *zPathname = 0;     /* Full path to database file */
45397   int nPathname = 0;       /* Number of bytes in zPathname */
45398   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
45399   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
45400   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
45401   const char *zUri = 0;    /* URI args to copy */
45402   int nUri = 0;            /* Number of bytes of URI args at *zUri */
45403 
45404   /* Figure out how much space is required for each journal file-handle
45405   ** (there are two of them, the main journal and the sub-journal). This
45406   ** is the maximum space required for an in-memory journal file handle
45407   ** and a regular journal file-handle. Note that a "regular journal-handle"
45408   ** may be a wrapper capable of caching the first portion of the journal
45409   ** file in memory to implement the atomic-write optimization (see
45410   ** source file journal.c).
45411   */
45412   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
45413     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
45414   }else{
45415     journalFileSize = ROUND8(sqlite3MemJournalSize());
45416   }
45417 
45418   /* Set the output variable to NULL in case an error occurs. */
45419   *ppPager = 0;
45420 
45421 #ifndef SQLITE_OMIT_MEMORYDB
45422   if( flags & PAGER_MEMORY ){
45423     memDb = 1;
45424     if( zFilename && zFilename[0] ){
45425       zPathname = sqlite3DbStrDup(0, zFilename);
45426       if( zPathname==0  ) return SQLITE_NOMEM;
45427       nPathname = sqlite3Strlen30(zPathname);
45428       zFilename = 0;
45429     }
45430   }
45431 #endif
45432 
45433   /* Compute and store the full pathname in an allocated buffer pointed
45434   ** to by zPathname, length nPathname. Or, if this is a temporary file,
45435   ** leave both nPathname and zPathname set to 0.
45436   */
45437   if( zFilename && zFilename[0] ){
45438     const char *z;
45439     nPathname = pVfs->mxPathname+1;
45440     zPathname = sqlite3DbMallocRaw(0, nPathname*2);
45441     if( zPathname==0 ){
45442       return SQLITE_NOMEM;
45443     }
45444     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
45445     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
45446     nPathname = sqlite3Strlen30(zPathname);
45447     z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
45448     while( *z ){
45449       z += sqlite3Strlen30(z)+1;
45450       z += sqlite3Strlen30(z)+1;
45451     }
45452     nUri = (int)(&z[1] - zUri);
45453     assert( nUri>=0 );
45454     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
45455       /* This branch is taken when the journal path required by
45456       ** the database being opened will be more than pVfs->mxPathname
45457       ** bytes in length. This means the database cannot be opened,
45458       ** as it will not be possible to open the journal file or even
45459       ** check for a hot-journal before reading.
45460       */
45461       rc = SQLITE_CANTOPEN_BKPT;
45462     }
45463     if( rc!=SQLITE_OK ){
45464       sqlite3DbFree(0, zPathname);
45465       return rc;
45466     }
45467   }
45468 
45469   /* Allocate memory for the Pager structure, PCache object, the
45470   ** three file descriptors, the database file name and the journal
45471   ** file name. The layout in memory is as follows:
45472   **
45473   **     Pager object                    (sizeof(Pager) bytes)
45474   **     PCache object                   (sqlite3PcacheSize() bytes)
45475   **     Database file handle            (pVfs->szOsFile bytes)
45476   **     Sub-journal file handle         (journalFileSize bytes)
45477   **     Main journal file handle        (journalFileSize bytes)
45478   **     Database file name              (nPathname+1 bytes)
45479   **     Journal file name               (nPathname+8+1 bytes)
45480   */
45481   pPtr = (u8 *)sqlite3MallocZero(
45482     ROUND8(sizeof(*pPager)) +      /* Pager structure */
45483     ROUND8(pcacheSize) +           /* PCache object */
45484     ROUND8(pVfs->szOsFile) +       /* The main db file */
45485     journalFileSize * 2 +          /* The two journal files */
45486     nPathname + 1 + nUri +         /* zFilename */
45487     nPathname + 8 + 2              /* zJournal */
45488 #ifndef SQLITE_OMIT_WAL
45489     + nPathname + 4 + 2            /* zWal */
45490 #endif
45491   );
45492   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
45493   if( !pPtr ){
45494     sqlite3DbFree(0, zPathname);
45495     return SQLITE_NOMEM;
45496   }
45497   pPager =              (Pager*)(pPtr);
45498   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
45499   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
45500   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
45501   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
45502   pPager->zFilename =    (char*)(pPtr += journalFileSize);
45503   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
45504 
45505   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
45506   if( zPathname ){
45507     assert( nPathname>0 );
45508     pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
45509     memcpy(pPager->zFilename, zPathname, nPathname);
45510     if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
45511     memcpy(pPager->zJournal, zPathname, nPathname);
45512     memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
45513     sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
45514 #ifndef SQLITE_OMIT_WAL
45515     pPager->zWal = &pPager->zJournal[nPathname+8+1];
45516     memcpy(pPager->zWal, zPathname, nPathname);
45517     memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
45518     sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
45519 #endif
45520     sqlite3DbFree(0, zPathname);
45521   }
45522   pPager->pVfs = pVfs;
45523   pPager->vfsFlags = vfsFlags;
45524 
45525   /* Open the pager file.
45526   */
45527   if( zFilename && zFilename[0] ){
45528     int fout = 0;                    /* VFS flags returned by xOpen() */
45529     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
45530     assert( !memDb );
45531     readOnly = (fout&SQLITE_OPEN_READONLY);
45532 
45533     /* If the file was successfully opened for read/write access,
45534     ** choose a default page size in case we have to create the
45535     ** database file. The default page size is the maximum of:
45536     **
45537     **    + SQLITE_DEFAULT_PAGE_SIZE,
45538     **    + The value returned by sqlite3OsSectorSize()
45539     **    + The largest page size that can be written atomically.
45540     */
45541     if( rc==SQLITE_OK ){
45542       int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
45543       if( !readOnly ){
45544         setSectorSize(pPager);
45545         assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
45546         if( szPageDflt<pPager->sectorSize ){
45547           if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
45548             szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
45549           }else{
45550             szPageDflt = (u32)pPager->sectorSize;
45551           }
45552         }
45553 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
45554         {
45555           int ii;
45556           assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
45557           assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
45558           assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
45559           for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
45560             if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
45561               szPageDflt = ii;
45562             }
45563           }
45564         }
45565 #endif
45566       }
45567       pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
45568       if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
45569        || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
45570           vfsFlags |= SQLITE_OPEN_READONLY;
45571           goto act_like_temp_file;
45572       }
45573     }
45574   }else{
45575     /* If a temporary file is requested, it is not opened immediately.
45576     ** In this case we accept the default page size and delay actually
45577     ** opening the file until the first call to OsWrite().
45578     **
45579     ** This branch is also run for an in-memory database. An in-memory
45580     ** database is the same as a temp-file that is never written out to
45581     ** disk and uses an in-memory rollback journal.
45582     **
45583     ** This branch also runs for files marked as immutable.
45584     */
45585 act_like_temp_file:
45586     tempFile = 1;
45587     pPager->eState = PAGER_READER;     /* Pretend we already have a lock */
45588     pPager->eLock = EXCLUSIVE_LOCK;    /* Pretend we are in EXCLUSIVE locking mode */
45589     pPager->noLock = 1;                /* Do no locking */
45590     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
45591   }
45592 
45593   /* The following call to PagerSetPagesize() serves to set the value of
45594   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
45595   */
45596   if( rc==SQLITE_OK ){
45597     assert( pPager->memDb==0 );
45598     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
45599     testcase( rc!=SQLITE_OK );
45600   }
45601 
45602   /* Initialize the PCache object. */
45603   if( rc==SQLITE_OK ){
45604     assert( nExtra<1000 );
45605     nExtra = ROUND8(nExtra);
45606     rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
45607                            !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
45608   }
45609 
45610   /* If an error occurred above, free the  Pager structure and close the file.
45611   */
45612   if( rc!=SQLITE_OK ){
45613     sqlite3OsClose(pPager->fd);
45614     sqlite3PageFree(pPager->pTmpSpace);
45615     sqlite3_free(pPager);
45616     return rc;
45617   }
45618 
45619   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
45620   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
45621 
45622   pPager->useJournal = (u8)useJournal;
45623   /* pPager->stmtOpen = 0; */
45624   /* pPager->stmtInUse = 0; */
45625   /* pPager->nRef = 0; */
45626   /* pPager->stmtSize = 0; */
45627   /* pPager->stmtJSize = 0; */
45628   /* pPager->nPage = 0; */
45629   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
45630   /* pPager->state = PAGER_UNLOCK; */
45631   /* pPager->errMask = 0; */
45632   pPager->tempFile = (u8)tempFile;
45633   assert( tempFile==PAGER_LOCKINGMODE_NORMAL
45634           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
45635   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
45636   pPager->exclusiveMode = (u8)tempFile;
45637   pPager->changeCountDone = pPager->tempFile;
45638   pPager->memDb = (u8)memDb;
45639   pPager->readOnly = (u8)readOnly;
45640   assert( useJournal || pPager->tempFile );
45641   pPager->noSync = pPager->tempFile;
45642   if( pPager->noSync ){
45643     assert( pPager->fullSync==0 );
45644     assert( pPager->syncFlags==0 );
45645     assert( pPager->walSyncFlags==0 );
45646     assert( pPager->ckptSyncFlags==0 );
45647   }else{
45648     pPager->fullSync = 1;
45649     pPager->syncFlags = SQLITE_SYNC_NORMAL;
45650     pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
45651     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
45652   }
45653   /* pPager->pFirst = 0; */
45654   /* pPager->pFirstSynced = 0; */
45655   /* pPager->pLast = 0; */
45656   pPager->nExtra = (u16)nExtra;
45657   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
45658   assert( isOpen(pPager->fd) || tempFile );
45659   setSectorSize(pPager);
45660   if( !useJournal ){
45661     pPager->journalMode = PAGER_JOURNALMODE_OFF;
45662   }else if( memDb ){
45663     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
45664   }
45665   /* pPager->xBusyHandler = 0; */
45666   /* pPager->pBusyHandlerArg = 0; */
45667   pPager->xReiniter = xReinit;
45668   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
45669   /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
45670 
45671   *ppPager = pPager;
45672   return SQLITE_OK;
45673 }
45674 
45675 
45676 /* Verify that the database file has not be deleted or renamed out from
45677 ** under the pager.  Return SQLITE_OK if the database is still were it ought
45678 ** to be on disk.  Return non-zero (SQLITE_READONLY_DBMOVED or some other error
45679 ** code from sqlite3OsAccess()) if the database has gone missing.
45680 */
45681 static int databaseIsUnmoved(Pager *pPager){
45682   int bHasMoved = 0;
45683   int rc;
45684 
45685   if( pPager->tempFile ) return SQLITE_OK;
45686   if( pPager->dbSize==0 ) return SQLITE_OK;
45687   assert( pPager->zFilename && pPager->zFilename[0] );
45688   rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
45689   if( rc==SQLITE_NOTFOUND ){
45690     /* If the HAS_MOVED file-control is unimplemented, assume that the file
45691     ** has not been moved.  That is the historical behavior of SQLite: prior to
45692     ** version 3.8.3, it never checked */
45693     rc = SQLITE_OK;
45694   }else if( rc==SQLITE_OK && bHasMoved ){
45695     rc = SQLITE_READONLY_DBMOVED;
45696   }
45697   return rc;
45698 }
45699 
45700 
45701 /*
45702 ** This function is called after transitioning from PAGER_UNLOCK to
45703 ** PAGER_SHARED state. It tests if there is a hot journal present in
45704 ** the file-system for the given pager. A hot journal is one that
45705 ** needs to be played back. According to this function, a hot-journal
45706 ** file exists if the following criteria are met:
45707 **
45708 **   * The journal file exists in the file system, and
45709 **   * No process holds a RESERVED or greater lock on the database file, and
45710 **   * The database file itself is greater than 0 bytes in size, and
45711 **   * The first byte of the journal file exists and is not 0x00.
45712 **
45713 ** If the current size of the database file is 0 but a journal file
45714 ** exists, that is probably an old journal left over from a prior
45715 ** database with the same name. In this case the journal file is
45716 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
45717 ** is returned.
45718 **
45719 ** This routine does not check if there is a master journal filename
45720 ** at the end of the file. If there is, and that master journal file
45721 ** does not exist, then the journal file is not really hot. In this
45722 ** case this routine will return a false-positive. The pager_playback()
45723 ** routine will discover that the journal file is not really hot and
45724 ** will not roll it back.
45725 **
45726 ** If a hot-journal file is found to exist, *pExists is set to 1 and
45727 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
45728 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
45729 ** to determine whether or not a hot-journal file exists, the IO error
45730 ** code is returned and the value of *pExists is undefined.
45731 */
45732 static int hasHotJournal(Pager *pPager, int *pExists){
45733   sqlite3_vfs * const pVfs = pPager->pVfs;
45734   int rc = SQLITE_OK;           /* Return code */
45735   int exists = 1;               /* True if a journal file is present */
45736   int jrnlOpen = !!isOpen(pPager->jfd);
45737 
45738   assert( pPager->useJournal );
45739   assert( isOpen(pPager->fd) );
45740   assert( pPager->eState==PAGER_OPEN );
45741 
45742   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
45743     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
45744   ));
45745 
45746   *pExists = 0;
45747   if( !jrnlOpen ){
45748     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
45749   }
45750   if( rc==SQLITE_OK && exists ){
45751     int locked = 0;             /* True if some process holds a RESERVED lock */
45752 
45753     /* Race condition here:  Another process might have been holding the
45754     ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
45755     ** call above, but then delete the journal and drop the lock before
45756     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
45757     ** is the case, this routine might think there is a hot journal when
45758     ** in fact there is none.  This results in a false-positive which will
45759     ** be dealt with by the playback routine.  Ticket #3883.
45760     */
45761     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
45762     if( rc==SQLITE_OK && !locked ){
45763       Pgno nPage;                 /* Number of pages in database file */
45764 
45765       rc = pagerPagecount(pPager, &nPage);
45766       if( rc==SQLITE_OK ){
45767         /* If the database is zero pages in size, that means that either (1) the
45768         ** journal is a remnant from a prior database with the same name where
45769         ** the database file but not the journal was deleted, or (2) the initial
45770         ** transaction that populates a new database is being rolled back.
45771         ** In either case, the journal file can be deleted.  However, take care
45772         ** not to delete the journal file if it is already open due to
45773         ** journal_mode=PERSIST.
45774         */
45775         if( nPage==0 && !jrnlOpen ){
45776           sqlite3BeginBenignMalloc();
45777           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
45778             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
45779             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
45780           }
45781           sqlite3EndBenignMalloc();
45782         }else{
45783           /* The journal file exists and no other connection has a reserved
45784           ** or greater lock on the database file. Now check that there is
45785           ** at least one non-zero bytes at the start of the journal file.
45786           ** If there is, then we consider this journal to be hot. If not,
45787           ** it can be ignored.
45788           */
45789           if( !jrnlOpen ){
45790             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
45791             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
45792           }
45793           if( rc==SQLITE_OK ){
45794             u8 first = 0;
45795             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
45796             if( rc==SQLITE_IOERR_SHORT_READ ){
45797               rc = SQLITE_OK;
45798             }
45799             if( !jrnlOpen ){
45800               sqlite3OsClose(pPager->jfd);
45801             }
45802             *pExists = (first!=0);
45803           }else if( rc==SQLITE_CANTOPEN ){
45804             /* If we cannot open the rollback journal file in order to see if
45805             ** it has a zero header, that might be due to an I/O error, or
45806             ** it might be due to the race condition described above and in
45807             ** ticket #3883.  Either way, assume that the journal is hot.
45808             ** This might be a false positive.  But if it is, then the
45809             ** automatic journal playback and recovery mechanism will deal
45810             ** with it under an EXCLUSIVE lock where we do not need to
45811             ** worry so much with race conditions.
45812             */
45813             *pExists = 1;
45814             rc = SQLITE_OK;
45815           }
45816         }
45817       }
45818     }
45819   }
45820 
45821   return rc;
45822 }
45823 
45824 /*
45825 ** This function is called to obtain a shared lock on the database file.
45826 ** It is illegal to call sqlite3PagerAcquire() until after this function
45827 ** has been successfully called. If a shared-lock is already held when
45828 ** this function is called, it is a no-op.
45829 **
45830 ** The following operations are also performed by this function.
45831 **
45832 **   1) If the pager is currently in PAGER_OPEN state (no lock held
45833 **      on the database file), then an attempt is made to obtain a
45834 **      SHARED lock on the database file. Immediately after obtaining
45835 **      the SHARED lock, the file-system is checked for a hot-journal,
45836 **      which is played back if present. Following any hot-journal
45837 **      rollback, the contents of the cache are validated by checking
45838 **      the 'change-counter' field of the database file header and
45839 **      discarded if they are found to be invalid.
45840 **
45841 **   2) If the pager is running in exclusive-mode, and there are currently
45842 **      no outstanding references to any pages, and is in the error state,
45843 **      then an attempt is made to clear the error state by discarding
45844 **      the contents of the page cache and rolling back any open journal
45845 **      file.
45846 **
45847 ** If everything is successful, SQLITE_OK is returned. If an IO error
45848 ** occurs while locking the database, checking for a hot-journal file or
45849 ** rolling back a journal file, the IO error code is returned.
45850 */
45851 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
45852   int rc = SQLITE_OK;                /* Return code */
45853 
45854   /* This routine is only called from b-tree and only when there are no
45855   ** outstanding pages. This implies that the pager state should either
45856   ** be OPEN or READER. READER is only possible if the pager is or was in
45857   ** exclusive access mode.
45858   */
45859   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
45860   assert( assert_pager_state(pPager) );
45861   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
45862   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
45863 
45864   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
45865     int bHotJournal = 1;          /* True if there exists a hot journal-file */
45866 
45867     assert( !MEMDB );
45868 
45869     rc = pager_wait_on_lock(pPager, SHARED_LOCK);
45870     if( rc!=SQLITE_OK ){
45871       assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
45872       goto failed;
45873     }
45874 
45875     /* If a journal file exists, and there is no RESERVED lock on the
45876     ** database file, then it either needs to be played back or deleted.
45877     */
45878     if( pPager->eLock<=SHARED_LOCK ){
45879       rc = hasHotJournal(pPager, &bHotJournal);
45880     }
45881     if( rc!=SQLITE_OK ){
45882       goto failed;
45883     }
45884     if( bHotJournal ){
45885       if( pPager->readOnly ){
45886         rc = SQLITE_READONLY_ROLLBACK;
45887         goto failed;
45888       }
45889 
45890       /* Get an EXCLUSIVE lock on the database file. At this point it is
45891       ** important that a RESERVED lock is not obtained on the way to the
45892       ** EXCLUSIVE lock. If it were, another process might open the
45893       ** database file, detect the RESERVED lock, and conclude that the
45894       ** database is safe to read while this process is still rolling the
45895       ** hot-journal back.
45896       **
45897       ** Because the intermediate RESERVED lock is not requested, any
45898       ** other process attempting to access the database file will get to
45899       ** this point in the code and fail to obtain its own EXCLUSIVE lock
45900       ** on the database file.
45901       **
45902       ** Unless the pager is in locking_mode=exclusive mode, the lock is
45903       ** downgraded to SHARED_LOCK before this function returns.
45904       */
45905       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
45906       if( rc!=SQLITE_OK ){
45907         goto failed;
45908       }
45909 
45910       /* If it is not already open and the file exists on disk, open the
45911       ** journal for read/write access. Write access is required because
45912       ** in exclusive-access mode the file descriptor will be kept open
45913       ** and possibly used for a transaction later on. Also, write-access
45914       ** is usually required to finalize the journal in journal_mode=persist
45915       ** mode (and also for journal_mode=truncate on some systems).
45916       **
45917       ** If the journal does not exist, it usually means that some
45918       ** other connection managed to get in and roll it back before
45919       ** this connection obtained the exclusive lock above. Or, it
45920       ** may mean that the pager was in the error-state when this
45921       ** function was called and the journal file does not exist.
45922       */
45923       if( !isOpen(pPager->jfd) ){
45924         sqlite3_vfs * const pVfs = pPager->pVfs;
45925         int bExists;              /* True if journal file exists */
45926         rc = sqlite3OsAccess(
45927             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
45928         if( rc==SQLITE_OK && bExists ){
45929           int fout = 0;
45930           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
45931           assert( !pPager->tempFile );
45932           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
45933           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
45934           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
45935             rc = SQLITE_CANTOPEN_BKPT;
45936             sqlite3OsClose(pPager->jfd);
45937           }
45938         }
45939       }
45940 
45941       /* Playback and delete the journal.  Drop the database write
45942       ** lock and reacquire the read lock. Purge the cache before
45943       ** playing back the hot-journal so that we don't end up with
45944       ** an inconsistent cache.  Sync the hot journal before playing
45945       ** it back since the process that crashed and left the hot journal
45946       ** probably did not sync it and we are required to always sync
45947       ** the journal before playing it back.
45948       */
45949       if( isOpen(pPager->jfd) ){
45950         assert( rc==SQLITE_OK );
45951         rc = pagerSyncHotJournal(pPager);
45952         if( rc==SQLITE_OK ){
45953           rc = pager_playback(pPager, 1);
45954           pPager->eState = PAGER_OPEN;
45955         }
45956       }else if( !pPager->exclusiveMode ){
45957         pagerUnlockDb(pPager, SHARED_LOCK);
45958       }
45959 
45960       if( rc!=SQLITE_OK ){
45961         /* This branch is taken if an error occurs while trying to open
45962         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
45963         ** pager_unlock() routine will be called before returning to unlock
45964         ** the file. If the unlock attempt fails, then Pager.eLock must be
45965         ** set to UNKNOWN_LOCK (see the comment above the #define for
45966         ** UNKNOWN_LOCK above for an explanation).
45967         **
45968         ** In order to get pager_unlock() to do this, set Pager.eState to
45969         ** PAGER_ERROR now. This is not actually counted as a transition
45970         ** to ERROR state in the state diagram at the top of this file,
45971         ** since we know that the same call to pager_unlock() will very
45972         ** shortly transition the pager object to the OPEN state. Calling
45973         ** assert_pager_state() would fail now, as it should not be possible
45974         ** to be in ERROR state when there are zero outstanding page
45975         ** references.
45976         */
45977         pager_error(pPager, rc);
45978         goto failed;
45979       }
45980 
45981       assert( pPager->eState==PAGER_OPEN );
45982       assert( (pPager->eLock==SHARED_LOCK)
45983            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
45984       );
45985     }
45986 
45987     if( !pPager->tempFile && (
45988         pPager->pBackup
45989      || sqlite3PcachePagecount(pPager->pPCache)>0
45990      || USEFETCH(pPager)
45991     )){
45992       /* The shared-lock has just been acquired on the database file
45993       ** and there are already pages in the cache (from a previous
45994       ** read or write transaction).  Check to see if the database
45995       ** has been modified.  If the database has changed, flush the
45996       ** cache.
45997       **
45998       ** Database changes is detected by looking at 15 bytes beginning
45999       ** at offset 24 into the file.  The first 4 of these 16 bytes are
46000       ** a 32-bit counter that is incremented with each change.  The
46001       ** other bytes change randomly with each file change when
46002       ** a codec is in use.
46003       **
46004       ** There is a vanishingly small chance that a change will not be
46005       ** detected.  The chance of an undetected change is so small that
46006       ** it can be neglected.
46007       */
46008       Pgno nPage = 0;
46009       char dbFileVers[sizeof(pPager->dbFileVers)];
46010 
46011       rc = pagerPagecount(pPager, &nPage);
46012       if( rc ) goto failed;
46013 
46014       if( nPage>0 ){
46015         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
46016         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
46017         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
46018           goto failed;
46019         }
46020       }else{
46021         memset(dbFileVers, 0, sizeof(dbFileVers));
46022       }
46023 
46024       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
46025         pager_reset(pPager);
46026 
46027         /* Unmap the database file. It is possible that external processes
46028         ** may have truncated the database file and then extended it back
46029         ** to its original size while this process was not holding a lock.
46030         ** In this case there may exist a Pager.pMap mapping that appears
46031         ** to be the right size but is not actually valid. Avoid this
46032         ** possibility by unmapping the db here. */
46033         if( USEFETCH(pPager) ){
46034           sqlite3OsUnfetch(pPager->fd, 0, 0);
46035         }
46036       }
46037     }
46038 
46039     /* If there is a WAL file in the file-system, open this database in WAL
46040     ** mode. Otherwise, the following function call is a no-op.
46041     */
46042     rc = pagerOpenWalIfPresent(pPager);
46043 #ifndef SQLITE_OMIT_WAL
46044     assert( pPager->pWal==0 || rc==SQLITE_OK );
46045 #endif
46046   }
46047 
46048   if( pagerUseWal(pPager) ){
46049     assert( rc==SQLITE_OK );
46050     rc = pagerBeginReadTransaction(pPager);
46051   }
46052 
46053   if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
46054     rc = pagerPagecount(pPager, &pPager->dbSize);
46055   }
46056 
46057  failed:
46058   if( rc!=SQLITE_OK ){
46059     assert( !MEMDB );
46060     pager_unlock(pPager);
46061     assert( pPager->eState==PAGER_OPEN );
46062   }else{
46063     pPager->eState = PAGER_READER;
46064   }
46065   return rc;
46066 }
46067 
46068 /*
46069 ** If the reference count has reached zero, rollback any active
46070 ** transaction and unlock the pager.
46071 **
46072 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
46073 ** the rollback journal, the unlock is not performed and there is
46074 ** nothing to rollback, so this routine is a no-op.
46075 */
46076 static void pagerUnlockIfUnused(Pager *pPager){
46077   if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
46078     pagerUnlockAndRollback(pPager);
46079   }
46080 }
46081 
46082 /*
46083 ** Acquire a reference to page number pgno in pager pPager (a page
46084 ** reference has type DbPage*). If the requested reference is
46085 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
46086 **
46087 ** If the requested page is already in the cache, it is returned.
46088 ** Otherwise, a new page object is allocated and populated with data
46089 ** read from the database file. In some cases, the pcache module may
46090 ** choose not to allocate a new page object and may reuse an existing
46091 ** object with no outstanding references.
46092 **
46093 ** The extra data appended to a page is always initialized to zeros the
46094 ** first time a page is loaded into memory. If the page requested is
46095 ** already in the cache when this function is called, then the extra
46096 ** data is left as it was when the page object was last used.
46097 **
46098 ** If the database image is smaller than the requested page or if a
46099 ** non-zero value is passed as the noContent parameter and the
46100 ** requested page is not already stored in the cache, then no
46101 ** actual disk read occurs. In this case the memory image of the
46102 ** page is initialized to all zeros.
46103 **
46104 ** If noContent is true, it means that we do not care about the contents
46105 ** of the page. This occurs in two scenarios:
46106 **
46107 **   a) When reading a free-list leaf page from the database, and
46108 **
46109 **   b) When a savepoint is being rolled back and we need to load
46110 **      a new page into the cache to be filled with the data read
46111 **      from the savepoint journal.
46112 **
46113 ** If noContent is true, then the data returned is zeroed instead of
46114 ** being read from the database. Additionally, the bits corresponding
46115 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
46116 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
46117 ** savepoints are set. This means if the page is made writable at any
46118 ** point in the future, using a call to sqlite3PagerWrite(), its contents
46119 ** will not be journaled. This saves IO.
46120 **
46121 ** The acquisition might fail for several reasons.  In all cases,
46122 ** an appropriate error code is returned and *ppPage is set to NULL.
46123 **
46124 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
46125 ** to find a page in the in-memory cache first.  If the page is not already
46126 ** in memory, this routine goes to disk to read it in whereas Lookup()
46127 ** just returns 0.  This routine acquires a read-lock the first time it
46128 ** has to go to disk, and could also playback an old journal if necessary.
46129 ** Since Lookup() never goes to disk, it never has to deal with locks
46130 ** or journal files.
46131 */
46132 SQLITE_PRIVATE int sqlite3PagerAcquire(
46133   Pager *pPager,      /* The pager open on the database file */
46134   Pgno pgno,          /* Page number to fetch */
46135   DbPage **ppPage,    /* Write a pointer to the page here */
46136   int flags           /* PAGER_GET_XXX flags */
46137 ){
46138   int rc = SQLITE_OK;
46139   PgHdr *pPg = 0;
46140   u32 iFrame = 0;                 /* Frame to read from WAL file */
46141   const int noContent = (flags & PAGER_GET_NOCONTENT);
46142 
46143   /* It is acceptable to use a read-only (mmap) page for any page except
46144   ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
46145   ** flag was specified by the caller. And so long as the db is not a
46146   ** temporary or in-memory database.  */
46147   const int bMmapOk = (pgno!=1 && USEFETCH(pPager)
46148    && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
46149 #ifdef SQLITE_HAS_CODEC
46150    && pPager->xCodec==0
46151 #endif
46152   );
46153 
46154   assert( pPager->eState>=PAGER_READER );
46155   assert( assert_pager_state(pPager) );
46156   assert( noContent==0 || bMmapOk==0 );
46157 
46158   if( pgno==0 ){
46159     return SQLITE_CORRUPT_BKPT;
46160   }
46161 
46162   /* If the pager is in the error state, return an error immediately.
46163   ** Otherwise, request the page from the PCache layer. */
46164   if( pPager->errCode!=SQLITE_OK ){
46165     rc = pPager->errCode;
46166   }else{
46167     if( bMmapOk && pagerUseWal(pPager) ){
46168       rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
46169       if( rc!=SQLITE_OK ) goto pager_acquire_err;
46170     }
46171 
46172     if( bMmapOk && iFrame==0 ){
46173       void *pData = 0;
46174 
46175       rc = sqlite3OsFetch(pPager->fd,
46176           (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
46177       );
46178 
46179       if( rc==SQLITE_OK && pData ){
46180         if( pPager->eState>PAGER_READER ){
46181           pPg = sqlite3PagerLookup(pPager, pgno);
46182         }
46183         if( pPg==0 ){
46184           rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
46185         }else{
46186           sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
46187         }
46188         if( pPg ){
46189           assert( rc==SQLITE_OK );
46190           *ppPage = pPg;
46191           return SQLITE_OK;
46192         }
46193       }
46194       if( rc!=SQLITE_OK ){
46195         goto pager_acquire_err;
46196       }
46197     }
46198 
46199     {
46200       sqlite3_pcache_page *pBase;
46201       pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
46202       if( pBase==0 ){
46203         rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
46204         if( rc!=SQLITE_OK ) goto pager_acquire_err;
46205       }
46206       pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
46207       if( pPg==0 ) rc = SQLITE_NOMEM;
46208     }
46209   }
46210 
46211   if( rc!=SQLITE_OK ){
46212     /* Either the call to sqlite3PcacheFetch() returned an error or the
46213     ** pager was already in the error-state when this function was called.
46214     ** Set pPg to 0 and jump to the exception handler.  */
46215     pPg = 0;
46216     goto pager_acquire_err;
46217   }
46218   assert( (*ppPage)->pgno==pgno );
46219   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
46220 
46221   if( (*ppPage)->pPager && !noContent ){
46222     /* In this case the pcache already contains an initialized copy of
46223     ** the page. Return without further ado.  */
46224     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
46225     pPager->aStat[PAGER_STAT_HIT]++;
46226     return SQLITE_OK;
46227 
46228   }else{
46229     /* The pager cache has created a new page. Its content needs to
46230     ** be initialized.  */
46231 
46232     pPg = *ppPage;
46233     pPg->pPager = pPager;
46234 
46235     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
46236     ** number greater than this, or the unused locking-page, is requested. */
46237     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
46238       rc = SQLITE_CORRUPT_BKPT;
46239       goto pager_acquire_err;
46240     }
46241 
46242     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
46243       if( pgno>pPager->mxPgno ){
46244         rc = SQLITE_FULL;
46245         goto pager_acquire_err;
46246       }
46247       if( noContent ){
46248         /* Failure to set the bits in the InJournal bit-vectors is benign.
46249         ** It merely means that we might do some extra work to journal a
46250         ** page that does not need to be journaled.  Nevertheless, be sure
46251         ** to test the case where a malloc error occurs while trying to set
46252         ** a bit in a bit vector.
46253         */
46254         sqlite3BeginBenignMalloc();
46255         if( pgno<=pPager->dbOrigSize ){
46256           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
46257           testcase( rc==SQLITE_NOMEM );
46258         }
46259         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
46260         testcase( rc==SQLITE_NOMEM );
46261         sqlite3EndBenignMalloc();
46262       }
46263       memset(pPg->pData, 0, pPager->pageSize);
46264       IOTRACE(("ZERO %p %d\n", pPager, pgno));
46265     }else{
46266       if( pagerUseWal(pPager) && bMmapOk==0 ){
46267         rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
46268         if( rc!=SQLITE_OK ) goto pager_acquire_err;
46269       }
46270       assert( pPg->pPager==pPager );
46271       pPager->aStat[PAGER_STAT_MISS]++;
46272       rc = readDbPage(pPg, iFrame);
46273       if( rc!=SQLITE_OK ){
46274         goto pager_acquire_err;
46275       }
46276     }
46277     pager_set_pagehash(pPg);
46278   }
46279 
46280   return SQLITE_OK;
46281 
46282 pager_acquire_err:
46283   assert( rc!=SQLITE_OK );
46284   if( pPg ){
46285     sqlite3PcacheDrop(pPg);
46286   }
46287   pagerUnlockIfUnused(pPager);
46288 
46289   *ppPage = 0;
46290   return rc;
46291 }
46292 
46293 /*
46294 ** Acquire a page if it is already in the in-memory cache.  Do
46295 ** not read the page from disk.  Return a pointer to the page,
46296 ** or 0 if the page is not in cache.
46297 **
46298 ** See also sqlite3PagerGet().  The difference between this routine
46299 ** and sqlite3PagerGet() is that _get() will go to the disk and read
46300 ** in the page if the page is not already in cache.  This routine
46301 ** returns NULL if the page is not in cache or if a disk I/O error
46302 ** has ever happened.
46303 */
46304 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
46305   sqlite3_pcache_page *pPage;
46306   assert( pPager!=0 );
46307   assert( pgno!=0 );
46308   assert( pPager->pPCache!=0 );
46309   pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
46310   return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
46311 }
46312 
46313 /*
46314 ** Release a page reference.
46315 **
46316 ** If the number of references to the page drop to zero, then the
46317 ** page is added to the LRU list.  When all references to all pages
46318 ** are released, a rollback occurs and the lock on the database is
46319 ** removed.
46320 */
46321 SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
46322   Pager *pPager;
46323   assert( pPg!=0 );
46324   pPager = pPg->pPager;
46325   if( pPg->flags & PGHDR_MMAP ){
46326     pagerReleaseMapPage(pPg);
46327   }else{
46328     sqlite3PcacheRelease(pPg);
46329   }
46330   pagerUnlockIfUnused(pPager);
46331 }
46332 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
46333   if( pPg ) sqlite3PagerUnrefNotNull(pPg);
46334 }
46335 
46336 /*
46337 ** This function is called at the start of every write transaction.
46338 ** There must already be a RESERVED or EXCLUSIVE lock on the database
46339 ** file when this routine is called.
46340 **
46341 ** Open the journal file for pager pPager and write a journal header
46342 ** to the start of it. If there are active savepoints, open the sub-journal
46343 ** as well. This function is only used when the journal file is being
46344 ** opened to write a rollback log for a transaction. It is not used
46345 ** when opening a hot journal file to roll it back.
46346 **
46347 ** If the journal file is already open (as it may be in exclusive mode),
46348 ** then this function just writes a journal header to the start of the
46349 ** already open file.
46350 **
46351 ** Whether or not the journal file is opened by this function, the
46352 ** Pager.pInJournal bitvec structure is allocated.
46353 **
46354 ** Return SQLITE_OK if everything is successful. Otherwise, return
46355 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
46356 ** an IO error code if opening or writing the journal file fails.
46357 */
46358 static int pager_open_journal(Pager *pPager){
46359   int rc = SQLITE_OK;                        /* Return code */
46360   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
46361 
46362   assert( pPager->eState==PAGER_WRITER_LOCKED );
46363   assert( assert_pager_state(pPager) );
46364   assert( pPager->pInJournal==0 );
46365 
46366   /* If already in the error state, this function is a no-op.  But on
46367   ** the other hand, this routine is never called if we are already in
46368   ** an error state. */
46369   if( NEVER(pPager->errCode) ) return pPager->errCode;
46370 
46371   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
46372     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
46373     if( pPager->pInJournal==0 ){
46374       return SQLITE_NOMEM;
46375     }
46376 
46377     /* Open the journal file if it is not already open. */
46378     if( !isOpen(pPager->jfd) ){
46379       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
46380         sqlite3MemJournalOpen(pPager->jfd);
46381       }else{
46382         const int flags =                   /* VFS flags to open journal file */
46383           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
46384           (pPager->tempFile ?
46385             (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
46386             (SQLITE_OPEN_MAIN_JOURNAL)
46387           );
46388 
46389         /* Verify that the database still has the same name as it did when
46390         ** it was originally opened. */
46391         rc = databaseIsUnmoved(pPager);
46392         if( rc==SQLITE_OK ){
46393 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
46394           rc = sqlite3JournalOpen(
46395               pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
46396           );
46397 #else
46398           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
46399 #endif
46400         }
46401       }
46402       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
46403     }
46404 
46405 
46406     /* Write the first journal header to the journal file and open
46407     ** the sub-journal if necessary.
46408     */
46409     if( rc==SQLITE_OK ){
46410       /* TODO: Check if all of these are really required. */
46411       pPager->nRec = 0;
46412       pPager->journalOff = 0;
46413       pPager->setMaster = 0;
46414       pPager->journalHdr = 0;
46415       rc = writeJournalHdr(pPager);
46416     }
46417   }
46418 
46419   if( rc!=SQLITE_OK ){
46420     sqlite3BitvecDestroy(pPager->pInJournal);
46421     pPager->pInJournal = 0;
46422   }else{
46423     assert( pPager->eState==PAGER_WRITER_LOCKED );
46424     pPager->eState = PAGER_WRITER_CACHEMOD;
46425   }
46426 
46427   return rc;
46428 }
46429 
46430 /*
46431 ** Begin a write-transaction on the specified pager object. If a
46432 ** write-transaction has already been opened, this function is a no-op.
46433 **
46434 ** If the exFlag argument is false, then acquire at least a RESERVED
46435 ** lock on the database file. If exFlag is true, then acquire at least
46436 ** an EXCLUSIVE lock. If such a lock is already held, no locking
46437 ** functions need be called.
46438 **
46439 ** If the subjInMemory argument is non-zero, then any sub-journal opened
46440 ** within this transaction will be opened as an in-memory file. This
46441 ** has no effect if the sub-journal is already opened (as it may be when
46442 ** running in exclusive mode) or if the transaction does not require a
46443 ** sub-journal. If the subjInMemory argument is zero, then any required
46444 ** sub-journal is implemented in-memory if pPager is an in-memory database,
46445 ** or using a temporary file otherwise.
46446 */
46447 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
46448   int rc = SQLITE_OK;
46449 
46450   if( pPager->errCode ) return pPager->errCode;
46451   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
46452   pPager->subjInMemory = (u8)subjInMemory;
46453 
46454   if( ALWAYS(pPager->eState==PAGER_READER) ){
46455     assert( pPager->pInJournal==0 );
46456 
46457     if( pagerUseWal(pPager) ){
46458       /* If the pager is configured to use locking_mode=exclusive, and an
46459       ** exclusive lock on the database is not already held, obtain it now.
46460       */
46461       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
46462         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
46463         if( rc!=SQLITE_OK ){
46464           return rc;
46465         }
46466         sqlite3WalExclusiveMode(pPager->pWal, 1);
46467       }
46468 
46469       /* Grab the write lock on the log file. If successful, upgrade to
46470       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
46471       ** The busy-handler is not invoked if another connection already
46472       ** holds the write-lock. If possible, the upper layer will call it.
46473       */
46474       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
46475     }else{
46476       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
46477       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
46478       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
46479       ** lock, but not when obtaining the RESERVED lock.
46480       */
46481       rc = pagerLockDb(pPager, RESERVED_LOCK);
46482       if( rc==SQLITE_OK && exFlag ){
46483         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
46484       }
46485     }
46486 
46487     if( rc==SQLITE_OK ){
46488       /* Change to WRITER_LOCKED state.
46489       **
46490       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
46491       ** when it has an open transaction, but never to DBMOD or FINISHED.
46492       ** This is because in those states the code to roll back savepoint
46493       ** transactions may copy data from the sub-journal into the database
46494       ** file as well as into the page cache. Which would be incorrect in
46495       ** WAL mode.
46496       */
46497       pPager->eState = PAGER_WRITER_LOCKED;
46498       pPager->dbHintSize = pPager->dbSize;
46499       pPager->dbFileSize = pPager->dbSize;
46500       pPager->dbOrigSize = pPager->dbSize;
46501       pPager->journalOff = 0;
46502     }
46503 
46504     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
46505     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
46506     assert( assert_pager_state(pPager) );
46507   }
46508 
46509   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
46510   return rc;
46511 }
46512 
46513 /*
46514 ** Mark a single data page as writeable. The page is written into the
46515 ** main journal or sub-journal as required. If the page is written into
46516 ** one of the journals, the corresponding bit is set in the
46517 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
46518 ** of any open savepoints as appropriate.
46519 */
46520 static int pager_write(PgHdr *pPg){
46521   Pager *pPager = pPg->pPager;
46522   int rc = SQLITE_OK;
46523   int inJournal;
46524 
46525   /* This routine is not called unless a write-transaction has already
46526   ** been started. The journal file may or may not be open at this point.
46527   ** It is never called in the ERROR state.
46528   */
46529   assert( pPager->eState==PAGER_WRITER_LOCKED
46530        || pPager->eState==PAGER_WRITER_CACHEMOD
46531        || pPager->eState==PAGER_WRITER_DBMOD
46532   );
46533   assert( assert_pager_state(pPager) );
46534   assert( pPager->errCode==0 );
46535   assert( pPager->readOnly==0 );
46536 
46537   CHECK_PAGE(pPg);
46538 
46539   /* The journal file needs to be opened. Higher level routines have already
46540   ** obtained the necessary locks to begin the write-transaction, but the
46541   ** rollback journal might not yet be open. Open it now if this is the case.
46542   **
46543   ** This is done before calling sqlite3PcacheMakeDirty() on the page.
46544   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
46545   ** an error might occur and the pager would end up in WRITER_LOCKED state
46546   ** with pages marked as dirty in the cache.
46547   */
46548   if( pPager->eState==PAGER_WRITER_LOCKED ){
46549     rc = pager_open_journal(pPager);
46550     if( rc!=SQLITE_OK ) return rc;
46551   }
46552   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
46553   assert( assert_pager_state(pPager) );
46554 
46555   /* Mark the page as dirty.  If the page has already been written
46556   ** to the journal then we can return right away.
46557   */
46558   sqlite3PcacheMakeDirty(pPg);
46559   inJournal = pageInJournal(pPager, pPg);
46560   if( inJournal && (pPager->nSavepoint==0 || !subjRequiresPage(pPg)) ){
46561     assert( !pagerUseWal(pPager) );
46562   }else{
46563 
46564     /* The transaction journal now exists and we have a RESERVED or an
46565     ** EXCLUSIVE lock on the main database file.  Write the current page to
46566     ** the transaction journal if it is not there already.
46567     */
46568     if( !inJournal && !pagerUseWal(pPager) ){
46569       assert( pagerUseWal(pPager)==0 );
46570       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
46571         u32 cksum;
46572         char *pData2;
46573         i64 iOff = pPager->journalOff;
46574 
46575         /* We should never write to the journal file the page that
46576         ** contains the database locks.  The following assert verifies
46577         ** that we do not. */
46578         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
46579 
46580         assert( pPager->journalHdr<=pPager->journalOff );
46581         CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
46582         cksum = pager_cksum(pPager, (u8*)pData2);
46583 
46584         /* Even if an IO or diskfull error occurs while journalling the
46585         ** page in the block above, set the need-sync flag for the page.
46586         ** Otherwise, when the transaction is rolled back, the logic in
46587         ** playback_one_page() will think that the page needs to be restored
46588         ** in the database file. And if an IO error occurs while doing so,
46589         ** then corruption may follow.
46590         */
46591         pPg->flags |= PGHDR_NEED_SYNC;
46592 
46593         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
46594         if( rc!=SQLITE_OK ) return rc;
46595         rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
46596         if( rc!=SQLITE_OK ) return rc;
46597         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
46598         if( rc!=SQLITE_OK ) return rc;
46599 
46600         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
46601                  pPager->journalOff, pPager->pageSize));
46602         PAGER_INCR(sqlite3_pager_writej_count);
46603         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
46604              PAGERID(pPager), pPg->pgno,
46605              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
46606 
46607         pPager->journalOff += 8 + pPager->pageSize;
46608         pPager->nRec++;
46609         assert( pPager->pInJournal!=0 );
46610         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
46611         testcase( rc==SQLITE_NOMEM );
46612         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
46613         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
46614         if( rc!=SQLITE_OK ){
46615           assert( rc==SQLITE_NOMEM );
46616           return rc;
46617         }
46618       }else{
46619         if( pPager->eState!=PAGER_WRITER_DBMOD ){
46620           pPg->flags |= PGHDR_NEED_SYNC;
46621         }
46622         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
46623                 PAGERID(pPager), pPg->pgno,
46624                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
46625       }
46626     }
46627 
46628     /* If the statement journal is open and the page is not in it,
46629     ** then write the current page to the statement journal.  Note that
46630     ** the statement journal format differs from the standard journal format
46631     ** in that it omits the checksums and the header.
46632     */
46633     if( pPager->nSavepoint>0 && subjRequiresPage(pPg) ){
46634       rc = subjournalPage(pPg);
46635     }
46636   }
46637 
46638   /* Update the database size and return.
46639   */
46640   if( pPager->dbSize<pPg->pgno ){
46641     pPager->dbSize = pPg->pgno;
46642   }
46643   return rc;
46644 }
46645 
46646 /*
46647 ** This is a variant of sqlite3PagerWrite() that runs when the sector size
46648 ** is larger than the page size.  SQLite makes the (reasonable) assumption that
46649 ** all bytes of a sector are written together by hardware.  Hence, all bytes of
46650 ** a sector need to be journalled in case of a power loss in the middle of
46651 ** a write.
46652 **
46653 ** Usually, the sector size is less than or equal to the page size, in which
46654 ** case pages can be individually written.  This routine only runs in the exceptional
46655 ** case where the page size is smaller than the sector size.
46656 */
46657 static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
46658   int rc = SQLITE_OK;            /* Return code */
46659   Pgno nPageCount;               /* Total number of pages in database file */
46660   Pgno pg1;                      /* First page of the sector pPg is located on. */
46661   int nPage = 0;                 /* Number of pages starting at pg1 to journal */
46662   int ii;                        /* Loop counter */
46663   int needSync = 0;              /* True if any page has PGHDR_NEED_SYNC */
46664   Pager *pPager = pPg->pPager;   /* The pager that owns pPg */
46665   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
46666 
46667   /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
46668   ** a journal header to be written between the pages journaled by
46669   ** this function.
46670   */
46671   assert( !MEMDB );
46672   assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
46673   pPager->doNotSpill |= SPILLFLAG_NOSYNC;
46674 
46675   /* This trick assumes that both the page-size and sector-size are
46676   ** an integer power of 2. It sets variable pg1 to the identifier
46677   ** of the first page of the sector pPg is located on.
46678   */
46679   pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
46680 
46681   nPageCount = pPager->dbSize;
46682   if( pPg->pgno>nPageCount ){
46683     nPage = (pPg->pgno - pg1)+1;
46684   }else if( (pg1+nPagePerSector-1)>nPageCount ){
46685     nPage = nPageCount+1-pg1;
46686   }else{
46687     nPage = nPagePerSector;
46688   }
46689   assert(nPage>0);
46690   assert(pg1<=pPg->pgno);
46691   assert((pg1+nPage)>pPg->pgno);
46692 
46693   for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
46694     Pgno pg = pg1+ii;
46695     PgHdr *pPage;
46696     if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
46697       if( pg!=PAGER_MJ_PGNO(pPager) ){
46698         rc = sqlite3PagerGet(pPager, pg, &pPage);
46699         if( rc==SQLITE_OK ){
46700           rc = pager_write(pPage);
46701           if( pPage->flags&PGHDR_NEED_SYNC ){
46702             needSync = 1;
46703           }
46704           sqlite3PagerUnrefNotNull(pPage);
46705         }
46706       }
46707     }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
46708       if( pPage->flags&PGHDR_NEED_SYNC ){
46709         needSync = 1;
46710       }
46711       sqlite3PagerUnrefNotNull(pPage);
46712     }
46713   }
46714 
46715   /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
46716   ** starting at pg1, then it needs to be set for all of them. Because
46717   ** writing to any of these nPage pages may damage the others, the
46718   ** journal file must contain sync()ed copies of all of them
46719   ** before any of them can be written out to the database file.
46720   */
46721   if( rc==SQLITE_OK && needSync ){
46722     assert( !MEMDB );
46723     for(ii=0; ii<nPage; ii++){
46724       PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
46725       if( pPage ){
46726         pPage->flags |= PGHDR_NEED_SYNC;
46727         sqlite3PagerUnrefNotNull(pPage);
46728       }
46729     }
46730   }
46731 
46732   assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
46733   pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
46734   return rc;
46735 }
46736 
46737 /*
46738 ** Mark a data page as writeable. This routine must be called before
46739 ** making changes to a page. The caller must check the return value
46740 ** of this function and be careful not to change any page data unless
46741 ** this routine returns SQLITE_OK.
46742 **
46743 ** The difference between this function and pager_write() is that this
46744 ** function also deals with the special case where 2 or more pages
46745 ** fit on a single disk sector. In this case all co-resident pages
46746 ** must have been written to the journal file before returning.
46747 **
46748 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
46749 ** as appropriate. Otherwise, SQLITE_OK.
46750 */
46751 SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
46752   assert( (pPg->flags & PGHDR_MMAP)==0 );
46753   assert( pPg->pPager->eState>=PAGER_WRITER_LOCKED );
46754   assert( pPg->pPager->eState!=PAGER_ERROR );
46755   assert( assert_pager_state(pPg->pPager) );
46756   if( pPg->pPager->sectorSize > (u32)pPg->pPager->pageSize ){
46757     return pagerWriteLargeSector(pPg);
46758   }else{
46759     return pager_write(pPg);
46760   }
46761 }
46762 
46763 /*
46764 ** Return TRUE if the page given in the argument was previously passed
46765 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
46766 ** to change the content of the page.
46767 */
46768 #ifndef NDEBUG
46769 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
46770   return pPg->flags&PGHDR_DIRTY;
46771 }
46772 #endif
46773 
46774 /*
46775 ** A call to this routine tells the pager that it is not necessary to
46776 ** write the information on page pPg back to the disk, even though
46777 ** that page might be marked as dirty.  This happens, for example, when
46778 ** the page has been added as a leaf of the freelist and so its
46779 ** content no longer matters.
46780 **
46781 ** The overlying software layer calls this routine when all of the data
46782 ** on the given page is unused. The pager marks the page as clean so
46783 ** that it does not get written to disk.
46784 **
46785 ** Tests show that this optimization can quadruple the speed of large
46786 ** DELETE operations.
46787 */
46788 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
46789   Pager *pPager = pPg->pPager;
46790   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
46791     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
46792     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
46793     pPg->flags |= PGHDR_DONT_WRITE;
46794     pager_set_pagehash(pPg);
46795   }
46796 }
46797 
46798 /*
46799 ** This routine is called to increment the value of the database file
46800 ** change-counter, stored as a 4-byte big-endian integer starting at
46801 ** byte offset 24 of the pager file.  The secondary change counter at
46802 ** 92 is also updated, as is the SQLite version number at offset 96.
46803 **
46804 ** But this only happens if the pPager->changeCountDone flag is false.
46805 ** To avoid excess churning of page 1, the update only happens once.
46806 ** See also the pager_write_changecounter() routine that does an
46807 ** unconditional update of the change counters.
46808 **
46809 ** If the isDirectMode flag is zero, then this is done by calling
46810 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
46811 ** page data. In this case the file will be updated when the current
46812 ** transaction is committed.
46813 **
46814 ** The isDirectMode flag may only be non-zero if the library was compiled
46815 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
46816 ** if isDirect is non-zero, then the database file is updated directly
46817 ** by writing an updated version of page 1 using a call to the
46818 ** sqlite3OsWrite() function.
46819 */
46820 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
46821   int rc = SQLITE_OK;
46822 
46823   assert( pPager->eState==PAGER_WRITER_CACHEMOD
46824        || pPager->eState==PAGER_WRITER_DBMOD
46825   );
46826   assert( assert_pager_state(pPager) );
46827 
46828   /* Declare and initialize constant integer 'isDirect'. If the
46829   ** atomic-write optimization is enabled in this build, then isDirect
46830   ** is initialized to the value passed as the isDirectMode parameter
46831   ** to this function. Otherwise, it is always set to zero.
46832   **
46833   ** The idea is that if the atomic-write optimization is not
46834   ** enabled at compile time, the compiler can omit the tests of
46835   ** 'isDirect' below, as well as the block enclosed in the
46836   ** "if( isDirect )" condition.
46837   */
46838 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
46839 # define DIRECT_MODE 0
46840   assert( isDirectMode==0 );
46841   UNUSED_PARAMETER(isDirectMode);
46842 #else
46843 # define DIRECT_MODE isDirectMode
46844 #endif
46845 
46846   if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
46847     PgHdr *pPgHdr;                /* Reference to page 1 */
46848 
46849     assert( !pPager->tempFile && isOpen(pPager->fd) );
46850 
46851     /* Open page 1 of the file for writing. */
46852     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
46853     assert( pPgHdr==0 || rc==SQLITE_OK );
46854 
46855     /* If page one was fetched successfully, and this function is not
46856     ** operating in direct-mode, make page 1 writable.  When not in
46857     ** direct mode, page 1 is always held in cache and hence the PagerGet()
46858     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
46859     */
46860     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
46861       rc = sqlite3PagerWrite(pPgHdr);
46862     }
46863 
46864     if( rc==SQLITE_OK ){
46865       /* Actually do the update of the change counter */
46866       pager_write_changecounter(pPgHdr);
46867 
46868       /* If running in direct mode, write the contents of page 1 to the file. */
46869       if( DIRECT_MODE ){
46870         const void *zBuf;
46871         assert( pPager->dbFileSize>0 );
46872         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
46873         if( rc==SQLITE_OK ){
46874           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
46875           pPager->aStat[PAGER_STAT_WRITE]++;
46876         }
46877         if( rc==SQLITE_OK ){
46878           /* Update the pager's copy of the change-counter. Otherwise, the
46879           ** next time a read transaction is opened the cache will be
46880           ** flushed (as the change-counter values will not match).  */
46881           const void *pCopy = (const void *)&((const char *)zBuf)[24];
46882           memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
46883           pPager->changeCountDone = 1;
46884         }
46885       }else{
46886         pPager->changeCountDone = 1;
46887       }
46888     }
46889 
46890     /* Release the page reference. */
46891     sqlite3PagerUnref(pPgHdr);
46892   }
46893   return rc;
46894 }
46895 
46896 /*
46897 ** Sync the database file to disk. This is a no-op for in-memory databases
46898 ** or pages with the Pager.noSync flag set.
46899 **
46900 ** If successful, or if called on a pager for which it is a no-op, this
46901 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
46902 */
46903 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
46904   int rc = SQLITE_OK;
46905 
46906   if( isOpen(pPager->fd) ){
46907     void *pArg = (void*)zMaster;
46908     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
46909     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
46910   }
46911   if( rc==SQLITE_OK && !pPager->noSync ){
46912     assert( !MEMDB );
46913     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
46914   }
46915   return rc;
46916 }
46917 
46918 /*
46919 ** This function may only be called while a write-transaction is active in
46920 ** rollback. If the connection is in WAL mode, this call is a no-op.
46921 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
46922 ** the database file, an attempt is made to obtain one.
46923 **
46924 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
46925 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
46926 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
46927 ** returned.
46928 */
46929 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
46930   int rc = SQLITE_OK;
46931   assert( pPager->eState==PAGER_WRITER_CACHEMOD
46932        || pPager->eState==PAGER_WRITER_DBMOD
46933        || pPager->eState==PAGER_WRITER_LOCKED
46934   );
46935   assert( assert_pager_state(pPager) );
46936   if( 0==pagerUseWal(pPager) ){
46937     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
46938   }
46939   return rc;
46940 }
46941 
46942 /*
46943 ** Sync the database file for the pager pPager. zMaster points to the name
46944 ** of a master journal file that should be written into the individual
46945 ** journal file. zMaster may be NULL, which is interpreted as no master
46946 ** journal (a single database transaction).
46947 **
46948 ** This routine ensures that:
46949 **
46950 **   * The database file change-counter is updated,
46951 **   * the journal is synced (unless the atomic-write optimization is used),
46952 **   * all dirty pages are written to the database file,
46953 **   * the database file is truncated (if required), and
46954 **   * the database file synced.
46955 **
46956 ** The only thing that remains to commit the transaction is to finalize
46957 ** (delete, truncate or zero the first part of) the journal file (or
46958 ** delete the master journal file if specified).
46959 **
46960 ** Note that if zMaster==NULL, this does not overwrite a previous value
46961 ** passed to an sqlite3PagerCommitPhaseOne() call.
46962 **
46963 ** If the final parameter - noSync - is true, then the database file itself
46964 ** is not synced. The caller must call sqlite3PagerSync() directly to
46965 ** sync the database file before calling CommitPhaseTwo() to delete the
46966 ** journal file in this case.
46967 */
46968 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
46969   Pager *pPager,                  /* Pager object */
46970   const char *zMaster,            /* If not NULL, the master journal name */
46971   int noSync                      /* True to omit the xSync on the db file */
46972 ){
46973   int rc = SQLITE_OK;             /* Return code */
46974 
46975   assert( pPager->eState==PAGER_WRITER_LOCKED
46976        || pPager->eState==PAGER_WRITER_CACHEMOD
46977        || pPager->eState==PAGER_WRITER_DBMOD
46978        || pPager->eState==PAGER_ERROR
46979   );
46980   assert( assert_pager_state(pPager) );
46981 
46982   /* If a prior error occurred, report that error again. */
46983   if( NEVER(pPager->errCode) ) return pPager->errCode;
46984 
46985   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
46986       pPager->zFilename, zMaster, pPager->dbSize));
46987 
46988   /* If no database changes have been made, return early. */
46989   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
46990 
46991   if( MEMDB ){
46992     /* If this is an in-memory db, or no pages have been written to, or this
46993     ** function has already been called, it is mostly a no-op.  However, any
46994     ** backup in progress needs to be restarted.
46995     */
46996     sqlite3BackupRestart(pPager->pBackup);
46997   }else{
46998     if( pagerUseWal(pPager) ){
46999       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
47000       PgHdr *pPageOne = 0;
47001       if( pList==0 ){
47002         /* Must have at least one page for the WAL commit flag.
47003         ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
47004         rc = sqlite3PagerGet(pPager, 1, &pPageOne);
47005         pList = pPageOne;
47006         pList->pDirty = 0;
47007       }
47008       assert( rc==SQLITE_OK );
47009       if( ALWAYS(pList) ){
47010         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
47011       }
47012       sqlite3PagerUnref(pPageOne);
47013       if( rc==SQLITE_OK ){
47014         sqlite3PcacheCleanAll(pPager->pPCache);
47015       }
47016     }else{
47017       /* The following block updates the change-counter. Exactly how it
47018       ** does this depends on whether or not the atomic-update optimization
47019       ** was enabled at compile time, and if this transaction meets the
47020       ** runtime criteria to use the operation:
47021       **
47022       **    * The file-system supports the atomic-write property for
47023       **      blocks of size page-size, and
47024       **    * This commit is not part of a multi-file transaction, and
47025       **    * Exactly one page has been modified and store in the journal file.
47026       **
47027       ** If the optimization was not enabled at compile time, then the
47028       ** pager_incr_changecounter() function is called to update the change
47029       ** counter in 'indirect-mode'. If the optimization is compiled in but
47030       ** is not applicable to this transaction, call sqlite3JournalCreate()
47031       ** to make sure the journal file has actually been created, then call
47032       ** pager_incr_changecounter() to update the change-counter in indirect
47033       ** mode.
47034       **
47035       ** Otherwise, if the optimization is both enabled and applicable,
47036       ** then call pager_incr_changecounter() to update the change-counter
47037       ** in 'direct' mode. In this case the journal file will never be
47038       ** created for this transaction.
47039       */
47040   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
47041       PgHdr *pPg;
47042       assert( isOpen(pPager->jfd)
47043            || pPager->journalMode==PAGER_JOURNALMODE_OFF
47044            || pPager->journalMode==PAGER_JOURNALMODE_WAL
47045       );
47046       if( !zMaster && isOpen(pPager->jfd)
47047        && pPager->journalOff==jrnlBufferSize(pPager)
47048        && pPager->dbSize>=pPager->dbOrigSize
47049        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
47050       ){
47051         /* Update the db file change counter via the direct-write method. The
47052         ** following call will modify the in-memory representation of page 1
47053         ** to include the updated change counter and then write page 1
47054         ** directly to the database file. Because of the atomic-write
47055         ** property of the host file-system, this is safe.
47056         */
47057         rc = pager_incr_changecounter(pPager, 1);
47058       }else{
47059         rc = sqlite3JournalCreate(pPager->jfd);
47060         if( rc==SQLITE_OK ){
47061           rc = pager_incr_changecounter(pPager, 0);
47062         }
47063       }
47064   #else
47065       rc = pager_incr_changecounter(pPager, 0);
47066   #endif
47067       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
47068 
47069       /* Write the master journal name into the journal file. If a master
47070       ** journal file name has already been written to the journal file,
47071       ** or if zMaster is NULL (no master journal), then this call is a no-op.
47072       */
47073       rc = writeMasterJournal(pPager, zMaster);
47074       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
47075 
47076       /* Sync the journal file and write all dirty pages to the database.
47077       ** If the atomic-update optimization is being used, this sync will not
47078       ** create the journal file or perform any real IO.
47079       **
47080       ** Because the change-counter page was just modified, unless the
47081       ** atomic-update optimization is used it is almost certain that the
47082       ** journal requires a sync here. However, in locking_mode=exclusive
47083       ** on a system under memory pressure it is just possible that this is
47084       ** not the case. In this case it is likely enough that the redundant
47085       ** xSync() call will be changed to a no-op by the OS anyhow.
47086       */
47087       rc = syncJournal(pPager, 0);
47088       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
47089 
47090       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
47091       if( rc!=SQLITE_OK ){
47092         assert( rc!=SQLITE_IOERR_BLOCKED );
47093         goto commit_phase_one_exit;
47094       }
47095       sqlite3PcacheCleanAll(pPager->pPCache);
47096 
47097       /* If the file on disk is smaller than the database image, use
47098       ** pager_truncate to grow the file here. This can happen if the database
47099       ** image was extended as part of the current transaction and then the
47100       ** last page in the db image moved to the free-list. In this case the
47101       ** last page is never written out to disk, leaving the database file
47102       ** undersized. Fix this now if it is the case.  */
47103       if( pPager->dbSize>pPager->dbFileSize ){
47104         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
47105         assert( pPager->eState==PAGER_WRITER_DBMOD );
47106         rc = pager_truncate(pPager, nNew);
47107         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
47108       }
47109 
47110       /* Finally, sync the database file. */
47111       if( !noSync ){
47112         rc = sqlite3PagerSync(pPager, zMaster);
47113       }
47114       IOTRACE(("DBSYNC %p\n", pPager))
47115     }
47116   }
47117 
47118 commit_phase_one_exit:
47119   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
47120     pPager->eState = PAGER_WRITER_FINISHED;
47121   }
47122   return rc;
47123 }
47124 
47125 
47126 /*
47127 ** When this function is called, the database file has been completely
47128 ** updated to reflect the changes made by the current transaction and
47129 ** synced to disk. The journal file still exists in the file-system
47130 ** though, and if a failure occurs at this point it will eventually
47131 ** be used as a hot-journal and the current transaction rolled back.
47132 **
47133 ** This function finalizes the journal file, either by deleting,
47134 ** truncating or partially zeroing it, so that it cannot be used
47135 ** for hot-journal rollback. Once this is done the transaction is
47136 ** irrevocably committed.
47137 **
47138 ** If an error occurs, an IO error code is returned and the pager
47139 ** moves into the error state. Otherwise, SQLITE_OK is returned.
47140 */
47141 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
47142   int rc = SQLITE_OK;                  /* Return code */
47143 
47144   /* This routine should not be called if a prior error has occurred.
47145   ** But if (due to a coding error elsewhere in the system) it does get
47146   ** called, just return the same error code without doing anything. */
47147   if( NEVER(pPager->errCode) ) return pPager->errCode;
47148 
47149   assert( pPager->eState==PAGER_WRITER_LOCKED
47150        || pPager->eState==PAGER_WRITER_FINISHED
47151        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
47152   );
47153   assert( assert_pager_state(pPager) );
47154 
47155   /* An optimization. If the database was not actually modified during
47156   ** this transaction, the pager is running in exclusive-mode and is
47157   ** using persistent journals, then this function is a no-op.
47158   **
47159   ** The start of the journal file currently contains a single journal
47160   ** header with the nRec field set to 0. If such a journal is used as
47161   ** a hot-journal during hot-journal rollback, 0 changes will be made
47162   ** to the database file. So there is no need to zero the journal
47163   ** header. Since the pager is in exclusive mode, there is no need
47164   ** to drop any locks either.
47165   */
47166   if( pPager->eState==PAGER_WRITER_LOCKED
47167    && pPager->exclusiveMode
47168    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
47169   ){
47170     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
47171     pPager->eState = PAGER_READER;
47172     return SQLITE_OK;
47173   }
47174 
47175   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
47176   rc = pager_end_transaction(pPager, pPager->setMaster, 1);
47177   return pager_error(pPager, rc);
47178 }
47179 
47180 /*
47181 ** If a write transaction is open, then all changes made within the
47182 ** transaction are reverted and the current write-transaction is closed.
47183 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
47184 ** state if an error occurs.
47185 **
47186 ** If the pager is already in PAGER_ERROR state when this function is called,
47187 ** it returns Pager.errCode immediately. No work is performed in this case.
47188 **
47189 ** Otherwise, in rollback mode, this function performs two functions:
47190 **
47191 **   1) It rolls back the journal file, restoring all database file and
47192 **      in-memory cache pages to the state they were in when the transaction
47193 **      was opened, and
47194 **
47195 **   2) It finalizes the journal file, so that it is not used for hot
47196 **      rollback at any point in the future.
47197 **
47198 ** Finalization of the journal file (task 2) is only performed if the
47199 ** rollback is successful.
47200 **
47201 ** In WAL mode, all cache-entries containing data modified within the
47202 ** current transaction are either expelled from the cache or reverted to
47203 ** their pre-transaction state by re-reading data from the database or
47204 ** WAL files. The WAL transaction is then closed.
47205 */
47206 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
47207   int rc = SQLITE_OK;                  /* Return code */
47208   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
47209 
47210   /* PagerRollback() is a no-op if called in READER or OPEN state. If
47211   ** the pager is already in the ERROR state, the rollback is not
47212   ** attempted here. Instead, the error code is returned to the caller.
47213   */
47214   assert( assert_pager_state(pPager) );
47215   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
47216   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
47217 
47218   if( pagerUseWal(pPager) ){
47219     int rc2;
47220     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
47221     rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
47222     if( rc==SQLITE_OK ) rc = rc2;
47223   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
47224     int eState = pPager->eState;
47225     rc = pager_end_transaction(pPager, 0, 0);
47226     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
47227       /* This can happen using journal_mode=off. Move the pager to the error
47228       ** state to indicate that the contents of the cache may not be trusted.
47229       ** Any active readers will get SQLITE_ABORT.
47230       */
47231       pPager->errCode = SQLITE_ABORT;
47232       pPager->eState = PAGER_ERROR;
47233       return rc;
47234     }
47235   }else{
47236     rc = pager_playback(pPager, 0);
47237   }
47238 
47239   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
47240   assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
47241           || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
47242           || rc==SQLITE_CANTOPEN
47243   );
47244 
47245   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
47246   ** cache. So call pager_error() on the way out to make any error persistent.
47247   */
47248   return pager_error(pPager, rc);
47249 }
47250 
47251 /*
47252 ** Return TRUE if the database file is opened read-only.  Return FALSE
47253 ** if the database is (in theory) writable.
47254 */
47255 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
47256   return pPager->readOnly;
47257 }
47258 
47259 /*
47260 ** Return the number of references to the pager.
47261 */
47262 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
47263   return sqlite3PcacheRefCount(pPager->pPCache);
47264 }
47265 
47266 /*
47267 ** Return the approximate number of bytes of memory currently
47268 ** used by the pager and its associated cache.
47269 */
47270 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
47271   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
47272                                      + 5*sizeof(void*);
47273   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
47274            + sqlite3MallocSize(pPager)
47275            + pPager->pageSize;
47276 }
47277 
47278 /*
47279 ** Return the number of references to the specified page.
47280 */
47281 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
47282   return sqlite3PcachePageRefcount(pPage);
47283 }
47284 
47285 #ifdef SQLITE_TEST
47286 /*
47287 ** This routine is used for testing and analysis only.
47288 */
47289 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
47290   static int a[11];
47291   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
47292   a[1] = sqlite3PcachePagecount(pPager->pPCache);
47293   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
47294   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
47295   a[4] = pPager->eState;
47296   a[5] = pPager->errCode;
47297   a[6] = pPager->aStat[PAGER_STAT_HIT];
47298   a[7] = pPager->aStat[PAGER_STAT_MISS];
47299   a[8] = 0;  /* Used to be pPager->nOvfl */
47300   a[9] = pPager->nRead;
47301   a[10] = pPager->aStat[PAGER_STAT_WRITE];
47302   return a;
47303 }
47304 #endif
47305 
47306 /*
47307 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
47308 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
47309 ** current cache hit or miss count, according to the value of eStat. If the
47310 ** reset parameter is non-zero, the cache hit or miss count is zeroed before
47311 ** returning.
47312 */
47313 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
47314 
47315   assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
47316        || eStat==SQLITE_DBSTATUS_CACHE_MISS
47317        || eStat==SQLITE_DBSTATUS_CACHE_WRITE
47318   );
47319 
47320   assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
47321   assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
47322   assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
47323 
47324   *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
47325   if( reset ){
47326     pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
47327   }
47328 }
47329 
47330 /*
47331 ** Return true if this is an in-memory pager.
47332 */
47333 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
47334   return MEMDB;
47335 }
47336 
47337 /*
47338 ** Check that there are at least nSavepoint savepoints open. If there are
47339 ** currently less than nSavepoints open, then open one or more savepoints
47340 ** to make up the difference. If the number of savepoints is already
47341 ** equal to nSavepoint, then this function is a no-op.
47342 **
47343 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
47344 ** occurs while opening the sub-journal file, then an IO error code is
47345 ** returned. Otherwise, SQLITE_OK.
47346 */
47347 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
47348   int rc = SQLITE_OK;                       /* Return code */
47349   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
47350 
47351   assert( pPager->eState>=PAGER_WRITER_LOCKED );
47352   assert( assert_pager_state(pPager) );
47353 
47354   if( nSavepoint>nCurrent && pPager->useJournal ){
47355     int ii;                                 /* Iterator variable */
47356     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
47357 
47358     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
47359     ** if the allocation fails. Otherwise, zero the new portion in case a
47360     ** malloc failure occurs while populating it in the for(...) loop below.
47361     */
47362     aNew = (PagerSavepoint *)sqlite3Realloc(
47363         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
47364     );
47365     if( !aNew ){
47366       return SQLITE_NOMEM;
47367     }
47368     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
47369     pPager->aSavepoint = aNew;
47370 
47371     /* Populate the PagerSavepoint structures just allocated. */
47372     for(ii=nCurrent; ii<nSavepoint; ii++){
47373       aNew[ii].nOrig = pPager->dbSize;
47374       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
47375         aNew[ii].iOffset = pPager->journalOff;
47376       }else{
47377         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
47378       }
47379       aNew[ii].iSubRec = pPager->nSubRec;
47380       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
47381       if( !aNew[ii].pInSavepoint ){
47382         return SQLITE_NOMEM;
47383       }
47384       if( pagerUseWal(pPager) ){
47385         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
47386       }
47387       pPager->nSavepoint = ii+1;
47388     }
47389     assert( pPager->nSavepoint==nSavepoint );
47390     assertTruncateConstraint(pPager);
47391   }
47392 
47393   return rc;
47394 }
47395 
47396 /*
47397 ** This function is called to rollback or release (commit) a savepoint.
47398 ** The savepoint to release or rollback need not be the most recently
47399 ** created savepoint.
47400 **
47401 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
47402 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
47403 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
47404 ** that have occurred since the specified savepoint was created.
47405 **
47406 ** The savepoint to rollback or release is identified by parameter
47407 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
47408 ** (the first created). A value of (Pager.nSavepoint-1) means operate
47409 ** on the most recently created savepoint. If iSavepoint is greater than
47410 ** (Pager.nSavepoint-1), then this function is a no-op.
47411 **
47412 ** If a negative value is passed to this function, then the current
47413 ** transaction is rolled back. This is different to calling
47414 ** sqlite3PagerRollback() because this function does not terminate
47415 ** the transaction or unlock the database, it just restores the
47416 ** contents of the database to its original state.
47417 **
47418 ** In any case, all savepoints with an index greater than iSavepoint
47419 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
47420 ** then savepoint iSavepoint is also destroyed.
47421 **
47422 ** This function may return SQLITE_NOMEM if a memory allocation fails,
47423 ** or an IO error code if an IO error occurs while rolling back a
47424 ** savepoint. If no errors occur, SQLITE_OK is returned.
47425 */
47426 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
47427   int rc = pPager->errCode;       /* Return code */
47428 
47429   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
47430   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
47431 
47432   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
47433     int ii;            /* Iterator variable */
47434     int nNew;          /* Number of remaining savepoints after this op. */
47435 
47436     /* Figure out how many savepoints will still be active after this
47437     ** operation. Store this value in nNew. Then free resources associated
47438     ** with any savepoints that are destroyed by this operation.
47439     */
47440     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
47441     for(ii=nNew; ii<pPager->nSavepoint; ii++){
47442       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
47443     }
47444     pPager->nSavepoint = nNew;
47445 
47446     /* If this is a release of the outermost savepoint, truncate
47447     ** the sub-journal to zero bytes in size. */
47448     if( op==SAVEPOINT_RELEASE ){
47449       if( nNew==0 && isOpen(pPager->sjfd) ){
47450         /* Only truncate if it is an in-memory sub-journal. */
47451         if( sqlite3IsMemJournal(pPager->sjfd) ){
47452           rc = sqlite3OsTruncate(pPager->sjfd, 0);
47453           assert( rc==SQLITE_OK );
47454         }
47455         pPager->nSubRec = 0;
47456       }
47457     }
47458     /* Else this is a rollback operation, playback the specified savepoint.
47459     ** If this is a temp-file, it is possible that the journal file has
47460     ** not yet been opened. In this case there have been no changes to
47461     ** the database file, so the playback operation can be skipped.
47462     */
47463     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
47464       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
47465       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
47466       assert(rc!=SQLITE_DONE);
47467     }
47468   }
47469 
47470   return rc;
47471 }
47472 
47473 /*
47474 ** Return the full pathname of the database file.
47475 **
47476 ** Except, if the pager is in-memory only, then return an empty string if
47477 ** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
47478 ** used to report the filename to the user, for compatibility with legacy
47479 ** behavior.  But when the Btree needs to know the filename for matching to
47480 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
47481 ** participate in shared-cache.
47482 */
47483 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
47484   return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
47485 }
47486 
47487 /*
47488 ** Return the VFS structure for the pager.
47489 */
47490 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
47491   return pPager->pVfs;
47492 }
47493 
47494 /*
47495 ** Return the file handle for the database file associated
47496 ** with the pager.  This might return NULL if the file has
47497 ** not yet been opened.
47498 */
47499 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
47500   return pPager->fd;
47501 }
47502 
47503 /*
47504 ** Return the full pathname of the journal file.
47505 */
47506 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
47507   return pPager->zJournal;
47508 }
47509 
47510 /*
47511 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
47512 ** if fsync()s are executed normally.
47513 */
47514 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
47515   return pPager->noSync;
47516 }
47517 
47518 #ifdef SQLITE_HAS_CODEC
47519 /*
47520 ** Set or retrieve the codec for this pager
47521 */
47522 SQLITE_PRIVATE void sqlite3PagerSetCodec(
47523   Pager *pPager,
47524   void *(*xCodec)(void*,void*,Pgno,int),
47525   void (*xCodecSizeChng)(void*,int,int),
47526   void (*xCodecFree)(void*),
47527   void *pCodec
47528 ){
47529   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
47530   pPager->xCodec = pPager->memDb ? 0 : xCodec;
47531   pPager->xCodecSizeChng = xCodecSizeChng;
47532   pPager->xCodecFree = xCodecFree;
47533   pPager->pCodec = pCodec;
47534   pagerReportSize(pPager);
47535 }
47536 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
47537   return pPager->pCodec;
47538 }
47539 
47540 /*
47541 ** This function is called by the wal module when writing page content
47542 ** into the log file.
47543 **
47544 ** This function returns a pointer to a buffer containing the encrypted
47545 ** page content. If a malloc fails, this function may return NULL.
47546 */
47547 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
47548   void *aData = 0;
47549   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
47550   return aData;
47551 }
47552 
47553 /*
47554 ** Return the current pager state
47555 */
47556 SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
47557   return pPager->eState;
47558 }
47559 #endif /* SQLITE_HAS_CODEC */
47560 
47561 #ifndef SQLITE_OMIT_AUTOVACUUM
47562 /*
47563 ** Move the page pPg to location pgno in the file.
47564 **
47565 ** There must be no references to the page previously located at
47566 ** pgno (which we call pPgOld) though that page is allowed to be
47567 ** in cache.  If the page previously located at pgno is not already
47568 ** in the rollback journal, it is not put there by by this routine.
47569 **
47570 ** References to the page pPg remain valid. Updating any
47571 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
47572 ** allocated along with the page) is the responsibility of the caller.
47573 **
47574 ** A transaction must be active when this routine is called. It used to be
47575 ** required that a statement transaction was not active, but this restriction
47576 ** has been removed (CREATE INDEX needs to move a page when a statement
47577 ** transaction is active).
47578 **
47579 ** If the fourth argument, isCommit, is non-zero, then this page is being
47580 ** moved as part of a database reorganization just before the transaction
47581 ** is being committed. In this case, it is guaranteed that the database page
47582 ** pPg refers to will not be written to again within this transaction.
47583 **
47584 ** This function may return SQLITE_NOMEM or an IO error code if an error
47585 ** occurs. Otherwise, it returns SQLITE_OK.
47586 */
47587 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
47588   PgHdr *pPgOld;               /* The page being overwritten. */
47589   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
47590   int rc;                      /* Return code */
47591   Pgno origPgno;               /* The original page number */
47592 
47593   assert( pPg->nRef>0 );
47594   assert( pPager->eState==PAGER_WRITER_CACHEMOD
47595        || pPager->eState==PAGER_WRITER_DBMOD
47596   );
47597   assert( assert_pager_state(pPager) );
47598 
47599   /* In order to be able to rollback, an in-memory database must journal
47600   ** the page we are moving from.
47601   */
47602   if( MEMDB ){
47603     rc = sqlite3PagerWrite(pPg);
47604     if( rc ) return rc;
47605   }
47606 
47607   /* If the page being moved is dirty and has not been saved by the latest
47608   ** savepoint, then save the current contents of the page into the
47609   ** sub-journal now. This is required to handle the following scenario:
47610   **
47611   **   BEGIN;
47612   **     <journal page X, then modify it in memory>
47613   **     SAVEPOINT one;
47614   **       <Move page X to location Y>
47615   **     ROLLBACK TO one;
47616   **
47617   ** If page X were not written to the sub-journal here, it would not
47618   ** be possible to restore its contents when the "ROLLBACK TO one"
47619   ** statement were is processed.
47620   **
47621   ** subjournalPage() may need to allocate space to store pPg->pgno into
47622   ** one or more savepoint bitvecs. This is the reason this function
47623   ** may return SQLITE_NOMEM.
47624   */
47625   if( pPg->flags&PGHDR_DIRTY
47626    && subjRequiresPage(pPg)
47627    && SQLITE_OK!=(rc = subjournalPage(pPg))
47628   ){
47629     return rc;
47630   }
47631 
47632   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
47633       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
47634   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
47635 
47636   /* If the journal needs to be sync()ed before page pPg->pgno can
47637   ** be written to, store pPg->pgno in local variable needSyncPgno.
47638   **
47639   ** If the isCommit flag is set, there is no need to remember that
47640   ** the journal needs to be sync()ed before database page pPg->pgno
47641   ** can be written to. The caller has already promised not to write to it.
47642   */
47643   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
47644     needSyncPgno = pPg->pgno;
47645     assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
47646             pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
47647     assert( pPg->flags&PGHDR_DIRTY );
47648   }
47649 
47650   /* If the cache contains a page with page-number pgno, remove it
47651   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
47652   ** page pgno before the 'move' operation, it needs to be retained
47653   ** for the page moved there.
47654   */
47655   pPg->flags &= ~PGHDR_NEED_SYNC;
47656   pPgOld = sqlite3PagerLookup(pPager, pgno);
47657   assert( !pPgOld || pPgOld->nRef==1 );
47658   if( pPgOld ){
47659     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
47660     if( MEMDB ){
47661       /* Do not discard pages from an in-memory database since we might
47662       ** need to rollback later.  Just move the page out of the way. */
47663       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
47664     }else{
47665       sqlite3PcacheDrop(pPgOld);
47666     }
47667   }
47668 
47669   origPgno = pPg->pgno;
47670   sqlite3PcacheMove(pPg, pgno);
47671   sqlite3PcacheMakeDirty(pPg);
47672 
47673   /* For an in-memory database, make sure the original page continues
47674   ** to exist, in case the transaction needs to roll back.  Use pPgOld
47675   ** as the original page since it has already been allocated.
47676   */
47677   if( MEMDB ){
47678     assert( pPgOld );
47679     sqlite3PcacheMove(pPgOld, origPgno);
47680     sqlite3PagerUnrefNotNull(pPgOld);
47681   }
47682 
47683   if( needSyncPgno ){
47684     /* If needSyncPgno is non-zero, then the journal file needs to be
47685     ** sync()ed before any data is written to database file page needSyncPgno.
47686     ** Currently, no such page exists in the page-cache and the
47687     ** "is journaled" bitvec flag has been set. This needs to be remedied by
47688     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
47689     ** flag.
47690     **
47691     ** If the attempt to load the page into the page-cache fails, (due
47692     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
47693     ** array. Otherwise, if the page is loaded and written again in
47694     ** this transaction, it may be written to the database file before
47695     ** it is synced into the journal file. This way, it may end up in
47696     ** the journal file twice, but that is not a problem.
47697     */
47698     PgHdr *pPgHdr;
47699     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
47700     if( rc!=SQLITE_OK ){
47701       if( needSyncPgno<=pPager->dbOrigSize ){
47702         assert( pPager->pTmpSpace!=0 );
47703         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
47704       }
47705       return rc;
47706     }
47707     pPgHdr->flags |= PGHDR_NEED_SYNC;
47708     sqlite3PcacheMakeDirty(pPgHdr);
47709     sqlite3PagerUnrefNotNull(pPgHdr);
47710   }
47711 
47712   return SQLITE_OK;
47713 }
47714 #endif
47715 
47716 /*
47717 ** Return a pointer to the data for the specified page.
47718 */
47719 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
47720   assert( pPg->nRef>0 || pPg->pPager->memDb );
47721   return pPg->pData;
47722 }
47723 
47724 /*
47725 ** Return a pointer to the Pager.nExtra bytes of "extra" space
47726 ** allocated along with the specified page.
47727 */
47728 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
47729   return pPg->pExtra;
47730 }
47731 
47732 /*
47733 ** Get/set the locking-mode for this pager. Parameter eMode must be one
47734 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
47735 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
47736 ** the locking-mode is set to the value specified.
47737 **
47738 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
47739 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
47740 ** locking-mode.
47741 */
47742 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
47743   assert( eMode==PAGER_LOCKINGMODE_QUERY
47744             || eMode==PAGER_LOCKINGMODE_NORMAL
47745             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
47746   assert( PAGER_LOCKINGMODE_QUERY<0 );
47747   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
47748   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
47749   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
47750     pPager->exclusiveMode = (u8)eMode;
47751   }
47752   return (int)pPager->exclusiveMode;
47753 }
47754 
47755 /*
47756 ** Set the journal-mode for this pager. Parameter eMode must be one of:
47757 **
47758 **    PAGER_JOURNALMODE_DELETE
47759 **    PAGER_JOURNALMODE_TRUNCATE
47760 **    PAGER_JOURNALMODE_PERSIST
47761 **    PAGER_JOURNALMODE_OFF
47762 **    PAGER_JOURNALMODE_MEMORY
47763 **    PAGER_JOURNALMODE_WAL
47764 **
47765 ** The journalmode is set to the value specified if the change is allowed.
47766 ** The change may be disallowed for the following reasons:
47767 **
47768 **   *  An in-memory database can only have its journal_mode set to _OFF
47769 **      or _MEMORY.
47770 **
47771 **   *  Temporary databases cannot have _WAL journalmode.
47772 **
47773 ** The returned indicate the current (possibly updated) journal-mode.
47774 */
47775 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
47776   u8 eOld = pPager->journalMode;    /* Prior journalmode */
47777 
47778 #ifdef SQLITE_DEBUG
47779   /* The print_pager_state() routine is intended to be used by the debugger
47780   ** only.  We invoke it once here to suppress a compiler warning. */
47781   print_pager_state(pPager);
47782 #endif
47783 
47784 
47785   /* The eMode parameter is always valid */
47786   assert(      eMode==PAGER_JOURNALMODE_DELETE
47787             || eMode==PAGER_JOURNALMODE_TRUNCATE
47788             || eMode==PAGER_JOURNALMODE_PERSIST
47789             || eMode==PAGER_JOURNALMODE_OFF
47790             || eMode==PAGER_JOURNALMODE_WAL
47791             || eMode==PAGER_JOURNALMODE_MEMORY );
47792 
47793   /* This routine is only called from the OP_JournalMode opcode, and
47794   ** the logic there will never allow a temporary file to be changed
47795   ** to WAL mode.
47796   */
47797   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
47798 
47799   /* Do allow the journalmode of an in-memory database to be set to
47800   ** anything other than MEMORY or OFF
47801   */
47802   if( MEMDB ){
47803     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
47804     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
47805       eMode = eOld;
47806     }
47807   }
47808 
47809   if( eMode!=eOld ){
47810 
47811     /* Change the journal mode. */
47812     assert( pPager->eState!=PAGER_ERROR );
47813     pPager->journalMode = (u8)eMode;
47814 
47815     /* When transistioning from TRUNCATE or PERSIST to any other journal
47816     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
47817     ** delete the journal file.
47818     */
47819     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
47820     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
47821     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
47822     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
47823     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
47824     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
47825 
47826     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
47827     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
47828 
47829       /* In this case we would like to delete the journal file. If it is
47830       ** not possible, then that is not a problem. Deleting the journal file
47831       ** here is an optimization only.
47832       **
47833       ** Before deleting the journal file, obtain a RESERVED lock on the
47834       ** database file. This ensures that the journal file is not deleted
47835       ** while it is in use by some other client.
47836       */
47837       sqlite3OsClose(pPager->jfd);
47838       if( pPager->eLock>=RESERVED_LOCK ){
47839         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
47840       }else{
47841         int rc = SQLITE_OK;
47842         int state = pPager->eState;
47843         assert( state==PAGER_OPEN || state==PAGER_READER );
47844         if( state==PAGER_OPEN ){
47845           rc = sqlite3PagerSharedLock(pPager);
47846         }
47847         if( pPager->eState==PAGER_READER ){
47848           assert( rc==SQLITE_OK );
47849           rc = pagerLockDb(pPager, RESERVED_LOCK);
47850         }
47851         if( rc==SQLITE_OK ){
47852           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
47853         }
47854         if( rc==SQLITE_OK && state==PAGER_READER ){
47855           pagerUnlockDb(pPager, SHARED_LOCK);
47856         }else if( state==PAGER_OPEN ){
47857           pager_unlock(pPager);
47858         }
47859         assert( state==pPager->eState );
47860       }
47861     }
47862   }
47863 
47864   /* Return the new journal mode */
47865   return (int)pPager->journalMode;
47866 }
47867 
47868 /*
47869 ** Return the current journal mode.
47870 */
47871 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
47872   return (int)pPager->journalMode;
47873 }
47874 
47875 /*
47876 ** Return TRUE if the pager is in a state where it is OK to change the
47877 ** journalmode.  Journalmode changes can only happen when the database
47878 ** is unmodified.
47879 */
47880 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
47881   assert( assert_pager_state(pPager) );
47882   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
47883   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
47884   return 1;
47885 }
47886 
47887 /*
47888 ** Get/set the size-limit used for persistent journal files.
47889 **
47890 ** Setting the size limit to -1 means no limit is enforced.
47891 ** An attempt to set a limit smaller than -1 is a no-op.
47892 */
47893 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
47894   if( iLimit>=-1 ){
47895     pPager->journalSizeLimit = iLimit;
47896     sqlite3WalLimit(pPager->pWal, iLimit);
47897   }
47898   return pPager->journalSizeLimit;
47899 }
47900 
47901 /*
47902 ** Return a pointer to the pPager->pBackup variable. The backup module
47903 ** in backup.c maintains the content of this variable. This module
47904 ** uses it opaquely as an argument to sqlite3BackupRestart() and
47905 ** sqlite3BackupUpdate() only.
47906 */
47907 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
47908   return &pPager->pBackup;
47909 }
47910 
47911 #ifndef SQLITE_OMIT_VACUUM
47912 /*
47913 ** Unless this is an in-memory or temporary database, clear the pager cache.
47914 */
47915 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
47916   if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
47917 }
47918 #endif
47919 
47920 #ifndef SQLITE_OMIT_WAL
47921 /*
47922 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
47923 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
47924 ** or wal_blocking_checkpoint() API functions.
47925 **
47926 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
47927 */
47928 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
47929   int rc = SQLITE_OK;
47930   if( pPager->pWal ){
47931     rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
47932         pPager->xBusyHandler, pPager->pBusyHandlerArg,
47933         pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
47934         pnLog, pnCkpt
47935     );
47936   }
47937   return rc;
47938 }
47939 
47940 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
47941   return sqlite3WalCallback(pPager->pWal);
47942 }
47943 
47944 /*
47945 ** Return true if the underlying VFS for the given pager supports the
47946 ** primitives necessary for write-ahead logging.
47947 */
47948 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
47949   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
47950   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
47951 }
47952 
47953 /*
47954 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
47955 ** is obtained instead, immediately release it.
47956 */
47957 static int pagerExclusiveLock(Pager *pPager){
47958   int rc;                         /* Return code */
47959 
47960   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
47961   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
47962   if( rc!=SQLITE_OK ){
47963     /* If the attempt to grab the exclusive lock failed, release the
47964     ** pending lock that may have been obtained instead.  */
47965     pagerUnlockDb(pPager, SHARED_LOCK);
47966   }
47967 
47968   return rc;
47969 }
47970 
47971 /*
47972 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
47973 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
47974 ** lock on the database file and use heap-memory to store the wal-index
47975 ** in. Otherwise, use the normal shared-memory.
47976 */
47977 static int pagerOpenWal(Pager *pPager){
47978   int rc = SQLITE_OK;
47979 
47980   assert( pPager->pWal==0 && pPager->tempFile==0 );
47981   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
47982 
47983   /* If the pager is already in exclusive-mode, the WAL module will use
47984   ** heap-memory for the wal-index instead of the VFS shared-memory
47985   ** implementation. Take the exclusive lock now, before opening the WAL
47986   ** file, to make sure this is safe.
47987   */
47988   if( pPager->exclusiveMode ){
47989     rc = pagerExclusiveLock(pPager);
47990   }
47991 
47992   /* Open the connection to the log file. If this operation fails,
47993   ** (e.g. due to malloc() failure), return an error code.
47994   */
47995   if( rc==SQLITE_OK ){
47996     rc = sqlite3WalOpen(pPager->pVfs,
47997         pPager->fd, pPager->zWal, pPager->exclusiveMode,
47998         pPager->journalSizeLimit, &pPager->pWal
47999     );
48000   }
48001   pagerFixMaplimit(pPager);
48002 
48003   return rc;
48004 }
48005 
48006 
48007 /*
48008 ** The caller must be holding a SHARED lock on the database file to call
48009 ** this function.
48010 **
48011 ** If the pager passed as the first argument is open on a real database
48012 ** file (not a temp file or an in-memory database), and the WAL file
48013 ** is not already open, make an attempt to open it now. If successful,
48014 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
48015 ** not support the xShmXXX() methods, return an error code. *pbOpen is
48016 ** not modified in either case.
48017 **
48018 ** If the pager is open on a temp-file (or in-memory database), or if
48019 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
48020 ** without doing anything.
48021 */
48022 SQLITE_PRIVATE int sqlite3PagerOpenWal(
48023   Pager *pPager,                  /* Pager object */
48024   int *pbOpen                     /* OUT: Set to true if call is a no-op */
48025 ){
48026   int rc = SQLITE_OK;             /* Return code */
48027 
48028   assert( assert_pager_state(pPager) );
48029   assert( pPager->eState==PAGER_OPEN   || pbOpen );
48030   assert( pPager->eState==PAGER_READER || !pbOpen );
48031   assert( pbOpen==0 || *pbOpen==0 );
48032   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
48033 
48034   if( !pPager->tempFile && !pPager->pWal ){
48035     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
48036 
48037     /* Close any rollback journal previously open */
48038     sqlite3OsClose(pPager->jfd);
48039 
48040     rc = pagerOpenWal(pPager);
48041     if( rc==SQLITE_OK ){
48042       pPager->journalMode = PAGER_JOURNALMODE_WAL;
48043       pPager->eState = PAGER_OPEN;
48044     }
48045   }else{
48046     *pbOpen = 1;
48047   }
48048 
48049   return rc;
48050 }
48051 
48052 /*
48053 ** This function is called to close the connection to the log file prior
48054 ** to switching from WAL to rollback mode.
48055 **
48056 ** Before closing the log file, this function attempts to take an
48057 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
48058 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
48059 ** If successful, the EXCLUSIVE lock is not released before returning.
48060 */
48061 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
48062   int rc = SQLITE_OK;
48063 
48064   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
48065 
48066   /* If the log file is not already open, but does exist in the file-system,
48067   ** it may need to be checkpointed before the connection can switch to
48068   ** rollback mode. Open it now so this can happen.
48069   */
48070   if( !pPager->pWal ){
48071     int logexists = 0;
48072     rc = pagerLockDb(pPager, SHARED_LOCK);
48073     if( rc==SQLITE_OK ){
48074       rc = sqlite3OsAccess(
48075           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
48076       );
48077     }
48078     if( rc==SQLITE_OK && logexists ){
48079       rc = pagerOpenWal(pPager);
48080     }
48081   }
48082 
48083   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
48084   ** the database file, the log and log-summary files will be deleted.
48085   */
48086   if( rc==SQLITE_OK && pPager->pWal ){
48087     rc = pagerExclusiveLock(pPager);
48088     if( rc==SQLITE_OK ){
48089       rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
48090                            pPager->pageSize, (u8*)pPager->pTmpSpace);
48091       pPager->pWal = 0;
48092       pagerFixMaplimit(pPager);
48093     }
48094   }
48095   return rc;
48096 }
48097 
48098 #endif /* !SQLITE_OMIT_WAL */
48099 
48100 #ifdef SQLITE_ENABLE_ZIPVFS
48101 /*
48102 ** A read-lock must be held on the pager when this function is called. If
48103 ** the pager is in WAL mode and the WAL file currently contains one or more
48104 ** frames, return the size in bytes of the page images stored within the
48105 ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
48106 ** is empty, return 0.
48107 */
48108 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
48109   assert( pPager->eState>=PAGER_READER );
48110   return sqlite3WalFramesize(pPager->pWal);
48111 }
48112 #endif
48113 
48114 #endif /* SQLITE_OMIT_DISKIO */
48115 
48116 /************** End of pager.c ***********************************************/
48117 /************** Begin file wal.c *********************************************/
48118 /*
48119 ** 2010 February 1
48120 **
48121 ** The author disclaims copyright to this source code.  In place of
48122 ** a legal notice, here is a blessing:
48123 **
48124 **    May you do good and not evil.
48125 **    May you find forgiveness for yourself and forgive others.
48126 **    May you share freely, never taking more than you give.
48127 **
48128 *************************************************************************
48129 **
48130 ** This file contains the implementation of a write-ahead log (WAL) used in
48131 ** "journal_mode=WAL" mode.
48132 **
48133 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
48134 **
48135 ** A WAL file consists of a header followed by zero or more "frames".
48136 ** Each frame records the revised content of a single page from the
48137 ** database file.  All changes to the database are recorded by writing
48138 ** frames into the WAL.  Transactions commit when a frame is written that
48139 ** contains a commit marker.  A single WAL can and usually does record
48140 ** multiple transactions.  Periodically, the content of the WAL is
48141 ** transferred back into the database file in an operation called a
48142 ** "checkpoint".
48143 **
48144 ** A single WAL file can be used multiple times.  In other words, the
48145 ** WAL can fill up with frames and then be checkpointed and then new
48146 ** frames can overwrite the old ones.  A WAL always grows from beginning
48147 ** toward the end.  Checksums and counters attached to each frame are
48148 ** used to determine which frames within the WAL are valid and which
48149 ** are leftovers from prior checkpoints.
48150 **
48151 ** The WAL header is 32 bytes in size and consists of the following eight
48152 ** big-endian 32-bit unsigned integer values:
48153 **
48154 **     0: Magic number.  0x377f0682 or 0x377f0683
48155 **     4: File format version.  Currently 3007000
48156 **     8: Database page size.  Example: 1024
48157 **    12: Checkpoint sequence number
48158 **    16: Salt-1, random integer incremented with each checkpoint
48159 **    20: Salt-2, a different random integer changing with each ckpt
48160 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
48161 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
48162 **
48163 ** Immediately following the wal-header are zero or more frames. Each
48164 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
48165 ** of page data. The frame-header is six big-endian 32-bit unsigned
48166 ** integer values, as follows:
48167 **
48168 **     0: Page number.
48169 **     4: For commit records, the size of the database image in pages
48170 **        after the commit. For all other records, zero.
48171 **     8: Salt-1 (copied from the header)
48172 **    12: Salt-2 (copied from the header)
48173 **    16: Checksum-1.
48174 **    20: Checksum-2.
48175 **
48176 ** A frame is considered valid if and only if the following conditions are
48177 ** true:
48178 **
48179 **    (1) The salt-1 and salt-2 values in the frame-header match
48180 **        salt values in the wal-header
48181 **
48182 **    (2) The checksum values in the final 8 bytes of the frame-header
48183 **        exactly match the checksum computed consecutively on the
48184 **        WAL header and the first 8 bytes and the content of all frames
48185 **        up to and including the current frame.
48186 **
48187 ** The checksum is computed using 32-bit big-endian integers if the
48188 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
48189 ** is computed using little-endian if the magic number is 0x377f0682.
48190 ** The checksum values are always stored in the frame header in a
48191 ** big-endian format regardless of which byte order is used to compute
48192 ** the checksum.  The checksum is computed by interpreting the input as
48193 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
48194 ** algorithm used for the checksum is as follows:
48195 **
48196 **   for i from 0 to n-1 step 2:
48197 **     s0 += x[i] + s1;
48198 **     s1 += x[i+1] + s0;
48199 **   endfor
48200 **
48201 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
48202 ** in reverse order (the largest fibonacci weight occurs on the first element
48203 ** of the sequence being summed.)  The s1 value spans all 32-bit
48204 ** terms of the sequence whereas s0 omits the final term.
48205 **
48206 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
48207 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
48208 ** The VFS.xSync operations serve as write barriers - all writes launched
48209 ** before the xSync must complete before any write that launches after the
48210 ** xSync begins.
48211 **
48212 ** After each checkpoint, the salt-1 value is incremented and the salt-2
48213 ** value is randomized.  This prevents old and new frames in the WAL from
48214 ** being considered valid at the same time and being checkpointing together
48215 ** following a crash.
48216 **
48217 ** READER ALGORITHM
48218 **
48219 ** To read a page from the database (call it page number P), a reader
48220 ** first checks the WAL to see if it contains page P.  If so, then the
48221 ** last valid instance of page P that is a followed by a commit frame
48222 ** or is a commit frame itself becomes the value read.  If the WAL
48223 ** contains no copies of page P that are valid and which are a commit
48224 ** frame or are followed by a commit frame, then page P is read from
48225 ** the database file.
48226 **
48227 ** To start a read transaction, the reader records the index of the last
48228 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
48229 ** for all subsequent read operations.  New transactions can be appended
48230 ** to the WAL, but as long as the reader uses its original mxFrame value
48231 ** and ignores the newly appended content, it will see a consistent snapshot
48232 ** of the database from a single point in time.  This technique allows
48233 ** multiple concurrent readers to view different versions of the database
48234 ** content simultaneously.
48235 **
48236 ** The reader algorithm in the previous paragraphs works correctly, but
48237 ** because frames for page P can appear anywhere within the WAL, the
48238 ** reader has to scan the entire WAL looking for page P frames.  If the
48239 ** WAL is large (multiple megabytes is typical) that scan can be slow,
48240 ** and read performance suffers.  To overcome this problem, a separate
48241 ** data structure called the wal-index is maintained to expedite the
48242 ** search for frames of a particular page.
48243 **
48244 ** WAL-INDEX FORMAT
48245 **
48246 ** Conceptually, the wal-index is shared memory, though VFS implementations
48247 ** might choose to implement the wal-index using a mmapped file.  Because
48248 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
48249 ** on a network filesystem.  All users of the database must be able to
48250 ** share memory.
48251 **
48252 ** The wal-index is transient.  After a crash, the wal-index can (and should
48253 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
48254 ** to either truncate or zero the header of the wal-index when the last
48255 ** connection to it closes.  Because the wal-index is transient, it can
48256 ** use an architecture-specific format; it does not have to be cross-platform.
48257 ** Hence, unlike the database and WAL file formats which store all values
48258 ** as big endian, the wal-index can store multi-byte values in the native
48259 ** byte order of the host computer.
48260 **
48261 ** The purpose of the wal-index is to answer this question quickly:  Given
48262 ** a page number P and a maximum frame index M, return the index of the
48263 ** last frame in the wal before frame M for page P in the WAL, or return
48264 ** NULL if there are no frames for page P in the WAL prior to M.
48265 **
48266 ** The wal-index consists of a header region, followed by an one or
48267 ** more index blocks.
48268 **
48269 ** The wal-index header contains the total number of frames within the WAL
48270 ** in the mxFrame field.
48271 **
48272 ** Each index block except for the first contains information on
48273 ** HASHTABLE_NPAGE frames. The first index block contains information on
48274 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
48275 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
48276 ** first index block are the same size as all other index blocks in the
48277 ** wal-index.
48278 **
48279 ** Each index block contains two sections, a page-mapping that contains the
48280 ** database page number associated with each wal frame, and a hash-table
48281 ** that allows readers to query an index block for a specific page number.
48282 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
48283 ** for the first index block) 32-bit page numbers. The first entry in the
48284 ** first index-block contains the database page number corresponding to the
48285 ** first frame in the WAL file. The first entry in the second index block
48286 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
48287 ** the log, and so on.
48288 **
48289 ** The last index block in a wal-index usually contains less than the full
48290 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
48291 ** depending on the contents of the WAL file. This does not change the
48292 ** allocated size of the page-mapping array - the page-mapping array merely
48293 ** contains unused entries.
48294 **
48295 ** Even without using the hash table, the last frame for page P
48296 ** can be found by scanning the page-mapping sections of each index block
48297 ** starting with the last index block and moving toward the first, and
48298 ** within each index block, starting at the end and moving toward the
48299 ** beginning.  The first entry that equals P corresponds to the frame
48300 ** holding the content for that page.
48301 **
48302 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
48303 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
48304 ** hash table for each page number in the mapping section, so the hash
48305 ** table is never more than half full.  The expected number of collisions
48306 ** prior to finding a match is 1.  Each entry of the hash table is an
48307 ** 1-based index of an entry in the mapping section of the same
48308 ** index block.   Let K be the 1-based index of the largest entry in
48309 ** the mapping section.  (For index blocks other than the last, K will
48310 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
48311 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
48312 ** contain a value of 0.
48313 **
48314 ** To look for page P in the hash table, first compute a hash iKey on
48315 ** P as follows:
48316 **
48317 **      iKey = (P * 383) % HASHTABLE_NSLOT
48318 **
48319 ** Then start scanning entries of the hash table, starting with iKey
48320 ** (wrapping around to the beginning when the end of the hash table is
48321 ** reached) until an unused hash slot is found. Let the first unused slot
48322 ** be at index iUnused.  (iUnused might be less than iKey if there was
48323 ** wrap-around.) Because the hash table is never more than half full,
48324 ** the search is guaranteed to eventually hit an unused entry.  Let
48325 ** iMax be the value between iKey and iUnused, closest to iUnused,
48326 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
48327 ** no hash slot such that aHash[i]==p) then page P is not in the
48328 ** current index block.  Otherwise the iMax-th mapping entry of the
48329 ** current index block corresponds to the last entry that references
48330 ** page P.
48331 **
48332 ** A hash search begins with the last index block and moves toward the
48333 ** first index block, looking for entries corresponding to page P.  On
48334 ** average, only two or three slots in each index block need to be
48335 ** examined in order to either find the last entry for page P, or to
48336 ** establish that no such entry exists in the block.  Each index block
48337 ** holds over 4000 entries.  So two or three index blocks are sufficient
48338 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
48339 ** comparisons (on average) suffice to either locate a frame in the
48340 ** WAL or to establish that the frame does not exist in the WAL.  This
48341 ** is much faster than scanning the entire 10MB WAL.
48342 **
48343 ** Note that entries are added in order of increasing K.  Hence, one
48344 ** reader might be using some value K0 and a second reader that started
48345 ** at a later time (after additional transactions were added to the WAL
48346 ** and to the wal-index) might be using a different value K1, where K1>K0.
48347 ** Both readers can use the same hash table and mapping section to get
48348 ** the correct result.  There may be entries in the hash table with
48349 ** K>K0 but to the first reader, those entries will appear to be unused
48350 ** slots in the hash table and so the first reader will get an answer as
48351 ** if no values greater than K0 had ever been inserted into the hash table
48352 ** in the first place - which is what reader one wants.  Meanwhile, the
48353 ** second reader using K1 will see additional values that were inserted
48354 ** later, which is exactly what reader two wants.
48355 **
48356 ** When a rollback occurs, the value of K is decreased. Hash table entries
48357 ** that correspond to frames greater than the new K value are removed
48358 ** from the hash table at this point.
48359 */
48360 #ifndef SQLITE_OMIT_WAL
48361 
48362 
48363 /*
48364 ** Trace output macros
48365 */
48366 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
48367 SQLITE_PRIVATE int sqlite3WalTrace = 0;
48368 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
48369 #else
48370 # define WALTRACE(X)
48371 #endif
48372 
48373 /*
48374 ** The maximum (and only) versions of the wal and wal-index formats
48375 ** that may be interpreted by this version of SQLite.
48376 **
48377 ** If a client begins recovering a WAL file and finds that (a) the checksum
48378 ** values in the wal-header are correct and (b) the version field is not
48379 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
48380 **
48381 ** Similarly, if a client successfully reads a wal-index header (i.e. the
48382 ** checksum test is successful) and finds that the version field is not
48383 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
48384 ** returns SQLITE_CANTOPEN.
48385 */
48386 #define WAL_MAX_VERSION      3007000
48387 #define WALINDEX_MAX_VERSION 3007000
48388 
48389 /*
48390 ** Indices of various locking bytes.   WAL_NREADER is the number
48391 ** of available reader locks and should be at least 3.
48392 */
48393 #define WAL_WRITE_LOCK         0
48394 #define WAL_ALL_BUT_WRITE      1
48395 #define WAL_CKPT_LOCK          1
48396 #define WAL_RECOVER_LOCK       2
48397 #define WAL_READ_LOCK(I)       (3+(I))
48398 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
48399 
48400 
48401 /* Object declarations */
48402 typedef struct WalIndexHdr WalIndexHdr;
48403 typedef struct WalIterator WalIterator;
48404 typedef struct WalCkptInfo WalCkptInfo;
48405 
48406 
48407 /*
48408 ** The following object holds a copy of the wal-index header content.
48409 **
48410 ** The actual header in the wal-index consists of two copies of this
48411 ** object.
48412 **
48413 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
48414 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
48415 ** added in 3.7.1 when support for 64K pages was added.
48416 */
48417 struct WalIndexHdr {
48418   u32 iVersion;                   /* Wal-index version */
48419   u32 unused;                     /* Unused (padding) field */
48420   u32 iChange;                    /* Counter incremented each transaction */
48421   u8 isInit;                      /* 1 when initialized */
48422   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
48423   u16 szPage;                     /* Database page size in bytes. 1==64K */
48424   u32 mxFrame;                    /* Index of last valid frame in the WAL */
48425   u32 nPage;                      /* Size of database in pages */
48426   u32 aFrameCksum[2];             /* Checksum of last frame in log */
48427   u32 aSalt[2];                   /* Two salt values copied from WAL header */
48428   u32 aCksum[2];                  /* Checksum over all prior fields */
48429 };
48430 
48431 /*
48432 ** A copy of the following object occurs in the wal-index immediately
48433 ** following the second copy of the WalIndexHdr.  This object stores
48434 ** information used by checkpoint.
48435 **
48436 ** nBackfill is the number of frames in the WAL that have been written
48437 ** back into the database. (We call the act of moving content from WAL to
48438 ** database "backfilling".)  The nBackfill number is never greater than
48439 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
48440 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
48441 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
48442 ** mxFrame back to zero when the WAL is reset.
48443 **
48444 ** There is one entry in aReadMark[] for each reader lock.  If a reader
48445 ** holds read-lock K, then the value in aReadMark[K] is no greater than
48446 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
48447 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is
48448 ** a special case; its value is never used and it exists as a place-holder
48449 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
48450 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
48451 ** directly from the database.
48452 **
48453 ** The value of aReadMark[K] may only be changed by a thread that
48454 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
48455 ** aReadMark[K] cannot changed while there is a reader is using that mark
48456 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
48457 **
48458 ** The checkpointer may only transfer frames from WAL to database where
48459 ** the frame numbers are less than or equal to every aReadMark[] that is
48460 ** in use (that is, every aReadMark[j] for which there is a corresponding
48461 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
48462 ** largest value and will increase an unused aReadMark[] to mxFrame if there
48463 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
48464 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
48465 ** in the WAL has been backfilled into the database) then new readers
48466 ** will choose aReadMark[0] which has value 0 and hence such reader will
48467 ** get all their all content directly from the database file and ignore
48468 ** the WAL.
48469 **
48470 ** Writers normally append new frames to the end of the WAL.  However,
48471 ** if nBackfill equals mxFrame (meaning that all WAL content has been
48472 ** written back into the database) and if no readers are using the WAL
48473 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
48474 ** the writer will first "reset" the WAL back to the beginning and start
48475 ** writing new content beginning at frame 1.
48476 **
48477 ** We assume that 32-bit loads are atomic and so no locks are needed in
48478 ** order to read from any aReadMark[] entries.
48479 */
48480 struct WalCkptInfo {
48481   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
48482   u32 aReadMark[WAL_NREADER];     /* Reader marks */
48483 };
48484 #define READMARK_NOT_USED  0xffffffff
48485 
48486 
48487 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
48488 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
48489 ** only support mandatory file-locks, we do not read or write data
48490 ** from the region of the file on which locks are applied.
48491 */
48492 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
48493 #define WALINDEX_LOCK_RESERVED 16
48494 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
48495 
48496 /* Size of header before each frame in wal */
48497 #define WAL_FRAME_HDRSIZE 24
48498 
48499 /* Size of write ahead log header, including checksum. */
48500 /* #define WAL_HDRSIZE 24 */
48501 #define WAL_HDRSIZE 32
48502 
48503 /* WAL magic value. Either this value, or the same value with the least
48504 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
48505 ** big-endian format in the first 4 bytes of a WAL file.
48506 **
48507 ** If the LSB is set, then the checksums for each frame within the WAL
48508 ** file are calculated by treating all data as an array of 32-bit
48509 ** big-endian words. Otherwise, they are calculated by interpreting
48510 ** all data as 32-bit little-endian words.
48511 */
48512 #define WAL_MAGIC 0x377f0682
48513 
48514 /*
48515 ** Return the offset of frame iFrame in the write-ahead log file,
48516 ** assuming a database page size of szPage bytes. The offset returned
48517 ** is to the start of the write-ahead log frame-header.
48518 */
48519 #define walFrameOffset(iFrame, szPage) (                               \
48520   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
48521 )
48522 
48523 /*
48524 ** An open write-ahead log file is represented by an instance of the
48525 ** following object.
48526 */
48527 struct Wal {
48528   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
48529   sqlite3_file *pDbFd;       /* File handle for the database file */
48530   sqlite3_file *pWalFd;      /* File handle for WAL file */
48531   u32 iCallback;             /* Value to pass to log callback (or 0) */
48532   i64 mxWalSize;             /* Truncate WAL to this size upon reset */
48533   int nWiData;               /* Size of array apWiData */
48534   int szFirstBlock;          /* Size of first block written to WAL file */
48535   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
48536   u32 szPage;                /* Database page size */
48537   i16 readLock;              /* Which read lock is being held.  -1 for none */
48538   u8 syncFlags;              /* Flags to use to sync header writes */
48539   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
48540   u8 writeLock;              /* True if in a write transaction */
48541   u8 ckptLock;               /* True if holding a checkpoint lock */
48542   u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
48543   u8 truncateOnCommit;       /* True to truncate WAL file on commit */
48544   u8 syncHeader;             /* Fsync the WAL header if true */
48545   u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
48546   WalIndexHdr hdr;           /* Wal-index header for current transaction */
48547   const char *zWalName;      /* Name of WAL file */
48548   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
48549 #ifdef SQLITE_DEBUG
48550   u8 lockError;              /* True if a locking error has occurred */
48551 #endif
48552 };
48553 
48554 /*
48555 ** Candidate values for Wal.exclusiveMode.
48556 */
48557 #define WAL_NORMAL_MODE     0
48558 #define WAL_EXCLUSIVE_MODE  1
48559 #define WAL_HEAPMEMORY_MODE 2
48560 
48561 /*
48562 ** Possible values for WAL.readOnly
48563 */
48564 #define WAL_RDWR        0    /* Normal read/write connection */
48565 #define WAL_RDONLY      1    /* The WAL file is readonly */
48566 #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
48567 
48568 /*
48569 ** Each page of the wal-index mapping contains a hash-table made up of
48570 ** an array of HASHTABLE_NSLOT elements of the following type.
48571 */
48572 typedef u16 ht_slot;
48573 
48574 /*
48575 ** This structure is used to implement an iterator that loops through
48576 ** all frames in the WAL in database page order. Where two or more frames
48577 ** correspond to the same database page, the iterator visits only the
48578 ** frame most recently written to the WAL (in other words, the frame with
48579 ** the largest index).
48580 **
48581 ** The internals of this structure are only accessed by:
48582 **
48583 **   walIteratorInit() - Create a new iterator,
48584 **   walIteratorNext() - Step an iterator,
48585 **   walIteratorFree() - Free an iterator.
48586 **
48587 ** This functionality is used by the checkpoint code (see walCheckpoint()).
48588 */
48589 struct WalIterator {
48590   int iPrior;                     /* Last result returned from the iterator */
48591   int nSegment;                   /* Number of entries in aSegment[] */
48592   struct WalSegment {
48593     int iNext;                    /* Next slot in aIndex[] not yet returned */
48594     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
48595     u32 *aPgno;                   /* Array of page numbers. */
48596     int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
48597     int iZero;                    /* Frame number associated with aPgno[0] */
48598   } aSegment[1];                  /* One for every 32KB page in the wal-index */
48599 };
48600 
48601 /*
48602 ** Define the parameters of the hash tables in the wal-index file. There
48603 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
48604 ** wal-index.
48605 **
48606 ** Changing any of these constants will alter the wal-index format and
48607 ** create incompatibilities.
48608 */
48609 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
48610 #define HASHTABLE_HASH_1     383                  /* Should be prime */
48611 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
48612 
48613 /*
48614 ** The block of page numbers associated with the first hash-table in a
48615 ** wal-index is smaller than usual. This is so that there is a complete
48616 ** hash-table on each aligned 32KB page of the wal-index.
48617 */
48618 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
48619 
48620 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
48621 #define WALINDEX_PGSZ   (                                         \
48622     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
48623 )
48624 
48625 /*
48626 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
48627 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
48628 ** numbered from zero.
48629 **
48630 ** If this call is successful, *ppPage is set to point to the wal-index
48631 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
48632 ** then an SQLite error code is returned and *ppPage is set to 0.
48633 */
48634 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
48635   int rc = SQLITE_OK;
48636 
48637   /* Enlarge the pWal->apWiData[] array if required */
48638   if( pWal->nWiData<=iPage ){
48639     int nByte = sizeof(u32*)*(iPage+1);
48640     volatile u32 **apNew;
48641     apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
48642     if( !apNew ){
48643       *ppPage = 0;
48644       return SQLITE_NOMEM;
48645     }
48646     memset((void*)&apNew[pWal->nWiData], 0,
48647            sizeof(u32*)*(iPage+1-pWal->nWiData));
48648     pWal->apWiData = apNew;
48649     pWal->nWiData = iPage+1;
48650   }
48651 
48652   /* Request a pointer to the required page from the VFS */
48653   if( pWal->apWiData[iPage]==0 ){
48654     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
48655       pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
48656       if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
48657     }else{
48658       rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
48659           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
48660       );
48661       if( rc==SQLITE_READONLY ){
48662         pWal->readOnly |= WAL_SHM_RDONLY;
48663         rc = SQLITE_OK;
48664       }
48665     }
48666   }
48667 
48668   *ppPage = pWal->apWiData[iPage];
48669   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
48670   return rc;
48671 }
48672 
48673 /*
48674 ** Return a pointer to the WalCkptInfo structure in the wal-index.
48675 */
48676 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
48677   assert( pWal->nWiData>0 && pWal->apWiData[0] );
48678   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
48679 }
48680 
48681 /*
48682 ** Return a pointer to the WalIndexHdr structure in the wal-index.
48683 */
48684 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
48685   assert( pWal->nWiData>0 && pWal->apWiData[0] );
48686   return (volatile WalIndexHdr*)pWal->apWiData[0];
48687 }
48688 
48689 /*
48690 ** The argument to this macro must be of type u32. On a little-endian
48691 ** architecture, it returns the u32 value that results from interpreting
48692 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
48693 ** returns the value that would be produced by interpreting the 4 bytes
48694 ** of the input value as a little-endian integer.
48695 */
48696 #define BYTESWAP32(x) ( \
48697     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
48698   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
48699 )
48700 
48701 /*
48702 ** Generate or extend an 8 byte checksum based on the data in
48703 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
48704 ** initial values of 0 and 0 if aIn==NULL).
48705 **
48706 ** The checksum is written back into aOut[] before returning.
48707 **
48708 ** nByte must be a positive multiple of 8.
48709 */
48710 static void walChecksumBytes(
48711   int nativeCksum, /* True for native byte-order, false for non-native */
48712   u8 *a,           /* Content to be checksummed */
48713   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
48714   const u32 *aIn,  /* Initial checksum value input */
48715   u32 *aOut        /* OUT: Final checksum value output */
48716 ){
48717   u32 s1, s2;
48718   u32 *aData = (u32 *)a;
48719   u32 *aEnd = (u32 *)&a[nByte];
48720 
48721   if( aIn ){
48722     s1 = aIn[0];
48723     s2 = aIn[1];
48724   }else{
48725     s1 = s2 = 0;
48726   }
48727 
48728   assert( nByte>=8 );
48729   assert( (nByte&0x00000007)==0 );
48730 
48731   if( nativeCksum ){
48732     do {
48733       s1 += *aData++ + s2;
48734       s2 += *aData++ + s1;
48735     }while( aData<aEnd );
48736   }else{
48737     do {
48738       s1 += BYTESWAP32(aData[0]) + s2;
48739       s2 += BYTESWAP32(aData[1]) + s1;
48740       aData += 2;
48741     }while( aData<aEnd );
48742   }
48743 
48744   aOut[0] = s1;
48745   aOut[1] = s2;
48746 }
48747 
48748 static void walShmBarrier(Wal *pWal){
48749   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
48750     sqlite3OsShmBarrier(pWal->pDbFd);
48751   }
48752 }
48753 
48754 /*
48755 ** Write the header information in pWal->hdr into the wal-index.
48756 **
48757 ** The checksum on pWal->hdr is updated before it is written.
48758 */
48759 static void walIndexWriteHdr(Wal *pWal){
48760   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
48761   const int nCksum = offsetof(WalIndexHdr, aCksum);
48762 
48763   assert( pWal->writeLock );
48764   pWal->hdr.isInit = 1;
48765   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
48766   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
48767   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
48768   walShmBarrier(pWal);
48769   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
48770 }
48771 
48772 /*
48773 ** This function encodes a single frame header and writes it to a buffer
48774 ** supplied by the caller. A frame-header is made up of a series of
48775 ** 4-byte big-endian integers, as follows:
48776 **
48777 **     0: Page number.
48778 **     4: For commit records, the size of the database image in pages
48779 **        after the commit. For all other records, zero.
48780 **     8: Salt-1 (copied from the wal-header)
48781 **    12: Salt-2 (copied from the wal-header)
48782 **    16: Checksum-1.
48783 **    20: Checksum-2.
48784 */
48785 static void walEncodeFrame(
48786   Wal *pWal,                      /* The write-ahead log */
48787   u32 iPage,                      /* Database page number for frame */
48788   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
48789   u8 *aData,                      /* Pointer to page data */
48790   u8 *aFrame                      /* OUT: Write encoded frame here */
48791 ){
48792   int nativeCksum;                /* True for native byte-order checksums */
48793   u32 *aCksum = pWal->hdr.aFrameCksum;
48794   assert( WAL_FRAME_HDRSIZE==24 );
48795   sqlite3Put4byte(&aFrame[0], iPage);
48796   sqlite3Put4byte(&aFrame[4], nTruncate);
48797   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
48798 
48799   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
48800   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
48801   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
48802 
48803   sqlite3Put4byte(&aFrame[16], aCksum[0]);
48804   sqlite3Put4byte(&aFrame[20], aCksum[1]);
48805 }
48806 
48807 /*
48808 ** Check to see if the frame with header in aFrame[] and content
48809 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
48810 ** *pnTruncate and return true.  Return if the frame is not valid.
48811 */
48812 static int walDecodeFrame(
48813   Wal *pWal,                      /* The write-ahead log */
48814   u32 *piPage,                    /* OUT: Database page number for frame */
48815   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
48816   u8 *aData,                      /* Pointer to page data (for checksum) */
48817   u8 *aFrame                      /* Frame data */
48818 ){
48819   int nativeCksum;                /* True for native byte-order checksums */
48820   u32 *aCksum = pWal->hdr.aFrameCksum;
48821   u32 pgno;                       /* Page number of the frame */
48822   assert( WAL_FRAME_HDRSIZE==24 );
48823 
48824   /* A frame is only valid if the salt values in the frame-header
48825   ** match the salt values in the wal-header.
48826   */
48827   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
48828     return 0;
48829   }
48830 
48831   /* A frame is only valid if the page number is creater than zero.
48832   */
48833   pgno = sqlite3Get4byte(&aFrame[0]);
48834   if( pgno==0 ){
48835     return 0;
48836   }
48837 
48838   /* A frame is only valid if a checksum of the WAL header,
48839   ** all prior frams, the first 16 bytes of this frame-header,
48840   ** and the frame-data matches the checksum in the last 8
48841   ** bytes of this frame-header.
48842   */
48843   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
48844   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
48845   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
48846   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
48847    || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
48848   ){
48849     /* Checksum failed. */
48850     return 0;
48851   }
48852 
48853   /* If we reach this point, the frame is valid.  Return the page number
48854   ** and the new database size.
48855   */
48856   *piPage = pgno;
48857   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
48858   return 1;
48859 }
48860 
48861 
48862 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
48863 /*
48864 ** Names of locks.  This routine is used to provide debugging output and is not
48865 ** a part of an ordinary build.
48866 */
48867 static const char *walLockName(int lockIdx){
48868   if( lockIdx==WAL_WRITE_LOCK ){
48869     return "WRITE-LOCK";
48870   }else if( lockIdx==WAL_CKPT_LOCK ){
48871     return "CKPT-LOCK";
48872   }else if( lockIdx==WAL_RECOVER_LOCK ){
48873     return "RECOVER-LOCK";
48874   }else{
48875     static char zName[15];
48876     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
48877                      lockIdx-WAL_READ_LOCK(0));
48878     return zName;
48879   }
48880 }
48881 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
48882 
48883 
48884 /*
48885 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
48886 ** A lock cannot be moved directly between shared and exclusive - it must go
48887 ** through the unlocked state first.
48888 **
48889 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
48890 */
48891 static int walLockShared(Wal *pWal, int lockIdx){
48892   int rc;
48893   if( pWal->exclusiveMode ) return SQLITE_OK;
48894   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
48895                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
48896   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
48897             walLockName(lockIdx), rc ? "failed" : "ok"));
48898   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
48899   return rc;
48900 }
48901 static void walUnlockShared(Wal *pWal, int lockIdx){
48902   if( pWal->exclusiveMode ) return;
48903   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
48904                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
48905   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
48906 }
48907 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
48908   int rc;
48909   if( pWal->exclusiveMode ) return SQLITE_OK;
48910   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
48911                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
48912   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
48913             walLockName(lockIdx), n, rc ? "failed" : "ok"));
48914   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
48915   return rc;
48916 }
48917 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
48918   if( pWal->exclusiveMode ) return;
48919   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
48920                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
48921   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
48922              walLockName(lockIdx), n));
48923 }
48924 
48925 /*
48926 ** Compute a hash on a page number.  The resulting hash value must land
48927 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
48928 ** the hash to the next value in the event of a collision.
48929 */
48930 static int walHash(u32 iPage){
48931   assert( iPage>0 );
48932   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
48933   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
48934 }
48935 static int walNextHash(int iPriorHash){
48936   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
48937 }
48938 
48939 /*
48940 ** Return pointers to the hash table and page number array stored on
48941 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
48942 ** numbered starting from 0.
48943 **
48944 ** Set output variable *paHash to point to the start of the hash table
48945 ** in the wal-index file. Set *piZero to one less than the frame
48946 ** number of the first frame indexed by this hash table. If a
48947 ** slot in the hash table is set to N, it refers to frame number
48948 ** (*piZero+N) in the log.
48949 **
48950 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
48951 ** first frame indexed by the hash table, frame (*piZero+1).
48952 */
48953 static int walHashGet(
48954   Wal *pWal,                      /* WAL handle */
48955   int iHash,                      /* Find the iHash'th table */
48956   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
48957   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
48958   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
48959 ){
48960   int rc;                         /* Return code */
48961   volatile u32 *aPgno;
48962 
48963   rc = walIndexPage(pWal, iHash, &aPgno);
48964   assert( rc==SQLITE_OK || iHash>0 );
48965 
48966   if( rc==SQLITE_OK ){
48967     u32 iZero;
48968     volatile ht_slot *aHash;
48969 
48970     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
48971     if( iHash==0 ){
48972       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
48973       iZero = 0;
48974     }else{
48975       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
48976     }
48977 
48978     *paPgno = &aPgno[-1];
48979     *paHash = aHash;
48980     *piZero = iZero;
48981   }
48982   return rc;
48983 }
48984 
48985 /*
48986 ** Return the number of the wal-index page that contains the hash-table
48987 ** and page-number array that contain entries corresponding to WAL frame
48988 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
48989 ** are numbered starting from 0.
48990 */
48991 static int walFramePage(u32 iFrame){
48992   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
48993   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
48994        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
48995        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
48996        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
48997        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
48998   );
48999   return iHash;
49000 }
49001 
49002 /*
49003 ** Return the page number associated with frame iFrame in this WAL.
49004 */
49005 static u32 walFramePgno(Wal *pWal, u32 iFrame){
49006   int iHash = walFramePage(iFrame);
49007   if( iHash==0 ){
49008     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
49009   }
49010   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
49011 }
49012 
49013 /*
49014 ** Remove entries from the hash table that point to WAL slots greater
49015 ** than pWal->hdr.mxFrame.
49016 **
49017 ** This function is called whenever pWal->hdr.mxFrame is decreased due
49018 ** to a rollback or savepoint.
49019 **
49020 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
49021 ** updated.  Any later hash tables will be automatically cleared when
49022 ** pWal->hdr.mxFrame advances to the point where those hash tables are
49023 ** actually needed.
49024 */
49025 static void walCleanupHash(Wal *pWal){
49026   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
49027   volatile u32 *aPgno = 0;        /* Page number array for hash table */
49028   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
49029   int iLimit = 0;                 /* Zero values greater than this */
49030   int nByte;                      /* Number of bytes to zero in aPgno[] */
49031   int i;                          /* Used to iterate through aHash[] */
49032 
49033   assert( pWal->writeLock );
49034   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
49035   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
49036   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
49037 
49038   if( pWal->hdr.mxFrame==0 ) return;
49039 
49040   /* Obtain pointers to the hash-table and page-number array containing
49041   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
49042   ** that the page said hash-table and array reside on is already mapped.
49043   */
49044   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
49045   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
49046   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
49047 
49048   /* Zero all hash-table entries that correspond to frame numbers greater
49049   ** than pWal->hdr.mxFrame.
49050   */
49051   iLimit = pWal->hdr.mxFrame - iZero;
49052   assert( iLimit>0 );
49053   for(i=0; i<HASHTABLE_NSLOT; i++){
49054     if( aHash[i]>iLimit ){
49055       aHash[i] = 0;
49056     }
49057   }
49058 
49059   /* Zero the entries in the aPgno array that correspond to frames with
49060   ** frame numbers greater than pWal->hdr.mxFrame.
49061   */
49062   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
49063   memset((void *)&aPgno[iLimit+1], 0, nByte);
49064 
49065 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
49066   /* Verify that the every entry in the mapping region is still reachable
49067   ** via the hash table even after the cleanup.
49068   */
49069   if( iLimit ){
49070     int i;           /* Loop counter */
49071     int iKey;        /* Hash key */
49072     for(i=1; i<=iLimit; i++){
49073       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
49074         if( aHash[iKey]==i ) break;
49075       }
49076       assert( aHash[iKey]==i );
49077     }
49078   }
49079 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
49080 }
49081 
49082 
49083 /*
49084 ** Set an entry in the wal-index that will map database page number
49085 ** pPage into WAL frame iFrame.
49086 */
49087 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
49088   int rc;                         /* Return code */
49089   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
49090   volatile u32 *aPgno = 0;        /* Page number array */
49091   volatile ht_slot *aHash = 0;    /* Hash table */
49092 
49093   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
49094 
49095   /* Assuming the wal-index file was successfully mapped, populate the
49096   ** page number array and hash table entry.
49097   */
49098   if( rc==SQLITE_OK ){
49099     int iKey;                     /* Hash table key */
49100     int idx;                      /* Value to write to hash-table slot */
49101     int nCollide;                 /* Number of hash collisions */
49102 
49103     idx = iFrame - iZero;
49104     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
49105 
49106     /* If this is the first entry to be added to this hash-table, zero the
49107     ** entire hash table and aPgno[] array before proceeding.
49108     */
49109     if( idx==1 ){
49110       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
49111       memset((void*)&aPgno[1], 0, nByte);
49112     }
49113 
49114     /* If the entry in aPgno[] is already set, then the previous writer
49115     ** must have exited unexpectedly in the middle of a transaction (after
49116     ** writing one or more dirty pages to the WAL to free up memory).
49117     ** Remove the remnants of that writers uncommitted transaction from
49118     ** the hash-table before writing any new entries.
49119     */
49120     if( aPgno[idx] ){
49121       walCleanupHash(pWal);
49122       assert( !aPgno[idx] );
49123     }
49124 
49125     /* Write the aPgno[] array entry and the hash-table slot. */
49126     nCollide = idx;
49127     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
49128       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
49129     }
49130     aPgno[idx] = iPage;
49131     aHash[iKey] = (ht_slot)idx;
49132 
49133 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
49134     /* Verify that the number of entries in the hash table exactly equals
49135     ** the number of entries in the mapping region.
49136     */
49137     {
49138       int i;           /* Loop counter */
49139       int nEntry = 0;  /* Number of entries in the hash table */
49140       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
49141       assert( nEntry==idx );
49142     }
49143 
49144     /* Verify that the every entry in the mapping region is reachable
49145     ** via the hash table.  This turns out to be a really, really expensive
49146     ** thing to check, so only do this occasionally - not on every
49147     ** iteration.
49148     */
49149     if( (idx&0x3ff)==0 ){
49150       int i;           /* Loop counter */
49151       for(i=1; i<=idx; i++){
49152         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
49153           if( aHash[iKey]==i ) break;
49154         }
49155         assert( aHash[iKey]==i );
49156       }
49157     }
49158 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
49159   }
49160 
49161 
49162   return rc;
49163 }
49164 
49165 
49166 /*
49167 ** Recover the wal-index by reading the write-ahead log file.
49168 **
49169 ** This routine first tries to establish an exclusive lock on the
49170 ** wal-index to prevent other threads/processes from doing anything
49171 ** with the WAL or wal-index while recovery is running.  The
49172 ** WAL_RECOVER_LOCK is also held so that other threads will know
49173 ** that this thread is running recovery.  If unable to establish
49174 ** the necessary locks, this routine returns SQLITE_BUSY.
49175 */
49176 static int walIndexRecover(Wal *pWal){
49177   int rc;                         /* Return Code */
49178   i64 nSize;                      /* Size of log file */
49179   u32 aFrameCksum[2] = {0, 0};
49180   int iLock;                      /* Lock offset to lock for checkpoint */
49181   int nLock;                      /* Number of locks to hold */
49182 
49183   /* Obtain an exclusive lock on all byte in the locking range not already
49184   ** locked by the caller. The caller is guaranteed to have locked the
49185   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
49186   ** If successful, the same bytes that are locked here are unlocked before
49187   ** this function returns.
49188   */
49189   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
49190   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
49191   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
49192   assert( pWal->writeLock );
49193   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
49194   nLock = SQLITE_SHM_NLOCK - iLock;
49195   rc = walLockExclusive(pWal, iLock, nLock);
49196   if( rc ){
49197     return rc;
49198   }
49199   WALTRACE(("WAL%p: recovery begin...\n", pWal));
49200 
49201   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
49202 
49203   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
49204   if( rc!=SQLITE_OK ){
49205     goto recovery_error;
49206   }
49207 
49208   if( nSize>WAL_HDRSIZE ){
49209     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
49210     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
49211     int szFrame;                  /* Number of bytes in buffer aFrame[] */
49212     u8 *aData;                    /* Pointer to data part of aFrame buffer */
49213     int iFrame;                   /* Index of last frame read */
49214     i64 iOffset;                  /* Next offset to read from log file */
49215     int szPage;                   /* Page size according to the log */
49216     u32 magic;                    /* Magic value read from WAL header */
49217     u32 version;                  /* Magic value read from WAL header */
49218     int isValid;                  /* True if this frame is valid */
49219 
49220     /* Read in the WAL header. */
49221     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
49222     if( rc!=SQLITE_OK ){
49223       goto recovery_error;
49224     }
49225 
49226     /* If the database page size is not a power of two, or is greater than
49227     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
49228     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
49229     ** WAL file.
49230     */
49231     magic = sqlite3Get4byte(&aBuf[0]);
49232     szPage = sqlite3Get4byte(&aBuf[8]);
49233     if( (magic&0xFFFFFFFE)!=WAL_MAGIC
49234      || szPage&(szPage-1)
49235      || szPage>SQLITE_MAX_PAGE_SIZE
49236      || szPage<512
49237     ){
49238       goto finished;
49239     }
49240     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
49241     pWal->szPage = szPage;
49242     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
49243     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
49244 
49245     /* Verify that the WAL header checksum is correct */
49246     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
49247         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
49248     );
49249     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
49250      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
49251     ){
49252       goto finished;
49253     }
49254 
49255     /* Verify that the version number on the WAL format is one that
49256     ** are able to understand */
49257     version = sqlite3Get4byte(&aBuf[4]);
49258     if( version!=WAL_MAX_VERSION ){
49259       rc = SQLITE_CANTOPEN_BKPT;
49260       goto finished;
49261     }
49262 
49263     /* Malloc a buffer to read frames into. */
49264     szFrame = szPage + WAL_FRAME_HDRSIZE;
49265     aFrame = (u8 *)sqlite3_malloc(szFrame);
49266     if( !aFrame ){
49267       rc = SQLITE_NOMEM;
49268       goto recovery_error;
49269     }
49270     aData = &aFrame[WAL_FRAME_HDRSIZE];
49271 
49272     /* Read all frames from the log file. */
49273     iFrame = 0;
49274     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
49275       u32 pgno;                   /* Database page number for frame */
49276       u32 nTruncate;              /* dbsize field from frame header */
49277 
49278       /* Read and decode the next log frame. */
49279       iFrame++;
49280       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
49281       if( rc!=SQLITE_OK ) break;
49282       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
49283       if( !isValid ) break;
49284       rc = walIndexAppend(pWal, iFrame, pgno);
49285       if( rc!=SQLITE_OK ) break;
49286 
49287       /* If nTruncate is non-zero, this is a commit record. */
49288       if( nTruncate ){
49289         pWal->hdr.mxFrame = iFrame;
49290         pWal->hdr.nPage = nTruncate;
49291         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
49292         testcase( szPage<=32768 );
49293         testcase( szPage>=65536 );
49294         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
49295         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
49296       }
49297     }
49298 
49299     sqlite3_free(aFrame);
49300   }
49301 
49302 finished:
49303   if( rc==SQLITE_OK ){
49304     volatile WalCkptInfo *pInfo;
49305     int i;
49306     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
49307     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
49308     walIndexWriteHdr(pWal);
49309 
49310     /* Reset the checkpoint-header. This is safe because this thread is
49311     ** currently holding locks that exclude all other readers, writers and
49312     ** checkpointers.
49313     */
49314     pInfo = walCkptInfo(pWal);
49315     pInfo->nBackfill = 0;
49316     pInfo->aReadMark[0] = 0;
49317     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
49318     if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
49319 
49320     /* If more than one frame was recovered from the log file, report an
49321     ** event via sqlite3_log(). This is to help with identifying performance
49322     ** problems caused by applications routinely shutting down without
49323     ** checkpointing the log file.
49324     */
49325     if( pWal->hdr.nPage ){
49326       sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
49327           "recovered %d frames from WAL file %s",
49328           pWal->hdr.mxFrame, pWal->zWalName
49329       );
49330     }
49331   }
49332 
49333 recovery_error:
49334   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
49335   walUnlockExclusive(pWal, iLock, nLock);
49336   return rc;
49337 }
49338 
49339 /*
49340 ** Close an open wal-index.
49341 */
49342 static void walIndexClose(Wal *pWal, int isDelete){
49343   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
49344     int i;
49345     for(i=0; i<pWal->nWiData; i++){
49346       sqlite3_free((void *)pWal->apWiData[i]);
49347       pWal->apWiData[i] = 0;
49348     }
49349   }else{
49350     sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
49351   }
49352 }
49353 
49354 /*
49355 ** Open a connection to the WAL file zWalName. The database file must
49356 ** already be opened on connection pDbFd. The buffer that zWalName points
49357 ** to must remain valid for the lifetime of the returned Wal* handle.
49358 **
49359 ** A SHARED lock should be held on the database file when this function
49360 ** is called. The purpose of this SHARED lock is to prevent any other
49361 ** client from unlinking the WAL or wal-index file. If another process
49362 ** were to do this just after this client opened one of these files, the
49363 ** system would be badly broken.
49364 **
49365 ** If the log file is successfully opened, SQLITE_OK is returned and
49366 ** *ppWal is set to point to a new WAL handle. If an error occurs,
49367 ** an SQLite error code is returned and *ppWal is left unmodified.
49368 */
49369 SQLITE_PRIVATE int sqlite3WalOpen(
49370   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
49371   sqlite3_file *pDbFd,            /* The open database file */
49372   const char *zWalName,           /* Name of the WAL file */
49373   int bNoShm,                     /* True to run in heap-memory mode */
49374   i64 mxWalSize,                  /* Truncate WAL to this size on reset */
49375   Wal **ppWal                     /* OUT: Allocated Wal handle */
49376 ){
49377   int rc;                         /* Return Code */
49378   Wal *pRet;                      /* Object to allocate and return */
49379   int flags;                      /* Flags passed to OsOpen() */
49380 
49381   assert( zWalName && zWalName[0] );
49382   assert( pDbFd );
49383 
49384   /* In the amalgamation, the os_unix.c and os_win.c source files come before
49385   ** this source file.  Verify that the #defines of the locking byte offsets
49386   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
49387   */
49388 #ifdef WIN_SHM_BASE
49389   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
49390 #endif
49391 #ifdef UNIX_SHM_BASE
49392   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
49393 #endif
49394 
49395 
49396   /* Allocate an instance of struct Wal to return. */
49397   *ppWal = 0;
49398   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
49399   if( !pRet ){
49400     return SQLITE_NOMEM;
49401   }
49402 
49403   pRet->pVfs = pVfs;
49404   pRet->pWalFd = (sqlite3_file *)&pRet[1];
49405   pRet->pDbFd = pDbFd;
49406   pRet->readLock = -1;
49407   pRet->mxWalSize = mxWalSize;
49408   pRet->zWalName = zWalName;
49409   pRet->syncHeader = 1;
49410   pRet->padToSectorBoundary = 1;
49411   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
49412 
49413   /* Open file handle on the write-ahead log file. */
49414   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
49415   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
49416   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
49417     pRet->readOnly = WAL_RDONLY;
49418   }
49419 
49420   if( rc!=SQLITE_OK ){
49421     walIndexClose(pRet, 0);
49422     sqlite3OsClose(pRet->pWalFd);
49423     sqlite3_free(pRet);
49424   }else{
49425     int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
49426     if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
49427     if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
49428       pRet->padToSectorBoundary = 0;
49429     }
49430     *ppWal = pRet;
49431     WALTRACE(("WAL%d: opened\n", pRet));
49432   }
49433   return rc;
49434 }
49435 
49436 /*
49437 ** Change the size to which the WAL file is trucated on each reset.
49438 */
49439 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
49440   if( pWal ) pWal->mxWalSize = iLimit;
49441 }
49442 
49443 /*
49444 ** Find the smallest page number out of all pages held in the WAL that
49445 ** has not been returned by any prior invocation of this method on the
49446 ** same WalIterator object.   Write into *piFrame the frame index where
49447 ** that page was last written into the WAL.  Write into *piPage the page
49448 ** number.
49449 **
49450 ** Return 0 on success.  If there are no pages in the WAL with a page
49451 ** number larger than *piPage, then return 1.
49452 */
49453 static int walIteratorNext(
49454   WalIterator *p,               /* Iterator */
49455   u32 *piPage,                  /* OUT: The page number of the next page */
49456   u32 *piFrame                  /* OUT: Wal frame index of next page */
49457 ){
49458   u32 iMin;                     /* Result pgno must be greater than iMin */
49459   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
49460   int i;                        /* For looping through segments */
49461 
49462   iMin = p->iPrior;
49463   assert( iMin<0xffffffff );
49464   for(i=p->nSegment-1; i>=0; i--){
49465     struct WalSegment *pSegment = &p->aSegment[i];
49466     while( pSegment->iNext<pSegment->nEntry ){
49467       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
49468       if( iPg>iMin ){
49469         if( iPg<iRet ){
49470           iRet = iPg;
49471           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
49472         }
49473         break;
49474       }
49475       pSegment->iNext++;
49476     }
49477   }
49478 
49479   *piPage = p->iPrior = iRet;
49480   return (iRet==0xFFFFFFFF);
49481 }
49482 
49483 /*
49484 ** This function merges two sorted lists into a single sorted list.
49485 **
49486 ** aLeft[] and aRight[] are arrays of indices.  The sort key is
49487 ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
49488 ** is guaranteed for all J<K:
49489 **
49490 **        aContent[aLeft[J]] < aContent[aLeft[K]]
49491 **        aContent[aRight[J]] < aContent[aRight[K]]
49492 **
49493 ** This routine overwrites aRight[] with a new (probably longer) sequence
49494 ** of indices such that the aRight[] contains every index that appears in
49495 ** either aLeft[] or the old aRight[] and such that the second condition
49496 ** above is still met.
49497 **
49498 ** The aContent[aLeft[X]] values will be unique for all X.  And the
49499 ** aContent[aRight[X]] values will be unique too.  But there might be
49500 ** one or more combinations of X and Y such that
49501 **
49502 **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
49503 **
49504 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
49505 */
49506 static void walMerge(
49507   const u32 *aContent,            /* Pages in wal - keys for the sort */
49508   ht_slot *aLeft,                 /* IN: Left hand input list */
49509   int nLeft,                      /* IN: Elements in array *paLeft */
49510   ht_slot **paRight,              /* IN/OUT: Right hand input list */
49511   int *pnRight,                   /* IN/OUT: Elements in *paRight */
49512   ht_slot *aTmp                   /* Temporary buffer */
49513 ){
49514   int iLeft = 0;                  /* Current index in aLeft */
49515   int iRight = 0;                 /* Current index in aRight */
49516   int iOut = 0;                   /* Current index in output buffer */
49517   int nRight = *pnRight;
49518   ht_slot *aRight = *paRight;
49519 
49520   assert( nLeft>0 && nRight>0 );
49521   while( iRight<nRight || iLeft<nLeft ){
49522     ht_slot logpage;
49523     Pgno dbpage;
49524 
49525     if( (iLeft<nLeft)
49526      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
49527     ){
49528       logpage = aLeft[iLeft++];
49529     }else{
49530       logpage = aRight[iRight++];
49531     }
49532     dbpage = aContent[logpage];
49533 
49534     aTmp[iOut++] = logpage;
49535     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
49536 
49537     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
49538     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
49539   }
49540 
49541   *paRight = aLeft;
49542   *pnRight = iOut;
49543   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
49544 }
49545 
49546 /*
49547 ** Sort the elements in list aList using aContent[] as the sort key.
49548 ** Remove elements with duplicate keys, preferring to keep the
49549 ** larger aList[] values.
49550 **
49551 ** The aList[] entries are indices into aContent[].  The values in
49552 ** aList[] are to be sorted so that for all J<K:
49553 **
49554 **      aContent[aList[J]] < aContent[aList[K]]
49555 **
49556 ** For any X and Y such that
49557 **
49558 **      aContent[aList[X]] == aContent[aList[Y]]
49559 **
49560 ** Keep the larger of the two values aList[X] and aList[Y] and discard
49561 ** the smaller.
49562 */
49563 static void walMergesort(
49564   const u32 *aContent,            /* Pages in wal */
49565   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
49566   ht_slot *aList,                 /* IN/OUT: List to sort */
49567   int *pnList                     /* IN/OUT: Number of elements in aList[] */
49568 ){
49569   struct Sublist {
49570     int nList;                    /* Number of elements in aList */
49571     ht_slot *aList;               /* Pointer to sub-list content */
49572   };
49573 
49574   const int nList = *pnList;      /* Size of input list */
49575   int nMerge = 0;                 /* Number of elements in list aMerge */
49576   ht_slot *aMerge = 0;            /* List to be merged */
49577   int iList;                      /* Index into input list */
49578   int iSub = 0;                   /* Index into aSub array */
49579   struct Sublist aSub[13];        /* Array of sub-lists */
49580 
49581   memset(aSub, 0, sizeof(aSub));
49582   assert( nList<=HASHTABLE_NPAGE && nList>0 );
49583   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
49584 
49585   for(iList=0; iList<nList; iList++){
49586     nMerge = 1;
49587     aMerge = &aList[iList];
49588     for(iSub=0; iList & (1<<iSub); iSub++){
49589       struct Sublist *p = &aSub[iSub];
49590       assert( p->aList && p->nList<=(1<<iSub) );
49591       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
49592       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
49593     }
49594     aSub[iSub].aList = aMerge;
49595     aSub[iSub].nList = nMerge;
49596   }
49597 
49598   for(iSub++; iSub<ArraySize(aSub); iSub++){
49599     if( nList & (1<<iSub) ){
49600       struct Sublist *p = &aSub[iSub];
49601       assert( p->nList<=(1<<iSub) );
49602       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
49603       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
49604     }
49605   }
49606   assert( aMerge==aList );
49607   *pnList = nMerge;
49608 
49609 #ifdef SQLITE_DEBUG
49610   {
49611     int i;
49612     for(i=1; i<*pnList; i++){
49613       assert( aContent[aList[i]] > aContent[aList[i-1]] );
49614     }
49615   }
49616 #endif
49617 }
49618 
49619 /*
49620 ** Free an iterator allocated by walIteratorInit().
49621 */
49622 static void walIteratorFree(WalIterator *p){
49623   sqlite3ScratchFree(p);
49624 }
49625 
49626 /*
49627 ** Construct a WalInterator object that can be used to loop over all
49628 ** pages in the WAL in ascending order. The caller must hold the checkpoint
49629 ** lock.
49630 **
49631 ** On success, make *pp point to the newly allocated WalInterator object
49632 ** return SQLITE_OK. Otherwise, return an error code. If this routine
49633 ** returns an error, the value of *pp is undefined.
49634 **
49635 ** The calling routine should invoke walIteratorFree() to destroy the
49636 ** WalIterator object when it has finished with it.
49637 */
49638 static int walIteratorInit(Wal *pWal, WalIterator **pp){
49639   WalIterator *p;                 /* Return value */
49640   int nSegment;                   /* Number of segments to merge */
49641   u32 iLast;                      /* Last frame in log */
49642   int nByte;                      /* Number of bytes to allocate */
49643   int i;                          /* Iterator variable */
49644   ht_slot *aTmp;                  /* Temp space used by merge-sort */
49645   int rc = SQLITE_OK;             /* Return Code */
49646 
49647   /* This routine only runs while holding the checkpoint lock. And
49648   ** it only runs if there is actually content in the log (mxFrame>0).
49649   */
49650   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
49651   iLast = pWal->hdr.mxFrame;
49652 
49653   /* Allocate space for the WalIterator object. */
49654   nSegment = walFramePage(iLast) + 1;
49655   nByte = sizeof(WalIterator)
49656         + (nSegment-1)*sizeof(struct WalSegment)
49657         + iLast*sizeof(ht_slot);
49658   p = (WalIterator *)sqlite3ScratchMalloc(nByte);
49659   if( !p ){
49660     return SQLITE_NOMEM;
49661   }
49662   memset(p, 0, nByte);
49663   p->nSegment = nSegment;
49664 
49665   /* Allocate temporary space used by the merge-sort routine. This block
49666   ** of memory will be freed before this function returns.
49667   */
49668   aTmp = (ht_slot *)sqlite3ScratchMalloc(
49669       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
49670   );
49671   if( !aTmp ){
49672     rc = SQLITE_NOMEM;
49673   }
49674 
49675   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
49676     volatile ht_slot *aHash;
49677     u32 iZero;
49678     volatile u32 *aPgno;
49679 
49680     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
49681     if( rc==SQLITE_OK ){
49682       int j;                      /* Counter variable */
49683       int nEntry;                 /* Number of entries in this segment */
49684       ht_slot *aIndex;            /* Sorted index for this segment */
49685 
49686       aPgno++;
49687       if( (i+1)==nSegment ){
49688         nEntry = (int)(iLast - iZero);
49689       }else{
49690         nEntry = (int)((u32*)aHash - (u32*)aPgno);
49691       }
49692       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
49693       iZero++;
49694 
49695       for(j=0; j<nEntry; j++){
49696         aIndex[j] = (ht_slot)j;
49697       }
49698       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
49699       p->aSegment[i].iZero = iZero;
49700       p->aSegment[i].nEntry = nEntry;
49701       p->aSegment[i].aIndex = aIndex;
49702       p->aSegment[i].aPgno = (u32 *)aPgno;
49703     }
49704   }
49705   sqlite3ScratchFree(aTmp);
49706 
49707   if( rc!=SQLITE_OK ){
49708     walIteratorFree(p);
49709   }
49710   *pp = p;
49711   return rc;
49712 }
49713 
49714 /*
49715 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
49716 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
49717 ** busy-handler function. Invoke it and retry the lock until either the
49718 ** lock is successfully obtained or the busy-handler returns 0.
49719 */
49720 static int walBusyLock(
49721   Wal *pWal,                      /* WAL connection */
49722   int (*xBusy)(void*),            /* Function to call when busy */
49723   void *pBusyArg,                 /* Context argument for xBusyHandler */
49724   int lockIdx,                    /* Offset of first byte to lock */
49725   int n                           /* Number of bytes to lock */
49726 ){
49727   int rc;
49728   do {
49729     rc = walLockExclusive(pWal, lockIdx, n);
49730   }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
49731   return rc;
49732 }
49733 
49734 /*
49735 ** The cache of the wal-index header must be valid to call this function.
49736 ** Return the page-size in bytes used by the database.
49737 */
49738 static int walPagesize(Wal *pWal){
49739   return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
49740 }
49741 
49742 /*
49743 ** Copy as much content as we can from the WAL back into the database file
49744 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
49745 **
49746 ** The amount of information copies from WAL to database might be limited
49747 ** by active readers.  This routine will never overwrite a database page
49748 ** that a concurrent reader might be using.
49749 **
49750 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
49751 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
49752 ** checkpoints are always run by a background thread or background
49753 ** process, foreground threads will never block on a lengthy fsync call.
49754 **
49755 ** Fsync is called on the WAL before writing content out of the WAL and
49756 ** into the database.  This ensures that if the new content is persistent
49757 ** in the WAL and can be recovered following a power-loss or hard reset.
49758 **
49759 ** Fsync is also called on the database file if (and only if) the entire
49760 ** WAL content is copied into the database file.  This second fsync makes
49761 ** it safe to delete the WAL since the new content will persist in the
49762 ** database file.
49763 **
49764 ** This routine uses and updates the nBackfill field of the wal-index header.
49765 ** This is the only routine that will increase the value of nBackfill.
49766 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
49767 ** its value.)
49768 **
49769 ** The caller must be holding sufficient locks to ensure that no other
49770 ** checkpoint is running (in any other thread or process) at the same
49771 ** time.
49772 */
49773 static int walCheckpoint(
49774   Wal *pWal,                      /* Wal connection */
49775   int eMode,                      /* One of PASSIVE, FULL or RESTART */
49776   int (*xBusyCall)(void*),        /* Function to call when busy */
49777   void *pBusyArg,                 /* Context argument for xBusyHandler */
49778   int sync_flags,                 /* Flags for OsSync() (or 0) */
49779   u8 *zBuf                        /* Temporary buffer to use */
49780 ){
49781   int rc;                         /* Return code */
49782   int szPage;                     /* Database page-size */
49783   WalIterator *pIter = 0;         /* Wal iterator context */
49784   u32 iDbpage = 0;                /* Next database page to write */
49785   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
49786   u32 mxSafeFrame;                /* Max frame that can be backfilled */
49787   u32 mxPage;                     /* Max database page to write */
49788   int i;                          /* Loop counter */
49789   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
49790   int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
49791 
49792   szPage = walPagesize(pWal);
49793   testcase( szPage<=32768 );
49794   testcase( szPage>=65536 );
49795   pInfo = walCkptInfo(pWal);
49796   if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
49797 
49798   /* Allocate the iterator */
49799   rc = walIteratorInit(pWal, &pIter);
49800   if( rc!=SQLITE_OK ){
49801     return rc;
49802   }
49803   assert( pIter );
49804 
49805   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
49806 
49807   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
49808   ** safe to write into the database.  Frames beyond mxSafeFrame might
49809   ** overwrite database pages that are in use by active readers and thus
49810   ** cannot be backfilled from the WAL.
49811   */
49812   mxSafeFrame = pWal->hdr.mxFrame;
49813   mxPage = pWal->hdr.nPage;
49814   for(i=1; i<WAL_NREADER; i++){
49815     u32 y = pInfo->aReadMark[i];
49816     if( mxSafeFrame>y ){
49817       assert( y<=pWal->hdr.mxFrame );
49818       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
49819       if( rc==SQLITE_OK ){
49820         pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
49821         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
49822       }else if( rc==SQLITE_BUSY ){
49823         mxSafeFrame = y;
49824         xBusy = 0;
49825       }else{
49826         goto walcheckpoint_out;
49827       }
49828     }
49829   }
49830 
49831   if( pInfo->nBackfill<mxSafeFrame
49832    && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
49833   ){
49834     i64 nSize;                    /* Current size of database file */
49835     u32 nBackfill = pInfo->nBackfill;
49836 
49837     /* Sync the WAL to disk */
49838     if( sync_flags ){
49839       rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
49840     }
49841 
49842     /* If the database may grow as a result of this checkpoint, hint
49843     ** about the eventual size of the db file to the VFS layer.
49844     */
49845     if( rc==SQLITE_OK ){
49846       i64 nReq = ((i64)mxPage * szPage);
49847       rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
49848       if( rc==SQLITE_OK && nSize<nReq ){
49849         sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
49850       }
49851     }
49852 
49853 
49854     /* Iterate through the contents of the WAL, copying data to the db file. */
49855     while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
49856       i64 iOffset;
49857       assert( walFramePgno(pWal, iFrame)==iDbpage );
49858       if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
49859       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
49860       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
49861       rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
49862       if( rc!=SQLITE_OK ) break;
49863       iOffset = (iDbpage-1)*(i64)szPage;
49864       testcase( IS_BIG_INT(iOffset) );
49865       rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
49866       if( rc!=SQLITE_OK ) break;
49867     }
49868 
49869     /* If work was actually accomplished... */
49870     if( rc==SQLITE_OK ){
49871       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
49872         i64 szDb = pWal->hdr.nPage*(i64)szPage;
49873         testcase( IS_BIG_INT(szDb) );
49874         rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
49875         if( rc==SQLITE_OK && sync_flags ){
49876           rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
49877         }
49878       }
49879       if( rc==SQLITE_OK ){
49880         pInfo->nBackfill = mxSafeFrame;
49881       }
49882     }
49883 
49884     /* Release the reader lock held while backfilling */
49885     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
49886   }
49887 
49888   if( rc==SQLITE_BUSY ){
49889     /* Reset the return code so as not to report a checkpoint failure
49890     ** just because there are active readers.  */
49891     rc = SQLITE_OK;
49892   }
49893 
49894   /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
49895   ** file has been copied into the database file, then block until all
49896   ** readers have finished using the wal file. This ensures that the next
49897   ** process to write to the database restarts the wal file.
49898   */
49899   if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
49900     assert( pWal->writeLock );
49901     if( pInfo->nBackfill<pWal->hdr.mxFrame ){
49902       rc = SQLITE_BUSY;
49903     }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
49904       assert( mxSafeFrame==pWal->hdr.mxFrame );
49905       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
49906       if( rc==SQLITE_OK ){
49907         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
49908       }
49909     }
49910   }
49911 
49912  walcheckpoint_out:
49913   walIteratorFree(pIter);
49914   return rc;
49915 }
49916 
49917 /*
49918 ** If the WAL file is currently larger than nMax bytes in size, truncate
49919 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
49920 */
49921 static void walLimitSize(Wal *pWal, i64 nMax){
49922   i64 sz;
49923   int rx;
49924   sqlite3BeginBenignMalloc();
49925   rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
49926   if( rx==SQLITE_OK && (sz > nMax ) ){
49927     rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
49928   }
49929   sqlite3EndBenignMalloc();
49930   if( rx ){
49931     sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
49932   }
49933 }
49934 
49935 /*
49936 ** Close a connection to a log file.
49937 */
49938 SQLITE_PRIVATE int sqlite3WalClose(
49939   Wal *pWal,                      /* Wal to close */
49940   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
49941   int nBuf,
49942   u8 *zBuf                        /* Buffer of at least nBuf bytes */
49943 ){
49944   int rc = SQLITE_OK;
49945   if( pWal ){
49946     int isDelete = 0;             /* True to unlink wal and wal-index files */
49947 
49948     /* If an EXCLUSIVE lock can be obtained on the database file (using the
49949     ** ordinary, rollback-mode locking methods, this guarantees that the
49950     ** connection associated with this log file is the only connection to
49951     ** the database. In this case checkpoint the database and unlink both
49952     ** the wal and wal-index files.
49953     **
49954     ** The EXCLUSIVE lock is not released before returning.
49955     */
49956     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
49957     if( rc==SQLITE_OK ){
49958       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
49959         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
49960       }
49961       rc = sqlite3WalCheckpoint(
49962           pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
49963       );
49964       if( rc==SQLITE_OK ){
49965         int bPersist = -1;
49966         sqlite3OsFileControlHint(
49967             pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
49968         );
49969         if( bPersist!=1 ){
49970           /* Try to delete the WAL file if the checkpoint completed and
49971           ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
49972           ** mode (!bPersist) */
49973           isDelete = 1;
49974         }else if( pWal->mxWalSize>=0 ){
49975           /* Try to truncate the WAL file to zero bytes if the checkpoint
49976           ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
49977           ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
49978           ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
49979           ** to zero bytes as truncating to the journal_size_limit might
49980           ** leave a corrupt WAL file on disk. */
49981           walLimitSize(pWal, 0);
49982         }
49983       }
49984     }
49985 
49986     walIndexClose(pWal, isDelete);
49987     sqlite3OsClose(pWal->pWalFd);
49988     if( isDelete ){
49989       sqlite3BeginBenignMalloc();
49990       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
49991       sqlite3EndBenignMalloc();
49992     }
49993     WALTRACE(("WAL%p: closed\n", pWal));
49994     sqlite3_free((void *)pWal->apWiData);
49995     sqlite3_free(pWal);
49996   }
49997   return rc;
49998 }
49999 
50000 /*
50001 ** Try to read the wal-index header.  Return 0 on success and 1 if
50002 ** there is a problem.
50003 **
50004 ** The wal-index is in shared memory.  Another thread or process might
50005 ** be writing the header at the same time this procedure is trying to
50006 ** read it, which might result in inconsistency.  A dirty read is detected
50007 ** by verifying that both copies of the header are the same and also by
50008 ** a checksum on the header.
50009 **
50010 ** If and only if the read is consistent and the header is different from
50011 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
50012 ** and *pChanged is set to 1.
50013 **
50014 ** If the checksum cannot be verified return non-zero. If the header
50015 ** is read successfully and the checksum verified, return zero.
50016 */
50017 static int walIndexTryHdr(Wal *pWal, int *pChanged){
50018   u32 aCksum[2];                  /* Checksum on the header content */
50019   WalIndexHdr h1, h2;             /* Two copies of the header content */
50020   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
50021 
50022   /* The first page of the wal-index must be mapped at this point. */
50023   assert( pWal->nWiData>0 && pWal->apWiData[0] );
50024 
50025   /* Read the header. This might happen concurrently with a write to the
50026   ** same area of shared memory on a different CPU in a SMP,
50027   ** meaning it is possible that an inconsistent snapshot is read
50028   ** from the file. If this happens, return non-zero.
50029   **
50030   ** There are two copies of the header at the beginning of the wal-index.
50031   ** When reading, read [0] first then [1].  Writes are in the reverse order.
50032   ** Memory barriers are used to prevent the compiler or the hardware from
50033   ** reordering the reads and writes.
50034   */
50035   aHdr = walIndexHdr(pWal);
50036   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
50037   walShmBarrier(pWal);
50038   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
50039 
50040   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
50041     return 1;   /* Dirty read */
50042   }
50043   if( h1.isInit==0 ){
50044     return 1;   /* Malformed header - probably all zeros */
50045   }
50046   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
50047   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
50048     return 1;   /* Checksum does not match */
50049   }
50050 
50051   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
50052     *pChanged = 1;
50053     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
50054     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
50055     testcase( pWal->szPage<=32768 );
50056     testcase( pWal->szPage>=65536 );
50057   }
50058 
50059   /* The header was successfully read. Return zero. */
50060   return 0;
50061 }
50062 
50063 /*
50064 ** Read the wal-index header from the wal-index and into pWal->hdr.
50065 ** If the wal-header appears to be corrupt, try to reconstruct the
50066 ** wal-index from the WAL before returning.
50067 **
50068 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
50069 ** changed by this operation.  If pWal->hdr is unchanged, set *pChanged
50070 ** to 0.
50071 **
50072 ** If the wal-index header is successfully read, return SQLITE_OK.
50073 ** Otherwise an SQLite error code.
50074 */
50075 static int walIndexReadHdr(Wal *pWal, int *pChanged){
50076   int rc;                         /* Return code */
50077   int badHdr;                     /* True if a header read failed */
50078   volatile u32 *page0;            /* Chunk of wal-index containing header */
50079 
50080   /* Ensure that page 0 of the wal-index (the page that contains the
50081   ** wal-index header) is mapped. Return early if an error occurs here.
50082   */
50083   assert( pChanged );
50084   rc = walIndexPage(pWal, 0, &page0);
50085   if( rc!=SQLITE_OK ){
50086     return rc;
50087   };
50088   assert( page0 || pWal->writeLock==0 );
50089 
50090   /* If the first page of the wal-index has been mapped, try to read the
50091   ** wal-index header immediately, without holding any lock. This usually
50092   ** works, but may fail if the wal-index header is corrupt or currently
50093   ** being modified by another thread or process.
50094   */
50095   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
50096 
50097   /* If the first attempt failed, it might have been due to a race
50098   ** with a writer.  So get a WRITE lock and try again.
50099   */
50100   assert( badHdr==0 || pWal->writeLock==0 );
50101   if( badHdr ){
50102     if( pWal->readOnly & WAL_SHM_RDONLY ){
50103       if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
50104         walUnlockShared(pWal, WAL_WRITE_LOCK);
50105         rc = SQLITE_READONLY_RECOVERY;
50106       }
50107     }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
50108       pWal->writeLock = 1;
50109       if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
50110         badHdr = walIndexTryHdr(pWal, pChanged);
50111         if( badHdr ){
50112           /* If the wal-index header is still malformed even while holding
50113           ** a WRITE lock, it can only mean that the header is corrupted and
50114           ** needs to be reconstructed.  So run recovery to do exactly that.
50115           */
50116           rc = walIndexRecover(pWal);
50117           *pChanged = 1;
50118         }
50119       }
50120       pWal->writeLock = 0;
50121       walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
50122     }
50123   }
50124 
50125   /* If the header is read successfully, check the version number to make
50126   ** sure the wal-index was not constructed with some future format that
50127   ** this version of SQLite cannot understand.
50128   */
50129   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
50130     rc = SQLITE_CANTOPEN_BKPT;
50131   }
50132 
50133   return rc;
50134 }
50135 
50136 /*
50137 ** This is the value that walTryBeginRead returns when it needs to
50138 ** be retried.
50139 */
50140 #define WAL_RETRY  (-1)
50141 
50142 /*
50143 ** Attempt to start a read transaction.  This might fail due to a race or
50144 ** other transient condition.  When that happens, it returns WAL_RETRY to
50145 ** indicate to the caller that it is safe to retry immediately.
50146 **
50147 ** On success return SQLITE_OK.  On a permanent failure (such an
50148 ** I/O error or an SQLITE_BUSY because another process is running
50149 ** recovery) return a positive error code.
50150 **
50151 ** The useWal parameter is true to force the use of the WAL and disable
50152 ** the case where the WAL is bypassed because it has been completely
50153 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
50154 ** to make a copy of the wal-index header into pWal->hdr.  If the
50155 ** wal-index header has changed, *pChanged is set to 1 (as an indication
50156 ** to the caller that the local paget cache is obsolete and needs to be
50157 ** flushed.)  When useWal==1, the wal-index header is assumed to already
50158 ** be loaded and the pChanged parameter is unused.
50159 **
50160 ** The caller must set the cnt parameter to the number of prior calls to
50161 ** this routine during the current read attempt that returned WAL_RETRY.
50162 ** This routine will start taking more aggressive measures to clear the
50163 ** race conditions after multiple WAL_RETRY returns, and after an excessive
50164 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
50165 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
50166 ** and is not honoring the locking protocol.  There is a vanishingly small
50167 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
50168 ** bad luck when there is lots of contention for the wal-index, but that
50169 ** possibility is so small that it can be safely neglected, we believe.
50170 **
50171 ** On success, this routine obtains a read lock on
50172 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
50173 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
50174 ** that means the Wal does not hold any read lock.  The reader must not
50175 ** access any database page that is modified by a WAL frame up to and
50176 ** including frame number aReadMark[pWal->readLock].  The reader will
50177 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
50178 ** Or if pWal->readLock==0, then the reader will ignore the WAL
50179 ** completely and get all content directly from the database file.
50180 ** If the useWal parameter is 1 then the WAL will never be ignored and
50181 ** this routine will always set pWal->readLock>0 on success.
50182 ** When the read transaction is completed, the caller must release the
50183 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
50184 **
50185 ** This routine uses the nBackfill and aReadMark[] fields of the header
50186 ** to select a particular WAL_READ_LOCK() that strives to let the
50187 ** checkpoint process do as much work as possible.  This routine might
50188 ** update values of the aReadMark[] array in the header, but if it does
50189 ** so it takes care to hold an exclusive lock on the corresponding
50190 ** WAL_READ_LOCK() while changing values.
50191 */
50192 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
50193   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
50194   u32 mxReadMark;                 /* Largest aReadMark[] value */
50195   int mxI;                        /* Index of largest aReadMark[] value */
50196   int i;                          /* Loop counter */
50197   int rc = SQLITE_OK;             /* Return code  */
50198 
50199   assert( pWal->readLock<0 );     /* Not currently locked */
50200 
50201   /* Take steps to avoid spinning forever if there is a protocol error.
50202   **
50203   ** Circumstances that cause a RETRY should only last for the briefest
50204   ** instances of time.  No I/O or other system calls are done while the
50205   ** locks are held, so the locks should not be held for very long. But
50206   ** if we are unlucky, another process that is holding a lock might get
50207   ** paged out or take a page-fault that is time-consuming to resolve,
50208   ** during the few nanoseconds that it is holding the lock.  In that case,
50209   ** it might take longer than normal for the lock to free.
50210   **
50211   ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
50212   ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
50213   ** is more of a scheduler yield than an actual delay.  But on the 10th
50214   ** an subsequent retries, the delays start becoming longer and longer,
50215   ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
50216   ** The total delay time before giving up is less than 10 seconds.
50217   */
50218   if( cnt>5 ){
50219     int nDelay = 1;                      /* Pause time in microseconds */
50220     if( cnt>100 ){
50221       VVA_ONLY( pWal->lockError = 1; )
50222       return SQLITE_PROTOCOL;
50223     }
50224     if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
50225     sqlite3OsSleep(pWal->pVfs, nDelay);
50226   }
50227 
50228   if( !useWal ){
50229     rc = walIndexReadHdr(pWal, pChanged);
50230     if( rc==SQLITE_BUSY ){
50231       /* If there is not a recovery running in another thread or process
50232       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
50233       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
50234       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
50235       ** would be technically correct.  But the race is benign since with
50236       ** WAL_RETRY this routine will be called again and will probably be
50237       ** right on the second iteration.
50238       */
50239       if( pWal->apWiData[0]==0 ){
50240         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
50241         ** We assume this is a transient condition, so return WAL_RETRY. The
50242         ** xShmMap() implementation used by the default unix and win32 VFS
50243         ** modules may return SQLITE_BUSY due to a race condition in the
50244         ** code that determines whether or not the shared-memory region
50245         ** must be zeroed before the requested page is returned.
50246         */
50247         rc = WAL_RETRY;
50248       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
50249         walUnlockShared(pWal, WAL_RECOVER_LOCK);
50250         rc = WAL_RETRY;
50251       }else if( rc==SQLITE_BUSY ){
50252         rc = SQLITE_BUSY_RECOVERY;
50253       }
50254     }
50255     if( rc!=SQLITE_OK ){
50256       return rc;
50257     }
50258   }
50259 
50260   pInfo = walCkptInfo(pWal);
50261   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
50262     /* The WAL has been completely backfilled (or it is empty).
50263     ** and can be safely ignored.
50264     */
50265     rc = walLockShared(pWal, WAL_READ_LOCK(0));
50266     walShmBarrier(pWal);
50267     if( rc==SQLITE_OK ){
50268       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
50269         /* It is not safe to allow the reader to continue here if frames
50270         ** may have been appended to the log before READ_LOCK(0) was obtained.
50271         ** When holding READ_LOCK(0), the reader ignores the entire log file,
50272         ** which implies that the database file contains a trustworthy
50273         ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
50274         ** happening, this is usually correct.
50275         **
50276         ** However, if frames have been appended to the log (or if the log
50277         ** is wrapped and written for that matter) before the READ_LOCK(0)
50278         ** is obtained, that is not necessarily true. A checkpointer may
50279         ** have started to backfill the appended frames but crashed before
50280         ** it finished. Leaving a corrupt image in the database file.
50281         */
50282         walUnlockShared(pWal, WAL_READ_LOCK(0));
50283         return WAL_RETRY;
50284       }
50285       pWal->readLock = 0;
50286       return SQLITE_OK;
50287     }else if( rc!=SQLITE_BUSY ){
50288       return rc;
50289     }
50290   }
50291 
50292   /* If we get this far, it means that the reader will want to use
50293   ** the WAL to get at content from recent commits.  The job now is
50294   ** to select one of the aReadMark[] entries that is closest to
50295   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
50296   */
50297   mxReadMark = 0;
50298   mxI = 0;
50299   for(i=1; i<WAL_NREADER; i++){
50300     u32 thisMark = pInfo->aReadMark[i];
50301     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
50302       assert( thisMark!=READMARK_NOT_USED );
50303       mxReadMark = thisMark;
50304       mxI = i;
50305     }
50306   }
50307   /* There was once an "if" here. The extra "{" is to preserve indentation. */
50308   {
50309     if( (pWal->readOnly & WAL_SHM_RDONLY)==0
50310      && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
50311     ){
50312       for(i=1; i<WAL_NREADER; i++){
50313         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
50314         if( rc==SQLITE_OK ){
50315           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
50316           mxI = i;
50317           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
50318           break;
50319         }else if( rc!=SQLITE_BUSY ){
50320           return rc;
50321         }
50322       }
50323     }
50324     if( mxI==0 ){
50325       assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
50326       return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
50327     }
50328 
50329     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
50330     if( rc ){
50331       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
50332     }
50333     /* Now that the read-lock has been obtained, check that neither the
50334     ** value in the aReadMark[] array or the contents of the wal-index
50335     ** header have changed.
50336     **
50337     ** It is necessary to check that the wal-index header did not change
50338     ** between the time it was read and when the shared-lock was obtained
50339     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
50340     ** that the log file may have been wrapped by a writer, or that frames
50341     ** that occur later in the log than pWal->hdr.mxFrame may have been
50342     ** copied into the database by a checkpointer. If either of these things
50343     ** happened, then reading the database with the current value of
50344     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
50345     ** instead.
50346     **
50347     ** This does not guarantee that the copy of the wal-index header is up to
50348     ** date before proceeding. That would not be possible without somehow
50349     ** blocking writers. It only guarantees that a dangerous checkpoint or
50350     ** log-wrap (either of which would require an exclusive lock on
50351     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
50352     */
50353     walShmBarrier(pWal);
50354     if( pInfo->aReadMark[mxI]!=mxReadMark
50355      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
50356     ){
50357       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
50358       return WAL_RETRY;
50359     }else{
50360       assert( mxReadMark<=pWal->hdr.mxFrame );
50361       pWal->readLock = (i16)mxI;
50362     }
50363   }
50364   return rc;
50365 }
50366 
50367 /*
50368 ** Begin a read transaction on the database.
50369 **
50370 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
50371 ** it takes a snapshot of the state of the WAL and wal-index for the current
50372 ** instant in time.  The current thread will continue to use this snapshot.
50373 ** Other threads might append new content to the WAL and wal-index but
50374 ** that extra content is ignored by the current thread.
50375 **
50376 ** If the database contents have changes since the previous read
50377 ** transaction, then *pChanged is set to 1 before returning.  The
50378 ** Pager layer will use this to know that is cache is stale and
50379 ** needs to be flushed.
50380 */
50381 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
50382   int rc;                         /* Return code */
50383   int cnt = 0;                    /* Number of TryBeginRead attempts */
50384 
50385   do{
50386     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
50387   }while( rc==WAL_RETRY );
50388   testcase( (rc&0xff)==SQLITE_BUSY );
50389   testcase( (rc&0xff)==SQLITE_IOERR );
50390   testcase( rc==SQLITE_PROTOCOL );
50391   testcase( rc==SQLITE_OK );
50392   return rc;
50393 }
50394 
50395 /*
50396 ** Finish with a read transaction.  All this does is release the
50397 ** read-lock.
50398 */
50399 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
50400   sqlite3WalEndWriteTransaction(pWal);
50401   if( pWal->readLock>=0 ){
50402     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
50403     pWal->readLock = -1;
50404   }
50405 }
50406 
50407 /*
50408 ** Search the wal file for page pgno. If found, set *piRead to the frame that
50409 ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
50410 ** to zero.
50411 **
50412 ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
50413 ** error does occur, the final value of *piRead is undefined.
50414 */
50415 SQLITE_PRIVATE int sqlite3WalFindFrame(
50416   Wal *pWal,                      /* WAL handle */
50417   Pgno pgno,                      /* Database page number to read data for */
50418   u32 *piRead                     /* OUT: Frame number (or zero) */
50419 ){
50420   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
50421   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
50422   int iHash;                      /* Used to loop through N hash tables */
50423 
50424   /* This routine is only be called from within a read transaction. */
50425   assert( pWal->readLock>=0 || pWal->lockError );
50426 
50427   /* If the "last page" field of the wal-index header snapshot is 0, then
50428   ** no data will be read from the wal under any circumstances. Return early
50429   ** in this case as an optimization.  Likewise, if pWal->readLock==0,
50430   ** then the WAL is ignored by the reader so return early, as if the
50431   ** WAL were empty.
50432   */
50433   if( iLast==0 || pWal->readLock==0 ){
50434     *piRead = 0;
50435     return SQLITE_OK;
50436   }
50437 
50438   /* Search the hash table or tables for an entry matching page number
50439   ** pgno. Each iteration of the following for() loop searches one
50440   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
50441   **
50442   ** This code might run concurrently to the code in walIndexAppend()
50443   ** that adds entries to the wal-index (and possibly to this hash
50444   ** table). This means the value just read from the hash
50445   ** slot (aHash[iKey]) may have been added before or after the
50446   ** current read transaction was opened. Values added after the
50447   ** read transaction was opened may have been written incorrectly -
50448   ** i.e. these slots may contain garbage data. However, we assume
50449   ** that any slots written before the current read transaction was
50450   ** opened remain unmodified.
50451   **
50452   ** For the reasons above, the if(...) condition featured in the inner
50453   ** loop of the following block is more stringent that would be required
50454   ** if we had exclusive access to the hash-table:
50455   **
50456   **   (aPgno[iFrame]==pgno):
50457   **     This condition filters out normal hash-table collisions.
50458   **
50459   **   (iFrame<=iLast):
50460   **     This condition filters out entries that were added to the hash
50461   **     table after the current read-transaction had started.
50462   */
50463   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
50464     volatile ht_slot *aHash;      /* Pointer to hash table */
50465     volatile u32 *aPgno;          /* Pointer to array of page numbers */
50466     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
50467     int iKey;                     /* Hash slot index */
50468     int nCollide;                 /* Number of hash collisions remaining */
50469     int rc;                       /* Error code */
50470 
50471     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
50472     if( rc!=SQLITE_OK ){
50473       return rc;
50474     }
50475     nCollide = HASHTABLE_NSLOT;
50476     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
50477       u32 iFrame = aHash[iKey] + iZero;
50478       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
50479         /* assert( iFrame>iRead ); -- not true if there is corruption */
50480         iRead = iFrame;
50481       }
50482       if( (nCollide--)==0 ){
50483         return SQLITE_CORRUPT_BKPT;
50484       }
50485     }
50486   }
50487 
50488 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
50489   /* If expensive assert() statements are available, do a linear search
50490   ** of the wal-index file content. Make sure the results agree with the
50491   ** result obtained using the hash indexes above.  */
50492   {
50493     u32 iRead2 = 0;
50494     u32 iTest;
50495     for(iTest=iLast; iTest>0; iTest--){
50496       if( walFramePgno(pWal, iTest)==pgno ){
50497         iRead2 = iTest;
50498         break;
50499       }
50500     }
50501     assert( iRead==iRead2 );
50502   }
50503 #endif
50504 
50505   *piRead = iRead;
50506   return SQLITE_OK;
50507 }
50508 
50509 /*
50510 ** Read the contents of frame iRead from the wal file into buffer pOut
50511 ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
50512 ** error code otherwise.
50513 */
50514 SQLITE_PRIVATE int sqlite3WalReadFrame(
50515   Wal *pWal,                      /* WAL handle */
50516   u32 iRead,                      /* Frame to read */
50517   int nOut,                       /* Size of buffer pOut in bytes */
50518   u8 *pOut                        /* Buffer to write page data to */
50519 ){
50520   int sz;
50521   i64 iOffset;
50522   sz = pWal->hdr.szPage;
50523   sz = (sz&0xfe00) + ((sz&0x0001)<<16);
50524   testcase( sz<=32768 );
50525   testcase( sz>=65536 );
50526   iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
50527   /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
50528   return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
50529 }
50530 
50531 /*
50532 ** Return the size of the database in pages (or zero, if unknown).
50533 */
50534 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
50535   if( pWal && ALWAYS(pWal->readLock>=0) ){
50536     return pWal->hdr.nPage;
50537   }
50538   return 0;
50539 }
50540 
50541 
50542 /*
50543 ** This function starts a write transaction on the WAL.
50544 **
50545 ** A read transaction must have already been started by a prior call
50546 ** to sqlite3WalBeginReadTransaction().
50547 **
50548 ** If another thread or process has written into the database since
50549 ** the read transaction was started, then it is not possible for this
50550 ** thread to write as doing so would cause a fork.  So this routine
50551 ** returns SQLITE_BUSY in that case and no write transaction is started.
50552 **
50553 ** There can only be a single writer active at a time.
50554 */
50555 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
50556   int rc;
50557 
50558   /* Cannot start a write transaction without first holding a read
50559   ** transaction. */
50560   assert( pWal->readLock>=0 );
50561 
50562   if( pWal->readOnly ){
50563     return SQLITE_READONLY;
50564   }
50565 
50566   /* Only one writer allowed at a time.  Get the write lock.  Return
50567   ** SQLITE_BUSY if unable.
50568   */
50569   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
50570   if( rc ){
50571     return rc;
50572   }
50573   pWal->writeLock = 1;
50574 
50575   /* If another connection has written to the database file since the
50576   ** time the read transaction on this connection was started, then
50577   ** the write is disallowed.
50578   */
50579   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
50580     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
50581     pWal->writeLock = 0;
50582     rc = SQLITE_BUSY_SNAPSHOT;
50583   }
50584 
50585   return rc;
50586 }
50587 
50588 /*
50589 ** End a write transaction.  The commit has already been done.  This
50590 ** routine merely releases the lock.
50591 */
50592 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
50593   if( pWal->writeLock ){
50594     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
50595     pWal->writeLock = 0;
50596     pWal->truncateOnCommit = 0;
50597   }
50598   return SQLITE_OK;
50599 }
50600 
50601 /*
50602 ** If any data has been written (but not committed) to the log file, this
50603 ** function moves the write-pointer back to the start of the transaction.
50604 **
50605 ** Additionally, the callback function is invoked for each frame written
50606 ** to the WAL since the start of the transaction. If the callback returns
50607 ** other than SQLITE_OK, it is not invoked again and the error code is
50608 ** returned to the caller.
50609 **
50610 ** Otherwise, if the callback function does not return an error, this
50611 ** function returns SQLITE_OK.
50612 */
50613 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
50614   int rc = SQLITE_OK;
50615   if( ALWAYS(pWal->writeLock) ){
50616     Pgno iMax = pWal->hdr.mxFrame;
50617     Pgno iFrame;
50618 
50619     /* Restore the clients cache of the wal-index header to the state it
50620     ** was in before the client began writing to the database.
50621     */
50622     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
50623 
50624     for(iFrame=pWal->hdr.mxFrame+1;
50625         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
50626         iFrame++
50627     ){
50628       /* This call cannot fail. Unless the page for which the page number
50629       ** is passed as the second argument is (a) in the cache and
50630       ** (b) has an outstanding reference, then xUndo is either a no-op
50631       ** (if (a) is false) or simply expels the page from the cache (if (b)
50632       ** is false).
50633       **
50634       ** If the upper layer is doing a rollback, it is guaranteed that there
50635       ** are no outstanding references to any page other than page 1. And
50636       ** page 1 is never written to the log until the transaction is
50637       ** committed. As a result, the call to xUndo may not fail.
50638       */
50639       assert( walFramePgno(pWal, iFrame)!=1 );
50640       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
50641     }
50642     if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
50643   }
50644   return rc;
50645 }
50646 
50647 /*
50648 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
50649 ** values. This function populates the array with values required to
50650 ** "rollback" the write position of the WAL handle back to the current
50651 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
50652 */
50653 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
50654   assert( pWal->writeLock );
50655   aWalData[0] = pWal->hdr.mxFrame;
50656   aWalData[1] = pWal->hdr.aFrameCksum[0];
50657   aWalData[2] = pWal->hdr.aFrameCksum[1];
50658   aWalData[3] = pWal->nCkpt;
50659 }
50660 
50661 /*
50662 ** Move the write position of the WAL back to the point identified by
50663 ** the values in the aWalData[] array. aWalData must point to an array
50664 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
50665 ** by a call to WalSavepoint().
50666 */
50667 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
50668   int rc = SQLITE_OK;
50669 
50670   assert( pWal->writeLock );
50671   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
50672 
50673   if( aWalData[3]!=pWal->nCkpt ){
50674     /* This savepoint was opened immediately after the write-transaction
50675     ** was started. Right after that, the writer decided to wrap around
50676     ** to the start of the log. Update the savepoint values to match.
50677     */
50678     aWalData[0] = 0;
50679     aWalData[3] = pWal->nCkpt;
50680   }
50681 
50682   if( aWalData[0]<pWal->hdr.mxFrame ){
50683     pWal->hdr.mxFrame = aWalData[0];
50684     pWal->hdr.aFrameCksum[0] = aWalData[1];
50685     pWal->hdr.aFrameCksum[1] = aWalData[2];
50686     walCleanupHash(pWal);
50687   }
50688 
50689   return rc;
50690 }
50691 
50692 
50693 /*
50694 ** This function is called just before writing a set of frames to the log
50695 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
50696 ** to the current log file, it is possible to overwrite the start of the
50697 ** existing log file with the new frames (i.e. "reset" the log). If so,
50698 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
50699 ** unchanged.
50700 **
50701 ** SQLITE_OK is returned if no error is encountered (regardless of whether
50702 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
50703 ** if an error occurs.
50704 */
50705 static int walRestartLog(Wal *pWal){
50706   int rc = SQLITE_OK;
50707   int cnt;
50708 
50709   if( pWal->readLock==0 ){
50710     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
50711     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
50712     if( pInfo->nBackfill>0 ){
50713       u32 salt1;
50714       sqlite3_randomness(4, &salt1);
50715       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
50716       if( rc==SQLITE_OK ){
50717         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
50718         ** readers are currently using the WAL), then the transactions
50719         ** frames will overwrite the start of the existing log. Update the
50720         ** wal-index header to reflect this.
50721         **
50722         ** In theory it would be Ok to update the cache of the header only
50723         ** at this point. But updating the actual wal-index header is also
50724         ** safe and means there is no special case for sqlite3WalUndo()
50725         ** to handle if this transaction is rolled back.
50726         */
50727         int i;                    /* Loop counter */
50728         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
50729 
50730         pWal->nCkpt++;
50731         pWal->hdr.mxFrame = 0;
50732         sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
50733         aSalt[1] = salt1;
50734         walIndexWriteHdr(pWal);
50735         pInfo->nBackfill = 0;
50736         pInfo->aReadMark[1] = 0;
50737         for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
50738         assert( pInfo->aReadMark[0]==0 );
50739         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
50740       }else if( rc!=SQLITE_BUSY ){
50741         return rc;
50742       }
50743     }
50744     walUnlockShared(pWal, WAL_READ_LOCK(0));
50745     pWal->readLock = -1;
50746     cnt = 0;
50747     do{
50748       int notUsed;
50749       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
50750     }while( rc==WAL_RETRY );
50751     assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
50752     testcase( (rc&0xff)==SQLITE_IOERR );
50753     testcase( rc==SQLITE_PROTOCOL );
50754     testcase( rc==SQLITE_OK );
50755   }
50756   return rc;
50757 }
50758 
50759 /*
50760 ** Information about the current state of the WAL file and where
50761 ** the next fsync should occur - passed from sqlite3WalFrames() into
50762 ** walWriteToLog().
50763 */
50764 typedef struct WalWriter {
50765   Wal *pWal;                   /* The complete WAL information */
50766   sqlite3_file *pFd;           /* The WAL file to which we write */
50767   sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
50768   int syncFlags;               /* Flags for the fsync */
50769   int szPage;                  /* Size of one page */
50770 } WalWriter;
50771 
50772 /*
50773 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
50774 ** Do a sync when crossing the p->iSyncPoint boundary.
50775 **
50776 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
50777 ** first write the part before iSyncPoint, then sync, then write the
50778 ** rest.
50779 */
50780 static int walWriteToLog(
50781   WalWriter *p,              /* WAL to write to */
50782   void *pContent,            /* Content to be written */
50783   int iAmt,                  /* Number of bytes to write */
50784   sqlite3_int64 iOffset      /* Start writing at this offset */
50785 ){
50786   int rc;
50787   if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
50788     int iFirstAmt = (int)(p->iSyncPoint - iOffset);
50789     rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
50790     if( rc ) return rc;
50791     iOffset += iFirstAmt;
50792     iAmt -= iFirstAmt;
50793     pContent = (void*)(iFirstAmt + (char*)pContent);
50794     assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
50795     rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
50796     if( iAmt==0 || rc ) return rc;
50797   }
50798   rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
50799   return rc;
50800 }
50801 
50802 /*
50803 ** Write out a single frame of the WAL
50804 */
50805 static int walWriteOneFrame(
50806   WalWriter *p,               /* Where to write the frame */
50807   PgHdr *pPage,               /* The page of the frame to be written */
50808   int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
50809   sqlite3_int64 iOffset       /* Byte offset at which to write */
50810 ){
50811   int rc;                         /* Result code from subfunctions */
50812   void *pData;                    /* Data actually written */
50813   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
50814 #if defined(SQLITE_HAS_CODEC)
50815   if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
50816 #else
50817   pData = pPage->pData;
50818 #endif
50819   walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
50820   rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
50821   if( rc ) return rc;
50822   /* Write the page data */
50823   rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
50824   return rc;
50825 }
50826 
50827 /*
50828 ** Write a set of frames to the log. The caller must hold the write-lock
50829 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
50830 */
50831 SQLITE_PRIVATE int sqlite3WalFrames(
50832   Wal *pWal,                      /* Wal handle to write to */
50833   int szPage,                     /* Database page-size in bytes */
50834   PgHdr *pList,                   /* List of dirty pages to write */
50835   Pgno nTruncate,                 /* Database size after this commit */
50836   int isCommit,                   /* True if this is a commit */
50837   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
50838 ){
50839   int rc;                         /* Used to catch return codes */
50840   u32 iFrame;                     /* Next frame address */
50841   PgHdr *p;                       /* Iterator to run through pList with. */
50842   PgHdr *pLast = 0;               /* Last frame in list */
50843   int nExtra = 0;                 /* Number of extra copies of last page */
50844   int szFrame;                    /* The size of a single frame */
50845   i64 iOffset;                    /* Next byte to write in WAL file */
50846   WalWriter w;                    /* The writer */
50847 
50848   assert( pList );
50849   assert( pWal->writeLock );
50850 
50851   /* If this frame set completes a transaction, then nTruncate>0.  If
50852   ** nTruncate==0 then this frame set does not complete the transaction. */
50853   assert( (isCommit!=0)==(nTruncate!=0) );
50854 
50855 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
50856   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
50857     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
50858               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
50859   }
50860 #endif
50861 
50862   /* See if it is possible to write these frames into the start of the
50863   ** log file, instead of appending to it at pWal->hdr.mxFrame.
50864   */
50865   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
50866     return rc;
50867   }
50868 
50869   /* If this is the first frame written into the log, write the WAL
50870   ** header to the start of the WAL file. See comments at the top of
50871   ** this source file for a description of the WAL header format.
50872   */
50873   iFrame = pWal->hdr.mxFrame;
50874   if( iFrame==0 ){
50875     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
50876     u32 aCksum[2];                /* Checksum for wal-header */
50877 
50878     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
50879     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
50880     sqlite3Put4byte(&aWalHdr[8], szPage);
50881     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
50882     if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
50883     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
50884     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
50885     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
50886     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
50887 
50888     pWal->szPage = szPage;
50889     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
50890     pWal->hdr.aFrameCksum[0] = aCksum[0];
50891     pWal->hdr.aFrameCksum[1] = aCksum[1];
50892     pWal->truncateOnCommit = 1;
50893 
50894     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
50895     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
50896     if( rc!=SQLITE_OK ){
50897       return rc;
50898     }
50899 
50900     /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
50901     ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
50902     ** an out-of-order write following a WAL restart could result in
50903     ** database corruption.  See the ticket:
50904     **
50905     **     http://localhost:591/sqlite/info/ff5be73dee
50906     */
50907     if( pWal->syncHeader && sync_flags ){
50908       rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
50909       if( rc ) return rc;
50910     }
50911   }
50912   assert( (int)pWal->szPage==szPage );
50913 
50914   /* Setup information needed to write frames into the WAL */
50915   w.pWal = pWal;
50916   w.pFd = pWal->pWalFd;
50917   w.iSyncPoint = 0;
50918   w.syncFlags = sync_flags;
50919   w.szPage = szPage;
50920   iOffset = walFrameOffset(iFrame+1, szPage);
50921   szFrame = szPage + WAL_FRAME_HDRSIZE;
50922 
50923   /* Write all frames into the log file exactly once */
50924   for(p=pList; p; p=p->pDirty){
50925     int nDbSize;   /* 0 normally.  Positive == commit flag */
50926     iFrame++;
50927     assert( iOffset==walFrameOffset(iFrame, szPage) );
50928     nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
50929     rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
50930     if( rc ) return rc;
50931     pLast = p;
50932     iOffset += szFrame;
50933   }
50934 
50935   /* If this is the end of a transaction, then we might need to pad
50936   ** the transaction and/or sync the WAL file.
50937   **
50938   ** Padding and syncing only occur if this set of frames complete a
50939   ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
50940   ** or synchronous==OFF, then no padding or syncing are needed.
50941   **
50942   ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
50943   ** needed and only the sync is done.  If padding is needed, then the
50944   ** final frame is repeated (with its commit mark) until the next sector
50945   ** boundary is crossed.  Only the part of the WAL prior to the last
50946   ** sector boundary is synced; the part of the last frame that extends
50947   ** past the sector boundary is written after the sync.
50948   */
50949   if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
50950     if( pWal->padToSectorBoundary ){
50951       int sectorSize = sqlite3SectorSize(pWal->pWalFd);
50952       w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
50953       while( iOffset<w.iSyncPoint ){
50954         rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
50955         if( rc ) return rc;
50956         iOffset += szFrame;
50957         nExtra++;
50958       }
50959     }else{
50960       rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
50961     }
50962   }
50963 
50964   /* If this frame set completes the first transaction in the WAL and
50965   ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
50966   ** journal size limit, if possible.
50967   */
50968   if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
50969     i64 sz = pWal->mxWalSize;
50970     if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
50971       sz = walFrameOffset(iFrame+nExtra+1, szPage);
50972     }
50973     walLimitSize(pWal, sz);
50974     pWal->truncateOnCommit = 0;
50975   }
50976 
50977   /* Append data to the wal-index. It is not necessary to lock the
50978   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
50979   ** guarantees that there are no other writers, and no data that may
50980   ** be in use by existing readers is being overwritten.
50981   */
50982   iFrame = pWal->hdr.mxFrame;
50983   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
50984     iFrame++;
50985     rc = walIndexAppend(pWal, iFrame, p->pgno);
50986   }
50987   while( rc==SQLITE_OK && nExtra>0 ){
50988     iFrame++;
50989     nExtra--;
50990     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
50991   }
50992 
50993   if( rc==SQLITE_OK ){
50994     /* Update the private copy of the header. */
50995     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
50996     testcase( szPage<=32768 );
50997     testcase( szPage>=65536 );
50998     pWal->hdr.mxFrame = iFrame;
50999     if( isCommit ){
51000       pWal->hdr.iChange++;
51001       pWal->hdr.nPage = nTruncate;
51002     }
51003     /* If this is a commit, update the wal-index header too. */
51004     if( isCommit ){
51005       walIndexWriteHdr(pWal);
51006       pWal->iCallback = iFrame;
51007     }
51008   }
51009 
51010   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
51011   return rc;
51012 }
51013 
51014 /*
51015 ** This routine is called to implement sqlite3_wal_checkpoint() and
51016 ** related interfaces.
51017 **
51018 ** Obtain a CHECKPOINT lock and then backfill as much information as
51019 ** we can from WAL into the database.
51020 **
51021 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
51022 ** callback. In this case this function runs a blocking checkpoint.
51023 */
51024 SQLITE_PRIVATE int sqlite3WalCheckpoint(
51025   Wal *pWal,                      /* Wal connection */
51026   int eMode,                      /* PASSIVE, FULL or RESTART */
51027   int (*xBusy)(void*),            /* Function to call when busy */
51028   void *pBusyArg,                 /* Context argument for xBusyHandler */
51029   int sync_flags,                 /* Flags to sync db file with (or 0) */
51030   int nBuf,                       /* Size of temporary buffer */
51031   u8 *zBuf,                       /* Temporary buffer to use */
51032   int *pnLog,                     /* OUT: Number of frames in WAL */
51033   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
51034 ){
51035   int rc;                         /* Return code */
51036   int isChanged = 0;              /* True if a new wal-index header is loaded */
51037   int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
51038 
51039   assert( pWal->ckptLock==0 );
51040   assert( pWal->writeLock==0 );
51041 
51042   if( pWal->readOnly ) return SQLITE_READONLY;
51043   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
51044   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
51045   if( rc ){
51046     /* Usually this is SQLITE_BUSY meaning that another thread or process
51047     ** is already running a checkpoint, or maybe a recovery.  But it might
51048     ** also be SQLITE_IOERR. */
51049     return rc;
51050   }
51051   pWal->ckptLock = 1;
51052 
51053   /* If this is a blocking-checkpoint, then obtain the write-lock as well
51054   ** to prevent any writers from running while the checkpoint is underway.
51055   ** This has to be done before the call to walIndexReadHdr() below.
51056   **
51057   ** If the writer lock cannot be obtained, then a passive checkpoint is
51058   ** run instead. Since the checkpointer is not holding the writer lock,
51059   ** there is no point in blocking waiting for any readers. Assuming no
51060   ** other error occurs, this function will return SQLITE_BUSY to the caller.
51061   */
51062   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
51063     rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
51064     if( rc==SQLITE_OK ){
51065       pWal->writeLock = 1;
51066     }else if( rc==SQLITE_BUSY ){
51067       eMode2 = SQLITE_CHECKPOINT_PASSIVE;
51068       rc = SQLITE_OK;
51069     }
51070   }
51071 
51072   /* Read the wal-index header. */
51073   if( rc==SQLITE_OK ){
51074     rc = walIndexReadHdr(pWal, &isChanged);
51075     if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
51076       sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
51077     }
51078   }
51079 
51080   /* Copy data from the log to the database file. */
51081   if( rc==SQLITE_OK ){
51082     if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
51083       rc = SQLITE_CORRUPT_BKPT;
51084     }else{
51085       rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
51086     }
51087 
51088     /* If no error occurred, set the output variables. */
51089     if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
51090       if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
51091       if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
51092     }
51093   }
51094 
51095   if( isChanged ){
51096     /* If a new wal-index header was loaded before the checkpoint was
51097     ** performed, then the pager-cache associated with pWal is now
51098     ** out of date. So zero the cached wal-index header to ensure that
51099     ** next time the pager opens a snapshot on this database it knows that
51100     ** the cache needs to be reset.
51101     */
51102     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
51103   }
51104 
51105   /* Release the locks. */
51106   sqlite3WalEndWriteTransaction(pWal);
51107   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
51108   pWal->ckptLock = 0;
51109   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
51110   return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
51111 }
51112 
51113 /* Return the value to pass to a sqlite3_wal_hook callback, the
51114 ** number of frames in the WAL at the point of the last commit since
51115 ** sqlite3WalCallback() was called.  If no commits have occurred since
51116 ** the last call, then return 0.
51117 */
51118 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
51119   u32 ret = 0;
51120   if( pWal ){
51121     ret = pWal->iCallback;
51122     pWal->iCallback = 0;
51123   }
51124   return (int)ret;
51125 }
51126 
51127 /*
51128 ** This function is called to change the WAL subsystem into or out
51129 ** of locking_mode=EXCLUSIVE.
51130 **
51131 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
51132 ** into locking_mode=NORMAL.  This means that we must acquire a lock
51133 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
51134 ** or if the acquisition of the lock fails, then return 0.  If the
51135 ** transition out of exclusive-mode is successful, return 1.  This
51136 ** operation must occur while the pager is still holding the exclusive
51137 ** lock on the main database file.
51138 **
51139 ** If op is one, then change from locking_mode=NORMAL into
51140 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
51141 ** be released.  Return 1 if the transition is made and 0 if the
51142 ** WAL is already in exclusive-locking mode - meaning that this
51143 ** routine is a no-op.  The pager must already hold the exclusive lock
51144 ** on the main database file before invoking this operation.
51145 **
51146 ** If op is negative, then do a dry-run of the op==1 case but do
51147 ** not actually change anything. The pager uses this to see if it
51148 ** should acquire the database exclusive lock prior to invoking
51149 ** the op==1 case.
51150 */
51151 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
51152   int rc;
51153   assert( pWal->writeLock==0 );
51154   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
51155 
51156   /* pWal->readLock is usually set, but might be -1 if there was a
51157   ** prior error while attempting to acquire are read-lock. This cannot
51158   ** happen if the connection is actually in exclusive mode (as no xShmLock
51159   ** locks are taken in this case). Nor should the pager attempt to
51160   ** upgrade to exclusive-mode following such an error.
51161   */
51162   assert( pWal->readLock>=0 || pWal->lockError );
51163   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
51164 
51165   if( op==0 ){
51166     if( pWal->exclusiveMode ){
51167       pWal->exclusiveMode = 0;
51168       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
51169         pWal->exclusiveMode = 1;
51170       }
51171       rc = pWal->exclusiveMode==0;
51172     }else{
51173       /* Already in locking_mode=NORMAL */
51174       rc = 0;
51175     }
51176   }else if( op>0 ){
51177     assert( pWal->exclusiveMode==0 );
51178     assert( pWal->readLock>=0 );
51179     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
51180     pWal->exclusiveMode = 1;
51181     rc = 1;
51182   }else{
51183     rc = pWal->exclusiveMode==0;
51184   }
51185   return rc;
51186 }
51187 
51188 /*
51189 ** Return true if the argument is non-NULL and the WAL module is using
51190 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
51191 ** WAL module is using shared-memory, return false.
51192 */
51193 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
51194   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
51195 }
51196 
51197 #ifdef SQLITE_ENABLE_ZIPVFS
51198 /*
51199 ** If the argument is not NULL, it points to a Wal object that holds a
51200 ** read-lock. This function returns the database page-size if it is known,
51201 ** or zero if it is not (or if pWal is NULL).
51202 */
51203 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
51204   assert( pWal==0 || pWal->readLock>=0 );
51205   return (pWal ? pWal->szPage : 0);
51206 }
51207 #endif
51208 
51209 #endif /* #ifndef SQLITE_OMIT_WAL */
51210 
51211 /************** End of wal.c *************************************************/
51212 /************** Begin file btmutex.c *****************************************/
51213 /*
51214 ** 2007 August 27
51215 **
51216 ** The author disclaims copyright to this source code.  In place of
51217 ** a legal notice, here is a blessing:
51218 **
51219 **    May you do good and not evil.
51220 **    May you find forgiveness for yourself and forgive others.
51221 **    May you share freely, never taking more than you give.
51222 **
51223 *************************************************************************
51224 **
51225 ** This file contains code used to implement mutexes on Btree objects.
51226 ** This code really belongs in btree.c.  But btree.c is getting too
51227 ** big and we want to break it down some.  This packaged seemed like
51228 ** a good breakout.
51229 */
51230 /************** Include btreeInt.h in the middle of btmutex.c ****************/
51231 /************** Begin file btreeInt.h ****************************************/
51232 /*
51233 ** 2004 April 6
51234 **
51235 ** The author disclaims copyright to this source code.  In place of
51236 ** a legal notice, here is a blessing:
51237 **
51238 **    May you do good and not evil.
51239 **    May you find forgiveness for yourself and forgive others.
51240 **    May you share freely, never taking more than you give.
51241 **
51242 *************************************************************************
51243 ** This file implements an external (disk-based) database using BTrees.
51244 ** For a detailed discussion of BTrees, refer to
51245 **
51246 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
51247 **     "Sorting And Searching", pages 473-480. Addison-Wesley
51248 **     Publishing Company, Reading, Massachusetts.
51249 **
51250 ** The basic idea is that each page of the file contains N database
51251 ** entries and N+1 pointers to subpages.
51252 **
51253 **   ----------------------------------------------------------------
51254 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
51255 **   ----------------------------------------------------------------
51256 **
51257 ** All of the keys on the page that Ptr(0) points to have values less
51258 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
51259 ** values greater than Key(0) and less than Key(1).  All of the keys
51260 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
51261 ** so forth.
51262 **
51263 ** Finding a particular key requires reading O(log(M)) pages from the
51264 ** disk where M is the number of entries in the tree.
51265 **
51266 ** In this implementation, a single file can hold one or more separate
51267 ** BTrees.  Each BTree is identified by the index of its root page.  The
51268 ** key and data for any entry are combined to form the "payload".  A
51269 ** fixed amount of payload can be carried directly on the database
51270 ** page.  If the payload is larger than the preset amount then surplus
51271 ** bytes are stored on overflow pages.  The payload for an entry
51272 ** and the preceding pointer are combined to form a "Cell".  Each
51273 ** page has a small header which contains the Ptr(N) pointer and other
51274 ** information such as the size of key and data.
51275 **
51276 ** FORMAT DETAILS
51277 **
51278 ** The file is divided into pages.  The first page is called page 1,
51279 ** the second is page 2, and so forth.  A page number of zero indicates
51280 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
51281 ** Each page can be either a btree page, a freelist page, an overflow
51282 ** page, or a pointer-map page.
51283 **
51284 ** The first page is always a btree page.  The first 100 bytes of the first
51285 ** page contain a special header (the "file header") that describes the file.
51286 ** The format of the file header is as follows:
51287 **
51288 **   OFFSET   SIZE    DESCRIPTION
51289 **      0      16     Header string: "SQLite format 3\000"
51290 **     16       2     Page size in bytes.  (1 means 65536)
51291 **     18       1     File format write version
51292 **     19       1     File format read version
51293 **     20       1     Bytes of unused space at the end of each page
51294 **     21       1     Max embedded payload fraction (must be 64)
51295 **     22       1     Min embedded payload fraction (must be 32)
51296 **     23       1     Min leaf payload fraction (must be 32)
51297 **     24       4     File change counter
51298 **     28       4     Reserved for future use
51299 **     32       4     First freelist page
51300 **     36       4     Number of freelist pages in the file
51301 **     40      60     15 4-byte meta values passed to higher layers
51302 **
51303 **     40       4     Schema cookie
51304 **     44       4     File format of schema layer
51305 **     48       4     Size of page cache
51306 **     52       4     Largest root-page (auto/incr_vacuum)
51307 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
51308 **     60       4     User version
51309 **     64       4     Incremental vacuum mode
51310 **     68       4     Application-ID
51311 **     72      20     unused
51312 **     92       4     The version-valid-for number
51313 **     96       4     SQLITE_VERSION_NUMBER
51314 **
51315 ** All of the integer values are big-endian (most significant byte first).
51316 **
51317 ** The file change counter is incremented when the database is changed
51318 ** This counter allows other processes to know when the file has changed
51319 ** and thus when they need to flush their cache.
51320 **
51321 ** The max embedded payload fraction is the amount of the total usable
51322 ** space in a page that can be consumed by a single cell for standard
51323 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
51324 ** is to limit the maximum cell size so that at least 4 cells will fit
51325 ** on one page.  Thus the default max embedded payload fraction is 64.
51326 **
51327 ** If the payload for a cell is larger than the max payload, then extra
51328 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
51329 ** as many bytes as possible are moved into the overflow pages without letting
51330 ** the cell size drop below the min embedded payload fraction.
51331 **
51332 ** The min leaf payload fraction is like the min embedded payload fraction
51333 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
51334 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
51335 ** not specified in the header.
51336 **
51337 ** Each btree pages is divided into three sections:  The header, the
51338 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
51339 ** file header that occurs before the page header.
51340 **
51341 **      |----------------|
51342 **      | file header    |   100 bytes.  Page 1 only.
51343 **      |----------------|
51344 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
51345 **      |----------------|
51346 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
51347 **      | array          |   |  Grows downward
51348 **      |                |   v
51349 **      |----------------|
51350 **      | unallocated    |
51351 **      | space          |
51352 **      |----------------|   ^  Grows upwards
51353 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
51354 **      | area           |   |  and free space fragments.
51355 **      |----------------|
51356 **
51357 ** The page headers looks like this:
51358 **
51359 **   OFFSET   SIZE     DESCRIPTION
51360 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
51361 **      1       2      byte offset to the first freeblock
51362 **      3       2      number of cells on this page
51363 **      5       2      first byte of the cell content area
51364 **      7       1      number of fragmented free bytes
51365 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
51366 **
51367 ** The flags define the format of this btree page.  The leaf flag means that
51368 ** this page has no children.  The zerodata flag means that this page carries
51369 ** only keys and no data.  The intkey flag means that the key is an integer
51370 ** which is stored in the key size entry of the cell header rather than in
51371 ** the payload area.
51372 **
51373 ** The cell pointer array begins on the first byte after the page header.
51374 ** The cell pointer array contains zero or more 2-byte numbers which are
51375 ** offsets from the beginning of the page to the cell content in the cell
51376 ** content area.  The cell pointers occur in sorted order.  The system strives
51377 ** to keep free space after the last cell pointer so that new cells can
51378 ** be easily added without having to defragment the page.
51379 **
51380 ** Cell content is stored at the very end of the page and grows toward the
51381 ** beginning of the page.
51382 **
51383 ** Unused space within the cell content area is collected into a linked list of
51384 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
51385 ** to the first freeblock is given in the header.  Freeblocks occur in
51386 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
51387 ** any group of 3 or fewer unused bytes in the cell content area cannot
51388 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
51389 ** a fragment.  The total number of bytes in all fragments is recorded.
51390 ** in the page header at offset 7.
51391 **
51392 **    SIZE    DESCRIPTION
51393 **      2     Byte offset of the next freeblock
51394 **      2     Bytes in this freeblock
51395 **
51396 ** Cells are of variable length.  Cells are stored in the cell content area at
51397 ** the end of the page.  Pointers to the cells are in the cell pointer array
51398 ** that immediately follows the page header.  Cells is not necessarily
51399 ** contiguous or in order, but cell pointers are contiguous and in order.
51400 **
51401 ** Cell content makes use of variable length integers.  A variable
51402 ** length integer is 1 to 9 bytes where the lower 7 bits of each
51403 ** byte are used.  The integer consists of all bytes that have bit 8 set and
51404 ** the first byte with bit 8 clear.  The most significant byte of the integer
51405 ** appears first.  A variable-length integer may not be more than 9 bytes long.
51406 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
51407 ** allows a 64-bit integer to be encoded in 9 bytes.
51408 **
51409 **    0x00                      becomes  0x00000000
51410 **    0x7f                      becomes  0x0000007f
51411 **    0x81 0x00                 becomes  0x00000080
51412 **    0x82 0x00                 becomes  0x00000100
51413 **    0x80 0x7f                 becomes  0x0000007f
51414 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
51415 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
51416 **
51417 ** Variable length integers are used for rowids and to hold the number of
51418 ** bytes of key and data in a btree cell.
51419 **
51420 ** The content of a cell looks like this:
51421 **
51422 **    SIZE    DESCRIPTION
51423 **      4     Page number of the left child. Omitted if leaf flag is set.
51424 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
51425 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
51426 **      *     Payload
51427 **      4     First page of the overflow chain.  Omitted if no overflow
51428 **
51429 ** Overflow pages form a linked list.  Each page except the last is completely
51430 ** filled with data (pagesize - 4 bytes).  The last page can have as little
51431 ** as 1 byte of data.
51432 **
51433 **    SIZE    DESCRIPTION
51434 **      4     Page number of next overflow page
51435 **      *     Data
51436 **
51437 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
51438 ** file header points to the first in a linked list of trunk page.  Each trunk
51439 ** page points to multiple leaf pages.  The content of a leaf page is
51440 ** unspecified.  A trunk page looks like this:
51441 **
51442 **    SIZE    DESCRIPTION
51443 **      4     Page number of next trunk page
51444 **      4     Number of leaf pointers on this page
51445 **      *     zero or more pages numbers of leaves
51446 */
51447 
51448 
51449 /* The following value is the maximum cell size assuming a maximum page
51450 ** size give above.
51451 */
51452 #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
51453 
51454 /* The maximum number of cells on a single page of the database.  This
51455 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
51456 ** plus 2 bytes for the index to the cell in the page header).  Such
51457 ** small cells will be rare, but they are possible.
51458 */
51459 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
51460 
51461 /* Forward declarations */
51462 typedef struct MemPage MemPage;
51463 typedef struct BtLock BtLock;
51464 
51465 /*
51466 ** This is a magic string that appears at the beginning of every
51467 ** SQLite database in order to identify the file as a real database.
51468 **
51469 ** You can change this value at compile-time by specifying a
51470 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
51471 ** header must be exactly 16 bytes including the zero-terminator so
51472 ** the string itself should be 15 characters long.  If you change
51473 ** the header, then your custom library will not be able to read
51474 ** databases generated by the standard tools and the standard tools
51475 ** will not be able to read databases created by your custom library.
51476 */
51477 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
51478 #  define SQLITE_FILE_HEADER "SQLite format 3"
51479 #endif
51480 
51481 /*
51482 ** Page type flags.  An ORed combination of these flags appear as the
51483 ** first byte of on-disk image of every BTree page.
51484 */
51485 #define PTF_INTKEY    0x01
51486 #define PTF_ZERODATA  0x02
51487 #define PTF_LEAFDATA  0x04
51488 #define PTF_LEAF      0x08
51489 
51490 /*
51491 ** As each page of the file is loaded into memory, an instance of the following
51492 ** structure is appended and initialized to zero.  This structure stores
51493 ** information about the page that is decoded from the raw file page.
51494 **
51495 ** The pParent field points back to the parent page.  This allows us to
51496 ** walk up the BTree from any leaf to the root.  Care must be taken to
51497 ** unref() the parent page pointer when this page is no longer referenced.
51498 ** The pageDestructor() routine handles that chore.
51499 **
51500 ** Access to all fields of this structure is controlled by the mutex
51501 ** stored in MemPage.pBt->mutex.
51502 */
51503 struct MemPage {
51504   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
51505   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
51506   u8 intKey;           /* True if table b-trees.  False for index b-trees */
51507   u8 intKeyLeaf;       /* True if the leaf of an intKey table */
51508   u8 noPayload;        /* True if internal intKey page (thus w/o data) */
51509   u8 leaf;             /* True if a leaf page */
51510   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
51511   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
51512   u8 max1bytePayload;  /* min(maxLocal,127) */
51513   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
51514   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
51515   u16 cellOffset;      /* Index in aData of first cell pointer */
51516   u16 nFree;           /* Number of free bytes on the page */
51517   u16 nCell;           /* Number of cells on this page, local and ovfl */
51518   u16 maskPage;        /* Mask for page offset */
51519   u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
51520                        ** non-overflow cell */
51521   u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
51522   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
51523   u8 *aData;           /* Pointer to disk image of the page data */
51524   u8 *aDataEnd;        /* One byte past the end of usable data */
51525   u8 *aCellIdx;        /* The cell index area */
51526   DbPage *pDbPage;     /* Pager page handle */
51527   Pgno pgno;           /* Page number for this page */
51528 };
51529 
51530 /*
51531 ** The in-memory image of a disk page has the auxiliary information appended
51532 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
51533 ** that extra information.
51534 */
51535 #define EXTRA_SIZE sizeof(MemPage)
51536 
51537 /*
51538 ** A linked list of the following structures is stored at BtShared.pLock.
51539 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
51540 ** is opened on the table with root page BtShared.iTable. Locks are removed
51541 ** from this list when a transaction is committed or rolled back, or when
51542 ** a btree handle is closed.
51543 */
51544 struct BtLock {
51545   Btree *pBtree;        /* Btree handle holding this lock */
51546   Pgno iTable;          /* Root page of table */
51547   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
51548   BtLock *pNext;        /* Next in BtShared.pLock list */
51549 };
51550 
51551 /* Candidate values for BtLock.eLock */
51552 #define READ_LOCK     1
51553 #define WRITE_LOCK    2
51554 
51555 /* A Btree handle
51556 **
51557 ** A database connection contains a pointer to an instance of
51558 ** this object for every database file that it has open.  This structure
51559 ** is opaque to the database connection.  The database connection cannot
51560 ** see the internals of this structure and only deals with pointers to
51561 ** this structure.
51562 **
51563 ** For some database files, the same underlying database cache might be
51564 ** shared between multiple connections.  In that case, each connection
51565 ** has it own instance of this object.  But each instance of this object
51566 ** points to the same BtShared object.  The database cache and the
51567 ** schema associated with the database file are all contained within
51568 ** the BtShared object.
51569 **
51570 ** All fields in this structure are accessed under sqlite3.mutex.
51571 ** The pBt pointer itself may not be changed while there exists cursors
51572 ** in the referenced BtShared that point back to this Btree since those
51573 ** cursors have to go through this Btree to find their BtShared and
51574 ** they often do so without holding sqlite3.mutex.
51575 */
51576 struct Btree {
51577   sqlite3 *db;       /* The database connection holding this btree */
51578   BtShared *pBt;     /* Sharable content of this btree */
51579   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
51580   u8 sharable;       /* True if we can share pBt with another db */
51581   u8 locked;         /* True if db currently has pBt locked */
51582   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
51583   int nBackup;       /* Number of backup operations reading this btree */
51584   Btree *pNext;      /* List of other sharable Btrees from the same db */
51585   Btree *pPrev;      /* Back pointer of the same list */
51586 #ifndef SQLITE_OMIT_SHARED_CACHE
51587   BtLock lock;       /* Object used to lock page 1 */
51588 #endif
51589 };
51590 
51591 /*
51592 ** Btree.inTrans may take one of the following values.
51593 **
51594 ** If the shared-data extension is enabled, there may be multiple users
51595 ** of the Btree structure. At most one of these may open a write transaction,
51596 ** but any number may have active read transactions.
51597 */
51598 #define TRANS_NONE  0
51599 #define TRANS_READ  1
51600 #define TRANS_WRITE 2
51601 
51602 /*
51603 ** An instance of this object represents a single database file.
51604 **
51605 ** A single database file can be in use at the same time by two
51606 ** or more database connections.  When two or more connections are
51607 ** sharing the same database file, each connection has it own
51608 ** private Btree object for the file and each of those Btrees points
51609 ** to this one BtShared object.  BtShared.nRef is the number of
51610 ** connections currently sharing this database file.
51611 **
51612 ** Fields in this structure are accessed under the BtShared.mutex
51613 ** mutex, except for nRef and pNext which are accessed under the
51614 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
51615 ** may not be modified once it is initially set as long as nRef>0.
51616 ** The pSchema field may be set once under BtShared.mutex and
51617 ** thereafter is unchanged as long as nRef>0.
51618 **
51619 ** isPending:
51620 **
51621 **   If a BtShared client fails to obtain a write-lock on a database
51622 **   table (because there exists one or more read-locks on the table),
51623 **   the shared-cache enters 'pending-lock' state and isPending is
51624 **   set to true.
51625 **
51626 **   The shared-cache leaves the 'pending lock' state when either of
51627 **   the following occur:
51628 **
51629 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
51630 **     2) The number of locks held by other connections drops to zero.
51631 **
51632 **   while in the 'pending-lock' state, no connection may start a new
51633 **   transaction.
51634 **
51635 **   This feature is included to help prevent writer-starvation.
51636 */
51637 struct BtShared {
51638   Pager *pPager;        /* The page cache */
51639   sqlite3 *db;          /* Database connection currently using this Btree */
51640   BtCursor *pCursor;    /* A list of all open cursors */
51641   MemPage *pPage1;      /* First page of the database */
51642   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
51643 #ifndef SQLITE_OMIT_AUTOVACUUM
51644   u8 autoVacuum;        /* True if auto-vacuum is enabled */
51645   u8 incrVacuum;        /* True if incr-vacuum is enabled */
51646   u8 bDoTruncate;       /* True to truncate db on commit */
51647 #endif
51648   u8 inTransaction;     /* Transaction state */
51649   u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
51650   u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
51651   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
51652   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
51653   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
51654   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
51655   u32 pageSize;         /* Total number of bytes on a page */
51656   u32 usableSize;       /* Number of usable bytes on each page */
51657   int nTransaction;     /* Number of open transactions (read + write) */
51658   u32 nPage;            /* Number of pages in the database */
51659   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
51660   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
51661   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
51662   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
51663 #ifndef SQLITE_OMIT_SHARED_CACHE
51664   int nRef;             /* Number of references to this structure */
51665   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
51666   BtLock *pLock;        /* List of locks held on this shared-btree struct */
51667   Btree *pWriter;       /* Btree with currently open write transaction */
51668 #endif
51669   u8 *pTmpSpace;        /* Temp space sufficient to hold a single cell */
51670 };
51671 
51672 /*
51673 ** Allowed values for BtShared.btsFlags
51674 */
51675 #define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
51676 #define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
51677 #define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
51678 #define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
51679 #define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
51680 #define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
51681 #define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
51682 
51683 /*
51684 ** An instance of the following structure is used to hold information
51685 ** about a cell.  The parseCellPtr() function fills in this structure
51686 ** based on information extract from the raw disk page.
51687 */
51688 typedef struct CellInfo CellInfo;
51689 struct CellInfo {
51690   i64 nKey;      /* The key for INTKEY tables, or nPayload otherwise */
51691   u8 *pPayload;  /* Pointer to the start of payload */
51692   u32 nPayload;  /* Bytes of payload */
51693   u16 nLocal;    /* Amount of payload held locally, not on overflow */
51694   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
51695   u16 nSize;     /* Size of the cell content on the main b-tree page */
51696 };
51697 
51698 /*
51699 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
51700 ** this will be declared corrupt. This value is calculated based on a
51701 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
51702 ** root-node and 3 for all other internal nodes.
51703 **
51704 ** If a tree that appears to be taller than this is encountered, it is
51705 ** assumed that the database is corrupt.
51706 */
51707 #define BTCURSOR_MAX_DEPTH 20
51708 
51709 /*
51710 ** A cursor is a pointer to a particular entry within a particular
51711 ** b-tree within a database file.
51712 **
51713 ** The entry is identified by its MemPage and the index in
51714 ** MemPage.aCell[] of the entry.
51715 **
51716 ** A single database file can be shared by two more database connections,
51717 ** but cursors cannot be shared.  Each cursor is associated with a
51718 ** particular database connection identified BtCursor.pBtree.db.
51719 **
51720 ** Fields in this structure are accessed under the BtShared.mutex
51721 ** found at self->pBt->mutex.
51722 **
51723 ** skipNext meaning:
51724 **    eState==SKIPNEXT && skipNext>0:  Next sqlite3BtreeNext() is no-op.
51725 **    eState==SKIPNEXT && skipNext<0:  Next sqlite3BtreePrevious() is no-op.
51726 **    eState==FAULT:                   Cursor fault with skipNext as error code.
51727 */
51728 struct BtCursor {
51729   Btree *pBtree;            /* The Btree to which this cursor belongs */
51730   BtShared *pBt;            /* The BtShared this cursor points to */
51731   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
51732   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
51733   Pgno *aOverflow;          /* Cache of overflow page locations */
51734   CellInfo info;            /* A parse of the cell we are pointing at */
51735   i64 nKey;                 /* Size of pKey, or last integer key */
51736   void *pKey;               /* Saved key that was cursor last known position */
51737   Pgno pgnoRoot;            /* The root page of this tree */
51738   int nOvflAlloc;           /* Allocated size of aOverflow[] array */
51739   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive.
51740                    ** Error code if eState==CURSOR_FAULT */
51741   u8 curFlags;              /* zero or more BTCF_* flags defined below */
51742   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
51743   u8 hints;                             /* As configured by CursorSetHints() */
51744   i16 iPage;                            /* Index of current page in apPage */
51745   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
51746   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
51747 };
51748 
51749 /*
51750 ** Legal values for BtCursor.curFlags
51751 */
51752 #define BTCF_WriteFlag    0x01   /* True if a write cursor */
51753 #define BTCF_ValidNKey    0x02   /* True if info.nKey is valid */
51754 #define BTCF_ValidOvfl    0x04   /* True if aOverflow is valid */
51755 #define BTCF_AtLast       0x08   /* Cursor is pointing ot the last entry */
51756 #define BTCF_Incrblob     0x10   /* True if an incremental I/O handle */
51757 
51758 /*
51759 ** Potential values for BtCursor.eState.
51760 **
51761 ** CURSOR_INVALID:
51762 **   Cursor does not point to a valid entry. This can happen (for example)
51763 **   because the table is empty or because BtreeCursorFirst() has not been
51764 **   called.
51765 **
51766 ** CURSOR_VALID:
51767 **   Cursor points to a valid entry. getPayload() etc. may be called.
51768 **
51769 ** CURSOR_SKIPNEXT:
51770 **   Cursor is valid except that the Cursor.skipNext field is non-zero
51771 **   indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
51772 **   operation should be a no-op.
51773 **
51774 ** CURSOR_REQUIRESEEK:
51775 **   The table that this cursor was opened on still exists, but has been
51776 **   modified since the cursor was last used. The cursor position is saved
51777 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
51778 **   this state, restoreCursorPosition() can be called to attempt to
51779 **   seek the cursor to the saved position.
51780 **
51781 ** CURSOR_FAULT:
51782 **   An unrecoverable error (an I/O error or a malloc failure) has occurred
51783 **   on a different connection that shares the BtShared cache with this
51784 **   cursor.  The error has left the cache in an inconsistent state.
51785 **   Do nothing else with this cursor.  Any attempt to use the cursor
51786 **   should return the error code stored in BtCursor.skipNext
51787 */
51788 #define CURSOR_INVALID           0
51789 #define CURSOR_VALID             1
51790 #define CURSOR_SKIPNEXT          2
51791 #define CURSOR_REQUIRESEEK       3
51792 #define CURSOR_FAULT             4
51793 
51794 /*
51795 ** The database page the PENDING_BYTE occupies. This page is never used.
51796 */
51797 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
51798 
51799 /*
51800 ** These macros define the location of the pointer-map entry for a
51801 ** database page. The first argument to each is the number of usable
51802 ** bytes on each page of the database (often 1024). The second is the
51803 ** page number to look up in the pointer map.
51804 **
51805 ** PTRMAP_PAGENO returns the database page number of the pointer-map
51806 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
51807 ** the offset of the requested map entry.
51808 **
51809 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
51810 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
51811 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
51812 ** this test.
51813 */
51814 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
51815 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
51816 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
51817 
51818 /*
51819 ** The pointer map is a lookup table that identifies the parent page for
51820 ** each child page in the database file.  The parent page is the page that
51821 ** contains a pointer to the child.  Every page in the database contains
51822 ** 0 or 1 parent pages.  (In this context 'database page' refers
51823 ** to any page that is not part of the pointer map itself.)  Each pointer map
51824 ** entry consists of a single byte 'type' and a 4 byte parent page number.
51825 ** The PTRMAP_XXX identifiers below are the valid types.
51826 **
51827 ** The purpose of the pointer map is to facility moving pages from one
51828 ** position in the file to another as part of autovacuum.  When a page
51829 ** is moved, the pointer in its parent must be updated to point to the
51830 ** new location.  The pointer map is used to locate the parent page quickly.
51831 **
51832 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
51833 **                  used in this case.
51834 **
51835 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
51836 **                  is not used in this case.
51837 **
51838 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
51839 **                   overflow pages. The page number identifies the page that
51840 **                   contains the cell with a pointer to this overflow page.
51841 **
51842 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
51843 **                   overflow pages. The page-number identifies the previous
51844 **                   page in the overflow page list.
51845 **
51846 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
51847 **               identifies the parent page in the btree.
51848 */
51849 #define PTRMAP_ROOTPAGE 1
51850 #define PTRMAP_FREEPAGE 2
51851 #define PTRMAP_OVERFLOW1 3
51852 #define PTRMAP_OVERFLOW2 4
51853 #define PTRMAP_BTREE 5
51854 
51855 /* A bunch of assert() statements to check the transaction state variables
51856 ** of handle p (type Btree*) are internally consistent.
51857 */
51858 #define btreeIntegrity(p) \
51859   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
51860   assert( p->pBt->inTransaction>=p->inTrans );
51861 
51862 
51863 /*
51864 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
51865 ** if the database supports auto-vacuum or not. Because it is used
51866 ** within an expression that is an argument to another macro
51867 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
51868 ** So, this macro is defined instead.
51869 */
51870 #ifndef SQLITE_OMIT_AUTOVACUUM
51871 #define ISAUTOVACUUM (pBt->autoVacuum)
51872 #else
51873 #define ISAUTOVACUUM 0
51874 #endif
51875 
51876 
51877 /*
51878 ** This structure is passed around through all the sanity checking routines
51879 ** in order to keep track of some global state information.
51880 **
51881 ** The aRef[] array is allocated so that there is 1 bit for each page in
51882 ** the database. As the integrity-check proceeds, for each page used in
51883 ** the database the corresponding bit is set. This allows integrity-check to
51884 ** detect pages that are used twice and orphaned pages (both of which
51885 ** indicate corruption).
51886 */
51887 typedef struct IntegrityCk IntegrityCk;
51888 struct IntegrityCk {
51889   BtShared *pBt;    /* The tree being checked out */
51890   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
51891   u8 *aPgRef;       /* 1 bit per page in the db (see above) */
51892   Pgno nPage;       /* Number of pages in the database */
51893   int mxErr;        /* Stop accumulating errors when this reaches zero */
51894   int nErr;         /* Number of messages written to zErrMsg so far */
51895   int mallocFailed; /* A memory allocation error has occurred */
51896   const char *zPfx; /* Error message prefix */
51897   int v1, v2;       /* Values for up to two %d fields in zPfx */
51898   StrAccum errMsg;  /* Accumulate the error message text here */
51899 };
51900 
51901 /*
51902 ** Routines to read or write a two- and four-byte big-endian integer values.
51903 */
51904 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
51905 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
51906 #define get4byte sqlite3Get4byte
51907 #define put4byte sqlite3Put4byte
51908 
51909 /************** End of btreeInt.h ********************************************/
51910 /************** Continuing where we left off in btmutex.c ********************/
51911 #ifndef SQLITE_OMIT_SHARED_CACHE
51912 #if SQLITE_THREADSAFE
51913 
51914 /*
51915 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
51916 ** set BtShared.db to the database handle associated with p and the
51917 ** p->locked boolean to true.
51918 */
51919 static void lockBtreeMutex(Btree *p){
51920   assert( p->locked==0 );
51921   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
51922   assert( sqlite3_mutex_held(p->db->mutex) );
51923 
51924   sqlite3_mutex_enter(p->pBt->mutex);
51925   p->pBt->db = p->db;
51926   p->locked = 1;
51927 }
51928 
51929 /*
51930 ** Release the BtShared mutex associated with B-Tree handle p and
51931 ** clear the p->locked boolean.
51932 */
51933 static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
51934   BtShared *pBt = p->pBt;
51935   assert( p->locked==1 );
51936   assert( sqlite3_mutex_held(pBt->mutex) );
51937   assert( sqlite3_mutex_held(p->db->mutex) );
51938   assert( p->db==pBt->db );
51939 
51940   sqlite3_mutex_leave(pBt->mutex);
51941   p->locked = 0;
51942 }
51943 
51944 /* Forward reference */
51945 static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
51946 
51947 /*
51948 ** Enter a mutex on the given BTree object.
51949 **
51950 ** If the object is not sharable, then no mutex is ever required
51951 ** and this routine is a no-op.  The underlying mutex is non-recursive.
51952 ** But we keep a reference count in Btree.wantToLock so the behavior
51953 ** of this interface is recursive.
51954 **
51955 ** To avoid deadlocks, multiple Btrees are locked in the same order
51956 ** by all database connections.  The p->pNext is a list of other
51957 ** Btrees belonging to the same database connection as the p Btree
51958 ** which need to be locked after p.  If we cannot get a lock on
51959 ** p, then first unlock all of the others on p->pNext, then wait
51960 ** for the lock to become available on p, then relock all of the
51961 ** subsequent Btrees that desire a lock.
51962 */
51963 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
51964   /* Some basic sanity checking on the Btree.  The list of Btrees
51965   ** connected by pNext and pPrev should be in sorted order by
51966   ** Btree.pBt value. All elements of the list should belong to
51967   ** the same connection. Only shared Btrees are on the list. */
51968   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
51969   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
51970   assert( p->pNext==0 || p->pNext->db==p->db );
51971   assert( p->pPrev==0 || p->pPrev->db==p->db );
51972   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
51973 
51974   /* Check for locking consistency */
51975   assert( !p->locked || p->wantToLock>0 );
51976   assert( p->sharable || p->wantToLock==0 );
51977 
51978   /* We should already hold a lock on the database connection */
51979   assert( sqlite3_mutex_held(p->db->mutex) );
51980 
51981   /* Unless the database is sharable and unlocked, then BtShared.db
51982   ** should already be set correctly. */
51983   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
51984 
51985   if( !p->sharable ) return;
51986   p->wantToLock++;
51987   if( p->locked ) return;
51988   btreeLockCarefully(p);
51989 }
51990 
51991 /* This is a helper function for sqlite3BtreeLock(). By moving
51992 ** complex, but seldom used logic, out of sqlite3BtreeLock() and
51993 ** into this routine, we avoid unnecessary stack pointer changes
51994 ** and thus help the sqlite3BtreeLock() routine to run much faster
51995 ** in the common case.
51996 */
51997 static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
51998   Btree *pLater;
51999 
52000   /* In most cases, we should be able to acquire the lock we
52001   ** want without having to go through the ascending lock
52002   ** procedure that follows.  Just be sure not to block.
52003   */
52004   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
52005     p->pBt->db = p->db;
52006     p->locked = 1;
52007     return;
52008   }
52009 
52010   /* To avoid deadlock, first release all locks with a larger
52011   ** BtShared address.  Then acquire our lock.  Then reacquire
52012   ** the other BtShared locks that we used to hold in ascending
52013   ** order.
52014   */
52015   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
52016     assert( pLater->sharable );
52017     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
52018     assert( !pLater->locked || pLater->wantToLock>0 );
52019     if( pLater->locked ){
52020       unlockBtreeMutex(pLater);
52021     }
52022   }
52023   lockBtreeMutex(p);
52024   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
52025     if( pLater->wantToLock ){
52026       lockBtreeMutex(pLater);
52027     }
52028   }
52029 }
52030 
52031 
52032 /*
52033 ** Exit the recursive mutex on a Btree.
52034 */
52035 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
52036   if( p->sharable ){
52037     assert( p->wantToLock>0 );
52038     p->wantToLock--;
52039     if( p->wantToLock==0 ){
52040       unlockBtreeMutex(p);
52041     }
52042   }
52043 }
52044 
52045 #ifndef NDEBUG
52046 /*
52047 ** Return true if the BtShared mutex is held on the btree, or if the
52048 ** B-Tree is not marked as sharable.
52049 **
52050 ** This routine is used only from within assert() statements.
52051 */
52052 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
52053   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
52054   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
52055   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
52056   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
52057 
52058   return (p->sharable==0 || p->locked);
52059 }
52060 #endif
52061 
52062 
52063 #ifndef SQLITE_OMIT_INCRBLOB
52064 /*
52065 ** Enter and leave a mutex on a Btree given a cursor owned by that
52066 ** Btree.  These entry points are used by incremental I/O and can be
52067 ** omitted if that module is not used.
52068 */
52069 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
52070   sqlite3BtreeEnter(pCur->pBtree);
52071 }
52072 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
52073   sqlite3BtreeLeave(pCur->pBtree);
52074 }
52075 #endif /* SQLITE_OMIT_INCRBLOB */
52076 
52077 
52078 /*
52079 ** Enter the mutex on every Btree associated with a database
52080 ** connection.  This is needed (for example) prior to parsing
52081 ** a statement since we will be comparing table and column names
52082 ** against all schemas and we do not want those schemas being
52083 ** reset out from under us.
52084 **
52085 ** There is a corresponding leave-all procedures.
52086 **
52087 ** Enter the mutexes in accending order by BtShared pointer address
52088 ** to avoid the possibility of deadlock when two threads with
52089 ** two or more btrees in common both try to lock all their btrees
52090 ** at the same instant.
52091 */
52092 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
52093   int i;
52094   Btree *p;
52095   assert( sqlite3_mutex_held(db->mutex) );
52096   for(i=0; i<db->nDb; i++){
52097     p = db->aDb[i].pBt;
52098     if( p ) sqlite3BtreeEnter(p);
52099   }
52100 }
52101 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
52102   int i;
52103   Btree *p;
52104   assert( sqlite3_mutex_held(db->mutex) );
52105   for(i=0; i<db->nDb; i++){
52106     p = db->aDb[i].pBt;
52107     if( p ) sqlite3BtreeLeave(p);
52108   }
52109 }
52110 
52111 /*
52112 ** Return true if a particular Btree requires a lock.  Return FALSE if
52113 ** no lock is ever required since it is not sharable.
52114 */
52115 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
52116   return p->sharable;
52117 }
52118 
52119 #ifndef NDEBUG
52120 /*
52121 ** Return true if the current thread holds the database connection
52122 ** mutex and all required BtShared mutexes.
52123 **
52124 ** This routine is used inside assert() statements only.
52125 */
52126 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
52127   int i;
52128   if( !sqlite3_mutex_held(db->mutex) ){
52129     return 0;
52130   }
52131   for(i=0; i<db->nDb; i++){
52132     Btree *p;
52133     p = db->aDb[i].pBt;
52134     if( p && p->sharable &&
52135          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
52136       return 0;
52137     }
52138   }
52139   return 1;
52140 }
52141 #endif /* NDEBUG */
52142 
52143 #ifndef NDEBUG
52144 /*
52145 ** Return true if the correct mutexes are held for accessing the
52146 ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
52147 ** access are:
52148 **
52149 **   (1) The mutex on db
52150 **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
52151 **
52152 ** If pSchema is not NULL, then iDb is computed from pSchema and
52153 ** db using sqlite3SchemaToIndex().
52154 */
52155 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
52156   Btree *p;
52157   assert( db!=0 );
52158   if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
52159   assert( iDb>=0 && iDb<db->nDb );
52160   if( !sqlite3_mutex_held(db->mutex) ) return 0;
52161   if( iDb==1 ) return 1;
52162   p = db->aDb[iDb].pBt;
52163   assert( p!=0 );
52164   return p->sharable==0 || p->locked==1;
52165 }
52166 #endif /* NDEBUG */
52167 
52168 #else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
52169 /*
52170 ** The following are special cases for mutex enter routines for use
52171 ** in single threaded applications that use shared cache.  Except for
52172 ** these two routines, all mutex operations are no-ops in that case and
52173 ** are null #defines in btree.h.
52174 **
52175 ** If shared cache is disabled, then all btree mutex routines, including
52176 ** the ones below, are no-ops and are null #defines in btree.h.
52177 */
52178 
52179 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
52180   p->pBt->db = p->db;
52181 }
52182 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
52183   int i;
52184   for(i=0; i<db->nDb; i++){
52185     Btree *p = db->aDb[i].pBt;
52186     if( p ){
52187       p->pBt->db = p->db;
52188     }
52189   }
52190 }
52191 #endif /* if SQLITE_THREADSAFE */
52192 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
52193 
52194 /************** End of btmutex.c *********************************************/
52195 /************** Begin file btree.c *******************************************/
52196 /*
52197 ** 2004 April 6
52198 **
52199 ** The author disclaims copyright to this source code.  In place of
52200 ** a legal notice, here is a blessing:
52201 **
52202 **    May you do good and not evil.
52203 **    May you find forgiveness for yourself and forgive others.
52204 **    May you share freely, never taking more than you give.
52205 **
52206 *************************************************************************
52207 ** This file implements an external (disk-based) database using BTrees.
52208 ** See the header comment on "btreeInt.h" for additional information.
52209 ** Including a description of file format and an overview of operation.
52210 */
52211 
52212 /*
52213 ** The header string that appears at the beginning of every
52214 ** SQLite database.
52215 */
52216 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
52217 
52218 /*
52219 ** Set this global variable to 1 to enable tracing using the TRACE
52220 ** macro.
52221 */
52222 #if 0
52223 int sqlite3BtreeTrace=1;  /* True to enable tracing */
52224 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
52225 #else
52226 # define TRACE(X)
52227 #endif
52228 
52229 /*
52230 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
52231 ** But if the value is zero, make it 65536.
52232 **
52233 ** This routine is used to extract the "offset to cell content area" value
52234 ** from the header of a btree page.  If the page size is 65536 and the page
52235 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
52236 ** This routine makes the necessary adjustment to 65536.
52237 */
52238 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
52239 
52240 /*
52241 ** Values passed as the 5th argument to allocateBtreePage()
52242 */
52243 #define BTALLOC_ANY   0           /* Allocate any page */
52244 #define BTALLOC_EXACT 1           /* Allocate exact page if possible */
52245 #define BTALLOC_LE    2           /* Allocate any page <= the parameter */
52246 
52247 /*
52248 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
52249 ** defined, or 0 if it is. For example:
52250 **
52251 **   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
52252 */
52253 #ifndef SQLITE_OMIT_AUTOVACUUM
52254 #define IfNotOmitAV(expr) (expr)
52255 #else
52256 #define IfNotOmitAV(expr) 0
52257 #endif
52258 
52259 #ifndef SQLITE_OMIT_SHARED_CACHE
52260 /*
52261 ** A list of BtShared objects that are eligible for participation
52262 ** in shared cache.  This variable has file scope during normal builds,
52263 ** but the test harness needs to access it so we make it global for
52264 ** test builds.
52265 **
52266 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
52267 */
52268 #ifdef SQLITE_TEST
52269 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
52270 #else
52271 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
52272 #endif
52273 #endif /* SQLITE_OMIT_SHARED_CACHE */
52274 
52275 #ifndef SQLITE_OMIT_SHARED_CACHE
52276 /*
52277 ** Enable or disable the shared pager and schema features.
52278 **
52279 ** This routine has no effect on existing database connections.
52280 ** The shared cache setting effects only future calls to
52281 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
52282 */
52283 SQLITE_API int sqlite3_enable_shared_cache(int enable){
52284   sqlite3GlobalConfig.sharedCacheEnabled = enable;
52285   return SQLITE_OK;
52286 }
52287 #endif
52288 
52289 
52290 
52291 #ifdef SQLITE_OMIT_SHARED_CACHE
52292   /*
52293   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
52294   ** and clearAllSharedCacheTableLocks()
52295   ** manipulate entries in the BtShared.pLock linked list used to store
52296   ** shared-cache table level locks. If the library is compiled with the
52297   ** shared-cache feature disabled, then there is only ever one user
52298   ** of each BtShared structure and so this locking is not necessary.
52299   ** So define the lock related functions as no-ops.
52300   */
52301   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
52302   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
52303   #define clearAllSharedCacheTableLocks(a)
52304   #define downgradeAllSharedCacheTableLocks(a)
52305   #define hasSharedCacheTableLock(a,b,c,d) 1
52306   #define hasReadConflicts(a, b) 0
52307 #endif
52308 
52309 #ifndef SQLITE_OMIT_SHARED_CACHE
52310 
52311 #ifdef SQLITE_DEBUG
52312 /*
52313 **** This function is only used as part of an assert() statement. ***
52314 **
52315 ** Check to see if pBtree holds the required locks to read or write to the
52316 ** table with root page iRoot.   Return 1 if it does and 0 if not.
52317 **
52318 ** For example, when writing to a table with root-page iRoot via
52319 ** Btree connection pBtree:
52320 **
52321 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
52322 **
52323 ** When writing to an index that resides in a sharable database, the
52324 ** caller should have first obtained a lock specifying the root page of
52325 ** the corresponding table. This makes things a bit more complicated,
52326 ** as this module treats each table as a separate structure. To determine
52327 ** the table corresponding to the index being written, this
52328 ** function has to search through the database schema.
52329 **
52330 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
52331 ** hold a write-lock on the schema table (root page 1). This is also
52332 ** acceptable.
52333 */
52334 static int hasSharedCacheTableLock(
52335   Btree *pBtree,         /* Handle that must hold lock */
52336   Pgno iRoot,            /* Root page of b-tree */
52337   int isIndex,           /* True if iRoot is the root of an index b-tree */
52338   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
52339 ){
52340   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
52341   Pgno iTab = 0;
52342   BtLock *pLock;
52343 
52344   /* If this database is not shareable, or if the client is reading
52345   ** and has the read-uncommitted flag set, then no lock is required.
52346   ** Return true immediately.
52347   */
52348   if( (pBtree->sharable==0)
52349    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
52350   ){
52351     return 1;
52352   }
52353 
52354   /* If the client is reading  or writing an index and the schema is
52355   ** not loaded, then it is too difficult to actually check to see if
52356   ** the correct locks are held.  So do not bother - just return true.
52357   ** This case does not come up very often anyhow.
52358   */
52359   if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
52360     return 1;
52361   }
52362 
52363   /* Figure out the root-page that the lock should be held on. For table
52364   ** b-trees, this is just the root page of the b-tree being read or
52365   ** written. For index b-trees, it is the root page of the associated
52366   ** table.  */
52367   if( isIndex ){
52368     HashElem *p;
52369     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
52370       Index *pIdx = (Index *)sqliteHashData(p);
52371       if( pIdx->tnum==(int)iRoot ){
52372         iTab = pIdx->pTable->tnum;
52373       }
52374     }
52375   }else{
52376     iTab = iRoot;
52377   }
52378 
52379   /* Search for the required lock. Either a write-lock on root-page iTab, a
52380   ** write-lock on the schema table, or (if the client is reading) a
52381   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
52382   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
52383     if( pLock->pBtree==pBtree
52384      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
52385      && pLock->eLock>=eLockType
52386     ){
52387       return 1;
52388     }
52389   }
52390 
52391   /* Failed to find the required lock. */
52392   return 0;
52393 }
52394 #endif /* SQLITE_DEBUG */
52395 
52396 #ifdef SQLITE_DEBUG
52397 /*
52398 **** This function may be used as part of assert() statements only. ****
52399 **
52400 ** Return true if it would be illegal for pBtree to write into the
52401 ** table or index rooted at iRoot because other shared connections are
52402 ** simultaneously reading that same table or index.
52403 **
52404 ** It is illegal for pBtree to write if some other Btree object that
52405 ** shares the same BtShared object is currently reading or writing
52406 ** the iRoot table.  Except, if the other Btree object has the
52407 ** read-uncommitted flag set, then it is OK for the other object to
52408 ** have a read cursor.
52409 **
52410 ** For example, before writing to any part of the table or index
52411 ** rooted at page iRoot, one should call:
52412 **
52413 **    assert( !hasReadConflicts(pBtree, iRoot) );
52414 */
52415 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
52416   BtCursor *p;
52417   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
52418     if( p->pgnoRoot==iRoot
52419      && p->pBtree!=pBtree
52420      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
52421     ){
52422       return 1;
52423     }
52424   }
52425   return 0;
52426 }
52427 #endif    /* #ifdef SQLITE_DEBUG */
52428 
52429 /*
52430 ** Query to see if Btree handle p may obtain a lock of type eLock
52431 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
52432 ** SQLITE_OK if the lock may be obtained (by calling
52433 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
52434 */
52435 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
52436   BtShared *pBt = p->pBt;
52437   BtLock *pIter;
52438 
52439   assert( sqlite3BtreeHoldsMutex(p) );
52440   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
52441   assert( p->db!=0 );
52442   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
52443 
52444   /* If requesting a write-lock, then the Btree must have an open write
52445   ** transaction on this file. And, obviously, for this to be so there
52446   ** must be an open write transaction on the file itself.
52447   */
52448   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
52449   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
52450 
52451   /* This routine is a no-op if the shared-cache is not enabled */
52452   if( !p->sharable ){
52453     return SQLITE_OK;
52454   }
52455 
52456   /* If some other connection is holding an exclusive lock, the
52457   ** requested lock may not be obtained.
52458   */
52459   if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
52460     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
52461     return SQLITE_LOCKED_SHAREDCACHE;
52462   }
52463 
52464   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
52465     /* The condition (pIter->eLock!=eLock) in the following if(...)
52466     ** statement is a simplification of:
52467     **
52468     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
52469     **
52470     ** since we know that if eLock==WRITE_LOCK, then no other connection
52471     ** may hold a WRITE_LOCK on any table in this file (since there can
52472     ** only be a single writer).
52473     */
52474     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
52475     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
52476     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
52477       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
52478       if( eLock==WRITE_LOCK ){
52479         assert( p==pBt->pWriter );
52480         pBt->btsFlags |= BTS_PENDING;
52481       }
52482       return SQLITE_LOCKED_SHAREDCACHE;
52483     }
52484   }
52485   return SQLITE_OK;
52486 }
52487 #endif /* !SQLITE_OMIT_SHARED_CACHE */
52488 
52489 #ifndef SQLITE_OMIT_SHARED_CACHE
52490 /*
52491 ** Add a lock on the table with root-page iTable to the shared-btree used
52492 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
52493 ** WRITE_LOCK.
52494 **
52495 ** This function assumes the following:
52496 **
52497 **   (a) The specified Btree object p is connected to a sharable
52498 **       database (one with the BtShared.sharable flag set), and
52499 **
52500 **   (b) No other Btree objects hold a lock that conflicts
52501 **       with the requested lock (i.e. querySharedCacheTableLock() has
52502 **       already been called and returned SQLITE_OK).
52503 **
52504 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
52505 ** is returned if a malloc attempt fails.
52506 */
52507 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
52508   BtShared *pBt = p->pBt;
52509   BtLock *pLock = 0;
52510   BtLock *pIter;
52511 
52512   assert( sqlite3BtreeHoldsMutex(p) );
52513   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
52514   assert( p->db!=0 );
52515 
52516   /* A connection with the read-uncommitted flag set will never try to
52517   ** obtain a read-lock using this function. The only read-lock obtained
52518   ** by a connection in read-uncommitted mode is on the sqlite_master
52519   ** table, and that lock is obtained in BtreeBeginTrans().  */
52520   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
52521 
52522   /* This function should only be called on a sharable b-tree after it
52523   ** has been determined that no other b-tree holds a conflicting lock.  */
52524   assert( p->sharable );
52525   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
52526 
52527   /* First search the list for an existing lock on this table. */
52528   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
52529     if( pIter->iTable==iTable && pIter->pBtree==p ){
52530       pLock = pIter;
52531       break;
52532     }
52533   }
52534 
52535   /* If the above search did not find a BtLock struct associating Btree p
52536   ** with table iTable, allocate one and link it into the list.
52537   */
52538   if( !pLock ){
52539     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
52540     if( !pLock ){
52541       return SQLITE_NOMEM;
52542     }
52543     pLock->iTable = iTable;
52544     pLock->pBtree = p;
52545     pLock->pNext = pBt->pLock;
52546     pBt->pLock = pLock;
52547   }
52548 
52549   /* Set the BtLock.eLock variable to the maximum of the current lock
52550   ** and the requested lock. This means if a write-lock was already held
52551   ** and a read-lock requested, we don't incorrectly downgrade the lock.
52552   */
52553   assert( WRITE_LOCK>READ_LOCK );
52554   if( eLock>pLock->eLock ){
52555     pLock->eLock = eLock;
52556   }
52557 
52558   return SQLITE_OK;
52559 }
52560 #endif /* !SQLITE_OMIT_SHARED_CACHE */
52561 
52562 #ifndef SQLITE_OMIT_SHARED_CACHE
52563 /*
52564 ** Release all the table locks (locks obtained via calls to
52565 ** the setSharedCacheTableLock() procedure) held by Btree object p.
52566 **
52567 ** This function assumes that Btree p has an open read or write
52568 ** transaction. If it does not, then the BTS_PENDING flag
52569 ** may be incorrectly cleared.
52570 */
52571 static void clearAllSharedCacheTableLocks(Btree *p){
52572   BtShared *pBt = p->pBt;
52573   BtLock **ppIter = &pBt->pLock;
52574 
52575   assert( sqlite3BtreeHoldsMutex(p) );
52576   assert( p->sharable || 0==*ppIter );
52577   assert( p->inTrans>0 );
52578 
52579   while( *ppIter ){
52580     BtLock *pLock = *ppIter;
52581     assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
52582     assert( pLock->pBtree->inTrans>=pLock->eLock );
52583     if( pLock->pBtree==p ){
52584       *ppIter = pLock->pNext;
52585       assert( pLock->iTable!=1 || pLock==&p->lock );
52586       if( pLock->iTable!=1 ){
52587         sqlite3_free(pLock);
52588       }
52589     }else{
52590       ppIter = &pLock->pNext;
52591     }
52592   }
52593 
52594   assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
52595   if( pBt->pWriter==p ){
52596     pBt->pWriter = 0;
52597     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
52598   }else if( pBt->nTransaction==2 ){
52599     /* This function is called when Btree p is concluding its
52600     ** transaction. If there currently exists a writer, and p is not
52601     ** that writer, then the number of locks held by connections other
52602     ** than the writer must be about to drop to zero. In this case
52603     ** set the BTS_PENDING flag to 0.
52604     **
52605     ** If there is not currently a writer, then BTS_PENDING must
52606     ** be zero already. So this next line is harmless in that case.
52607     */
52608     pBt->btsFlags &= ~BTS_PENDING;
52609   }
52610 }
52611 
52612 /*
52613 ** This function changes all write-locks held by Btree p into read-locks.
52614 */
52615 static void downgradeAllSharedCacheTableLocks(Btree *p){
52616   BtShared *pBt = p->pBt;
52617   if( pBt->pWriter==p ){
52618     BtLock *pLock;
52619     pBt->pWriter = 0;
52620     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
52621     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
52622       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
52623       pLock->eLock = READ_LOCK;
52624     }
52625   }
52626 }
52627 
52628 #endif /* SQLITE_OMIT_SHARED_CACHE */
52629 
52630 static void releasePage(MemPage *pPage);  /* Forward reference */
52631 
52632 /*
52633 ***** This routine is used inside of assert() only ****
52634 **
52635 ** Verify that the cursor holds the mutex on its BtShared
52636 */
52637 #ifdef SQLITE_DEBUG
52638 static int cursorHoldsMutex(BtCursor *p){
52639   return sqlite3_mutex_held(p->pBt->mutex);
52640 }
52641 #endif
52642 
52643 /*
52644 ** Invalidate the overflow cache of the cursor passed as the first argument.
52645 ** on the shared btree structure pBt.
52646 */
52647 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
52648 
52649 /*
52650 ** Invalidate the overflow page-list cache for all cursors opened
52651 ** on the shared btree structure pBt.
52652 */
52653 static void invalidateAllOverflowCache(BtShared *pBt){
52654   BtCursor *p;
52655   assert( sqlite3_mutex_held(pBt->mutex) );
52656   for(p=pBt->pCursor; p; p=p->pNext){
52657     invalidateOverflowCache(p);
52658   }
52659 }
52660 
52661 #ifndef SQLITE_OMIT_INCRBLOB
52662 /*
52663 ** This function is called before modifying the contents of a table
52664 ** to invalidate any incrblob cursors that are open on the
52665 ** row or one of the rows being modified.
52666 **
52667 ** If argument isClearTable is true, then the entire contents of the
52668 ** table is about to be deleted. In this case invalidate all incrblob
52669 ** cursors open on any row within the table with root-page pgnoRoot.
52670 **
52671 ** Otherwise, if argument isClearTable is false, then the row with
52672 ** rowid iRow is being replaced or deleted. In this case invalidate
52673 ** only those incrblob cursors open on that specific row.
52674 */
52675 static void invalidateIncrblobCursors(
52676   Btree *pBtree,          /* The database file to check */
52677   i64 iRow,               /* The rowid that might be changing */
52678   int isClearTable        /* True if all rows are being deleted */
52679 ){
52680   BtCursor *p;
52681   BtShared *pBt = pBtree->pBt;
52682   assert( sqlite3BtreeHoldsMutex(pBtree) );
52683   for(p=pBt->pCursor; p; p=p->pNext){
52684     if( (p->curFlags & BTCF_Incrblob)!=0
52685      && (isClearTable || p->info.nKey==iRow)
52686     ){
52687       p->eState = CURSOR_INVALID;
52688     }
52689   }
52690 }
52691 
52692 #else
52693   /* Stub function when INCRBLOB is omitted */
52694   #define invalidateIncrblobCursors(x,y,z)
52695 #endif /* SQLITE_OMIT_INCRBLOB */
52696 
52697 /*
52698 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
52699 ** when a page that previously contained data becomes a free-list leaf
52700 ** page.
52701 **
52702 ** The BtShared.pHasContent bitvec exists to work around an obscure
52703 ** bug caused by the interaction of two useful IO optimizations surrounding
52704 ** free-list leaf pages:
52705 **
52706 **   1) When all data is deleted from a page and the page becomes
52707 **      a free-list leaf page, the page is not written to the database
52708 **      (as free-list leaf pages contain no meaningful data). Sometimes
52709 **      such a page is not even journalled (as it will not be modified,
52710 **      why bother journalling it?).
52711 **
52712 **   2) When a free-list leaf page is reused, its content is not read
52713 **      from the database or written to the journal file (why should it
52714 **      be, if it is not at all meaningful?).
52715 **
52716 ** By themselves, these optimizations work fine and provide a handy
52717 ** performance boost to bulk delete or insert operations. However, if
52718 ** a page is moved to the free-list and then reused within the same
52719 ** transaction, a problem comes up. If the page is not journalled when
52720 ** it is moved to the free-list and it is also not journalled when it
52721 ** is extracted from the free-list and reused, then the original data
52722 ** may be lost. In the event of a rollback, it may not be possible
52723 ** to restore the database to its original configuration.
52724 **
52725 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
52726 ** moved to become a free-list leaf page, the corresponding bit is
52727 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
52728 ** optimization 2 above is omitted if the corresponding bit is already
52729 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
52730 ** at the end of every transaction.
52731 */
52732 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
52733   int rc = SQLITE_OK;
52734   if( !pBt->pHasContent ){
52735     assert( pgno<=pBt->nPage );
52736     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
52737     if( !pBt->pHasContent ){
52738       rc = SQLITE_NOMEM;
52739     }
52740   }
52741   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
52742     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
52743   }
52744   return rc;
52745 }
52746 
52747 /*
52748 ** Query the BtShared.pHasContent vector.
52749 **
52750 ** This function is called when a free-list leaf page is removed from the
52751 ** free-list for reuse. It returns false if it is safe to retrieve the
52752 ** page from the pager layer with the 'no-content' flag set. True otherwise.
52753 */
52754 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
52755   Bitvec *p = pBt->pHasContent;
52756   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
52757 }
52758 
52759 /*
52760 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
52761 ** invoked at the conclusion of each write-transaction.
52762 */
52763 static void btreeClearHasContent(BtShared *pBt){
52764   sqlite3BitvecDestroy(pBt->pHasContent);
52765   pBt->pHasContent = 0;
52766 }
52767 
52768 /*
52769 ** Release all of the apPage[] pages for a cursor.
52770 */
52771 static void btreeReleaseAllCursorPages(BtCursor *pCur){
52772   int i;
52773   for(i=0; i<=pCur->iPage; i++){
52774     releasePage(pCur->apPage[i]);
52775     pCur->apPage[i] = 0;
52776   }
52777   pCur->iPage = -1;
52778 }
52779 
52780 
52781 /*
52782 ** Save the current cursor position in the variables BtCursor.nKey
52783 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
52784 **
52785 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
52786 ** prior to calling this routine.
52787 */
52788 static int saveCursorPosition(BtCursor *pCur){
52789   int rc;
52790 
52791   assert( CURSOR_VALID==pCur->eState );
52792   assert( 0==pCur->pKey );
52793   assert( cursorHoldsMutex(pCur) );
52794 
52795   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
52796   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
52797 
52798   /* If this is an intKey table, then the above call to BtreeKeySize()
52799   ** stores the integer key in pCur->nKey. In this case this value is
52800   ** all that is required. Otherwise, if pCur is not open on an intKey
52801   ** table, then malloc space for and store the pCur->nKey bytes of key
52802   ** data.
52803   */
52804   if( 0==pCur->apPage[0]->intKey ){
52805     void *pKey = sqlite3Malloc( pCur->nKey );
52806     if( pKey ){
52807       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
52808       if( rc==SQLITE_OK ){
52809         pCur->pKey = pKey;
52810       }else{
52811         sqlite3_free(pKey);
52812       }
52813     }else{
52814       rc = SQLITE_NOMEM;
52815     }
52816   }
52817   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
52818 
52819   if( rc==SQLITE_OK ){
52820     btreeReleaseAllCursorPages(pCur);
52821     pCur->eState = CURSOR_REQUIRESEEK;
52822   }
52823 
52824   invalidateOverflowCache(pCur);
52825   return rc;
52826 }
52827 
52828 /* Forward reference */
52829 static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
52830 
52831 /*
52832 ** Save the positions of all cursors (except pExcept) that are open on
52833 ** the table with root-page iRoot.  "Saving the cursor position" means that
52834 ** the location in the btree is remembered in such a way that it can be
52835 ** moved back to the same spot after the btree has been modified.  This
52836 ** routine is called just before cursor pExcept is used to modify the
52837 ** table, for example in BtreeDelete() or BtreeInsert().
52838 **
52839 ** Implementation note:  This routine merely checks to see if any cursors
52840 ** need to be saved.  It calls out to saveCursorsOnList() in the (unusual)
52841 ** event that cursors are in need to being saved.
52842 */
52843 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
52844   BtCursor *p;
52845   assert( sqlite3_mutex_held(pBt->mutex) );
52846   assert( pExcept==0 || pExcept->pBt==pBt );
52847   for(p=pBt->pCursor; p; p=p->pNext){
52848     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
52849   }
52850   return p ? saveCursorsOnList(p, iRoot, pExcept) : SQLITE_OK;
52851 }
52852 
52853 /* This helper routine to saveAllCursors does the actual work of saving
52854 ** the cursors if and when a cursor is found that actually requires saving.
52855 ** The common case is that no cursors need to be saved, so this routine is
52856 ** broken out from its caller to avoid unnecessary stack pointer movement.
52857 */
52858 static int SQLITE_NOINLINE saveCursorsOnList(
52859   BtCursor *p,         /* The first cursor that needs saving */
52860   Pgno iRoot,          /* Only save cursor with this iRoot. Save all if zero */
52861   BtCursor *pExcept    /* Do not save this cursor */
52862 ){
52863   do{
52864     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
52865       if( p->eState==CURSOR_VALID ){
52866         int rc = saveCursorPosition(p);
52867         if( SQLITE_OK!=rc ){
52868           return rc;
52869         }
52870       }else{
52871         testcase( p->iPage>0 );
52872         btreeReleaseAllCursorPages(p);
52873       }
52874     }
52875     p = p->pNext;
52876   }while( p );
52877   return SQLITE_OK;
52878 }
52879 
52880 /*
52881 ** Clear the current cursor position.
52882 */
52883 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
52884   assert( cursorHoldsMutex(pCur) );
52885   sqlite3_free(pCur->pKey);
52886   pCur->pKey = 0;
52887   pCur->eState = CURSOR_INVALID;
52888 }
52889 
52890 /*
52891 ** In this version of BtreeMoveto, pKey is a packed index record
52892 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
52893 ** record and then call BtreeMovetoUnpacked() to do the work.
52894 */
52895 static int btreeMoveto(
52896   BtCursor *pCur,     /* Cursor open on the btree to be searched */
52897   const void *pKey,   /* Packed key if the btree is an index */
52898   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
52899   int bias,           /* Bias search to the high end */
52900   int *pRes           /* Write search results here */
52901 ){
52902   int rc;                    /* Status code */
52903   UnpackedRecord *pIdxKey;   /* Unpacked index key */
52904   char aSpace[200];          /* Temp space for pIdxKey - to avoid a malloc */
52905   char *pFree = 0;
52906 
52907   if( pKey ){
52908     assert( nKey==(i64)(int)nKey );
52909     pIdxKey = sqlite3VdbeAllocUnpackedRecord(
52910         pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
52911     );
52912     if( pIdxKey==0 ) return SQLITE_NOMEM;
52913     sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
52914     if( pIdxKey->nField==0 ){
52915       sqlite3DbFree(pCur->pKeyInfo->db, pFree);
52916       return SQLITE_CORRUPT_BKPT;
52917     }
52918   }else{
52919     pIdxKey = 0;
52920   }
52921   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
52922   if( pFree ){
52923     sqlite3DbFree(pCur->pKeyInfo->db, pFree);
52924   }
52925   return rc;
52926 }
52927 
52928 /*
52929 ** Restore the cursor to the position it was in (or as close to as possible)
52930 ** when saveCursorPosition() was called. Note that this call deletes the
52931 ** saved position info stored by saveCursorPosition(), so there can be
52932 ** at most one effective restoreCursorPosition() call after each
52933 ** saveCursorPosition().
52934 */
52935 static int btreeRestoreCursorPosition(BtCursor *pCur){
52936   int rc;
52937   assert( cursorHoldsMutex(pCur) );
52938   assert( pCur->eState>=CURSOR_REQUIRESEEK );
52939   if( pCur->eState==CURSOR_FAULT ){
52940     return pCur->skipNext;
52941   }
52942   pCur->eState = CURSOR_INVALID;
52943   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
52944   if( rc==SQLITE_OK ){
52945     sqlite3_free(pCur->pKey);
52946     pCur->pKey = 0;
52947     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
52948     if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
52949       pCur->eState = CURSOR_SKIPNEXT;
52950     }
52951   }
52952   return rc;
52953 }
52954 
52955 #define restoreCursorPosition(p) \
52956   (p->eState>=CURSOR_REQUIRESEEK ? \
52957          btreeRestoreCursorPosition(p) : \
52958          SQLITE_OK)
52959 
52960 /*
52961 ** Determine whether or not a cursor has moved from the position where
52962 ** it was last placed, or has been invalidated for any other reason.
52963 ** Cursors can move when the row they are pointing at is deleted out
52964 ** from under them, for example.  Cursor might also move if a btree
52965 ** is rebalanced.
52966 **
52967 ** Calling this routine with a NULL cursor pointer returns false.
52968 **
52969 ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
52970 ** back to where it ought to be if this routine returns true.
52971 */
52972 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
52973   return pCur->eState!=CURSOR_VALID;
52974 }
52975 
52976 /*
52977 ** This routine restores a cursor back to its original position after it
52978 ** has been moved by some outside activity (such as a btree rebalance or
52979 ** a row having been deleted out from under the cursor).
52980 **
52981 ** On success, the *pDifferentRow parameter is false if the cursor is left
52982 ** pointing at exactly the same row.  *pDifferntRow is the row the cursor
52983 ** was pointing to has been deleted, forcing the cursor to point to some
52984 ** nearby row.
52985 **
52986 ** This routine should only be called for a cursor that just returned
52987 ** TRUE from sqlite3BtreeCursorHasMoved().
52988 */
52989 SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
52990   int rc;
52991 
52992   assert( pCur!=0 );
52993   assert( pCur->eState!=CURSOR_VALID );
52994   rc = restoreCursorPosition(pCur);
52995   if( rc ){
52996     *pDifferentRow = 1;
52997     return rc;
52998   }
52999   if( pCur->eState!=CURSOR_VALID || NEVER(pCur->skipNext!=0) ){
53000     *pDifferentRow = 1;
53001   }else{
53002     *pDifferentRow = 0;
53003   }
53004   return SQLITE_OK;
53005 }
53006 
53007 #ifndef SQLITE_OMIT_AUTOVACUUM
53008 /*
53009 ** Given a page number of a regular database page, return the page
53010 ** number for the pointer-map page that contains the entry for the
53011 ** input page number.
53012 **
53013 ** Return 0 (not a valid page) for pgno==1 since there is
53014 ** no pointer map associated with page 1.  The integrity_check logic
53015 ** requires that ptrmapPageno(*,1)!=1.
53016 */
53017 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
53018   int nPagesPerMapPage;
53019   Pgno iPtrMap, ret;
53020   assert( sqlite3_mutex_held(pBt->mutex) );
53021   if( pgno<2 ) return 0;
53022   nPagesPerMapPage = (pBt->usableSize/5)+1;
53023   iPtrMap = (pgno-2)/nPagesPerMapPage;
53024   ret = (iPtrMap*nPagesPerMapPage) + 2;
53025   if( ret==PENDING_BYTE_PAGE(pBt) ){
53026     ret++;
53027   }
53028   return ret;
53029 }
53030 
53031 /*
53032 ** Write an entry into the pointer map.
53033 **
53034 ** This routine updates the pointer map entry for page number 'key'
53035 ** so that it maps to type 'eType' and parent page number 'pgno'.
53036 **
53037 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
53038 ** a no-op.  If an error occurs, the appropriate error code is written
53039 ** into *pRC.
53040 */
53041 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
53042   DbPage *pDbPage;  /* The pointer map page */
53043   u8 *pPtrmap;      /* The pointer map data */
53044   Pgno iPtrmap;     /* The pointer map page number */
53045   int offset;       /* Offset in pointer map page */
53046   int rc;           /* Return code from subfunctions */
53047 
53048   if( *pRC ) return;
53049 
53050   assert( sqlite3_mutex_held(pBt->mutex) );
53051   /* The master-journal page number must never be used as a pointer map page */
53052   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
53053 
53054   assert( pBt->autoVacuum );
53055   if( key==0 ){
53056     *pRC = SQLITE_CORRUPT_BKPT;
53057     return;
53058   }
53059   iPtrmap = PTRMAP_PAGENO(pBt, key);
53060   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
53061   if( rc!=SQLITE_OK ){
53062     *pRC = rc;
53063     return;
53064   }
53065   offset = PTRMAP_PTROFFSET(iPtrmap, key);
53066   if( offset<0 ){
53067     *pRC = SQLITE_CORRUPT_BKPT;
53068     goto ptrmap_exit;
53069   }
53070   assert( offset <= (int)pBt->usableSize-5 );
53071   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
53072 
53073   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
53074     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
53075     *pRC= rc = sqlite3PagerWrite(pDbPage);
53076     if( rc==SQLITE_OK ){
53077       pPtrmap[offset] = eType;
53078       put4byte(&pPtrmap[offset+1], parent);
53079     }
53080   }
53081 
53082 ptrmap_exit:
53083   sqlite3PagerUnref(pDbPage);
53084 }
53085 
53086 /*
53087 ** Read an entry from the pointer map.
53088 **
53089 ** This routine retrieves the pointer map entry for page 'key', writing
53090 ** the type and parent page number to *pEType and *pPgno respectively.
53091 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
53092 */
53093 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
53094   DbPage *pDbPage;   /* The pointer map page */
53095   int iPtrmap;       /* Pointer map page index */
53096   u8 *pPtrmap;       /* Pointer map page data */
53097   int offset;        /* Offset of entry in pointer map */
53098   int rc;
53099 
53100   assert( sqlite3_mutex_held(pBt->mutex) );
53101 
53102   iPtrmap = PTRMAP_PAGENO(pBt, key);
53103   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
53104   if( rc!=0 ){
53105     return rc;
53106   }
53107   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
53108 
53109   offset = PTRMAP_PTROFFSET(iPtrmap, key);
53110   if( offset<0 ){
53111     sqlite3PagerUnref(pDbPage);
53112     return SQLITE_CORRUPT_BKPT;
53113   }
53114   assert( offset <= (int)pBt->usableSize-5 );
53115   assert( pEType!=0 );
53116   *pEType = pPtrmap[offset];
53117   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
53118 
53119   sqlite3PagerUnref(pDbPage);
53120   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
53121   return SQLITE_OK;
53122 }
53123 
53124 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
53125   #define ptrmapPut(w,x,y,z,rc)
53126   #define ptrmapGet(w,x,y,z) SQLITE_OK
53127   #define ptrmapPutOvflPtr(x, y, rc)
53128 #endif
53129 
53130 /*
53131 ** Given a btree page and a cell index (0 means the first cell on
53132 ** the page, 1 means the second cell, and so forth) return a pointer
53133 ** to the cell content.
53134 **
53135 ** This routine works only for pages that do not contain overflow cells.
53136 */
53137 #define findCell(P,I) \
53138   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
53139 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
53140 
53141 
53142 /*
53143 ** This a more complex version of findCell() that works for
53144 ** pages that do contain overflow cells.
53145 */
53146 static u8 *findOverflowCell(MemPage *pPage, int iCell){
53147   int i;
53148   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53149   for(i=pPage->nOverflow-1; i>=0; i--){
53150     int k;
53151     k = pPage->aiOvfl[i];
53152     if( k<=iCell ){
53153       if( k==iCell ){
53154         return pPage->apOvfl[i];
53155       }
53156       iCell--;
53157     }
53158   }
53159   return findCell(pPage, iCell);
53160 }
53161 
53162 /*
53163 ** Parse a cell content block and fill in the CellInfo structure.  There
53164 ** are two versions of this function.  btreeParseCell() takes a
53165 ** cell index as the second argument and btreeParseCellPtr()
53166 ** takes a pointer to the body of the cell as its second argument.
53167 */
53168 static void btreeParseCellPtr(
53169   MemPage *pPage,         /* Page containing the cell */
53170   u8 *pCell,              /* Pointer to the cell text. */
53171   CellInfo *pInfo         /* Fill in this structure */
53172 ){
53173   u8 *pIter;              /* For scanning through pCell */
53174   u32 nPayload;           /* Number of bytes of cell payload */
53175 
53176   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53177   assert( pPage->leaf==0 || pPage->leaf==1 );
53178   if( pPage->intKeyLeaf ){
53179     assert( pPage->childPtrSize==0 );
53180     pIter = pCell + getVarint32(pCell, nPayload);
53181     pIter += getVarint(pIter, (u64*)&pInfo->nKey);
53182   }else if( pPage->noPayload ){
53183     assert( pPage->childPtrSize==4 );
53184     pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
53185     pInfo->nPayload = 0;
53186     pInfo->nLocal = 0;
53187     pInfo->iOverflow = 0;
53188     pInfo->pPayload = 0;
53189     return;
53190   }else{
53191     pIter = pCell + pPage->childPtrSize;
53192     pIter += getVarint32(pIter, nPayload);
53193     pInfo->nKey = nPayload;
53194   }
53195   pInfo->nPayload = nPayload;
53196   pInfo->pPayload = pIter;
53197   testcase( nPayload==pPage->maxLocal );
53198   testcase( nPayload==pPage->maxLocal+1 );
53199   if( nPayload<=pPage->maxLocal ){
53200     /* This is the (easy) common case where the entire payload fits
53201     ** on the local page.  No overflow is required.
53202     */
53203     pInfo->nSize = nPayload + (u16)(pIter - pCell);
53204     if( pInfo->nSize<4 ) pInfo->nSize = 4;
53205     pInfo->nLocal = (u16)nPayload;
53206     pInfo->iOverflow = 0;
53207   }else{
53208     /* If the payload will not fit completely on the local page, we have
53209     ** to decide how much to store locally and how much to spill onto
53210     ** overflow pages.  The strategy is to minimize the amount of unused
53211     ** space on overflow pages while keeping the amount of local storage
53212     ** in between minLocal and maxLocal.
53213     **
53214     ** Warning:  changing the way overflow payload is distributed in any
53215     ** way will result in an incompatible file format.
53216     */
53217     int minLocal;  /* Minimum amount of payload held locally */
53218     int maxLocal;  /* Maximum amount of payload held locally */
53219     int surplus;   /* Overflow payload available for local storage */
53220 
53221     minLocal = pPage->minLocal;
53222     maxLocal = pPage->maxLocal;
53223     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
53224     testcase( surplus==maxLocal );
53225     testcase( surplus==maxLocal+1 );
53226     if( surplus <= maxLocal ){
53227       pInfo->nLocal = (u16)surplus;
53228     }else{
53229       pInfo->nLocal = (u16)minLocal;
53230     }
53231     pInfo->iOverflow = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell);
53232     pInfo->nSize = pInfo->iOverflow + 4;
53233   }
53234 }
53235 static void btreeParseCell(
53236   MemPage *pPage,         /* Page containing the cell */
53237   int iCell,              /* The cell index.  First cell is 0 */
53238   CellInfo *pInfo         /* Fill in this structure */
53239 ){
53240   btreeParseCellPtr(pPage, findCell(pPage, iCell), pInfo);
53241 }
53242 
53243 /*
53244 ** Compute the total number of bytes that a Cell needs in the cell
53245 ** data area of the btree-page.  The return number includes the cell
53246 ** data header and the local payload, but not any overflow page or
53247 ** the space used by the cell pointer.
53248 */
53249 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
53250   u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
53251   u8 *pEnd;                                /* End mark for a varint */
53252   u32 nSize;                               /* Size value to return */
53253 
53254 #ifdef SQLITE_DEBUG
53255   /* The value returned by this function should always be the same as
53256   ** the (CellInfo.nSize) value found by doing a full parse of the
53257   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
53258   ** this function verifies that this invariant is not violated. */
53259   CellInfo debuginfo;
53260   btreeParseCellPtr(pPage, pCell, &debuginfo);
53261 #endif
53262 
53263   if( pPage->noPayload ){
53264     pEnd = &pIter[9];
53265     while( (*pIter++)&0x80 && pIter<pEnd );
53266     assert( pPage->childPtrSize==4 );
53267     return (u16)(pIter - pCell);
53268   }
53269   nSize = *pIter;
53270   if( nSize>=0x80 ){
53271     pEnd = &pIter[9];
53272     nSize &= 0x7f;
53273     do{
53274       nSize = (nSize<<7) | (*++pIter & 0x7f);
53275     }while( *(pIter)>=0x80 && pIter<pEnd );
53276   }
53277   pIter++;
53278   if( pPage->intKey ){
53279     /* pIter now points at the 64-bit integer key value, a variable length
53280     ** integer. The following block moves pIter to point at the first byte
53281     ** past the end of the key value. */
53282     pEnd = &pIter[9];
53283     while( (*pIter++)&0x80 && pIter<pEnd );
53284   }
53285   testcase( nSize==pPage->maxLocal );
53286   testcase( nSize==pPage->maxLocal+1 );
53287   if( nSize<=pPage->maxLocal ){
53288     nSize += (u32)(pIter - pCell);
53289     if( nSize<4 ) nSize = 4;
53290   }else{
53291     int minLocal = pPage->minLocal;
53292     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
53293     testcase( nSize==pPage->maxLocal );
53294     testcase( nSize==pPage->maxLocal+1 );
53295     if( nSize>pPage->maxLocal ){
53296       nSize = minLocal;
53297     }
53298     nSize += 4 + (u16)(pIter - pCell);
53299   }
53300   assert( nSize==debuginfo.nSize || CORRUPT_DB );
53301   return (u16)nSize;
53302 }
53303 
53304 #ifdef SQLITE_DEBUG
53305 /* This variation on cellSizePtr() is used inside of assert() statements
53306 ** only. */
53307 static u16 cellSize(MemPage *pPage, int iCell){
53308   return cellSizePtr(pPage, findCell(pPage, iCell));
53309 }
53310 #endif
53311 
53312 #ifndef SQLITE_OMIT_AUTOVACUUM
53313 /*
53314 ** If the cell pCell, part of page pPage contains a pointer
53315 ** to an overflow page, insert an entry into the pointer-map
53316 ** for the overflow page.
53317 */
53318 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
53319   CellInfo info;
53320   if( *pRC ) return;
53321   assert( pCell!=0 );
53322   btreeParseCellPtr(pPage, pCell, &info);
53323   if( info.iOverflow ){
53324     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
53325     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
53326   }
53327 }
53328 #endif
53329 
53330 
53331 /*
53332 ** Defragment the page given.  All Cells are moved to the
53333 ** end of the page and all free space is collected into one
53334 ** big FreeBlk that occurs in between the header and cell
53335 ** pointer array and the cell content area.
53336 */
53337 static int defragmentPage(MemPage *pPage){
53338   int i;                     /* Loop counter */
53339   int pc;                    /* Address of the i-th cell */
53340   int hdr;                   /* Offset to the page header */
53341   int size;                  /* Size of a cell */
53342   int usableSize;            /* Number of usable bytes on a page */
53343   int cellOffset;            /* Offset to the cell pointer array */
53344   int cbrk;                  /* Offset to the cell content area */
53345   int nCell;                 /* Number of cells on the page */
53346   unsigned char *data;       /* The page data */
53347   unsigned char *temp;       /* Temp area for cell content */
53348   int iCellFirst;            /* First allowable cell index */
53349   int iCellLast;             /* Last possible cell index */
53350 
53351 
53352   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53353   assert( pPage->pBt!=0 );
53354   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
53355   assert( pPage->nOverflow==0 );
53356   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53357   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
53358   data = pPage->aData;
53359   hdr = pPage->hdrOffset;
53360   cellOffset = pPage->cellOffset;
53361   nCell = pPage->nCell;
53362   assert( nCell==get2byte(&data[hdr+3]) );
53363   usableSize = pPage->pBt->usableSize;
53364   cbrk = get2byte(&data[hdr+5]);
53365   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
53366   cbrk = usableSize;
53367   iCellFirst = cellOffset + 2*nCell;
53368   iCellLast = usableSize - 4;
53369   for(i=0; i<nCell; i++){
53370     u8 *pAddr;     /* The i-th cell pointer */
53371     pAddr = &data[cellOffset + i*2];
53372     pc = get2byte(pAddr);
53373     testcase( pc==iCellFirst );
53374     testcase( pc==iCellLast );
53375 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
53376     /* These conditions have already been verified in btreeInitPage()
53377     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
53378     */
53379     if( pc<iCellFirst || pc>iCellLast ){
53380       return SQLITE_CORRUPT_BKPT;
53381     }
53382 #endif
53383     assert( pc>=iCellFirst && pc<=iCellLast );
53384     size = cellSizePtr(pPage, &temp[pc]);
53385     cbrk -= size;
53386 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
53387     if( cbrk<iCellFirst ){
53388       return SQLITE_CORRUPT_BKPT;
53389     }
53390 #else
53391     if( cbrk<iCellFirst || pc+size>usableSize ){
53392       return SQLITE_CORRUPT_BKPT;
53393     }
53394 #endif
53395     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
53396     testcase( cbrk+size==usableSize );
53397     testcase( pc+size==usableSize );
53398     memcpy(&data[cbrk], &temp[pc], size);
53399     put2byte(pAddr, cbrk);
53400   }
53401   assert( cbrk>=iCellFirst );
53402   put2byte(&data[hdr+5], cbrk);
53403   data[hdr+1] = 0;
53404   data[hdr+2] = 0;
53405   data[hdr+7] = 0;
53406   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
53407   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53408   if( cbrk-iCellFirst!=pPage->nFree ){
53409     return SQLITE_CORRUPT_BKPT;
53410   }
53411   return SQLITE_OK;
53412 }
53413 
53414 /*
53415 ** Allocate nByte bytes of space from within the B-Tree page passed
53416 ** as the first argument. Write into *pIdx the index into pPage->aData[]
53417 ** of the first byte of allocated space. Return either SQLITE_OK or
53418 ** an error code (usually SQLITE_CORRUPT).
53419 **
53420 ** The caller guarantees that there is sufficient space to make the
53421 ** allocation.  This routine might need to defragment in order to bring
53422 ** all the space together, however.  This routine will avoid using
53423 ** the first two bytes past the cell pointer area since presumably this
53424 ** allocation is being made in order to insert a new cell, so we will
53425 ** also end up needing a new cell pointer.
53426 */
53427 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
53428   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
53429   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
53430   int top;                             /* First byte of cell content area */
53431   int gap;        /* First byte of gap between cell pointers and cell content */
53432   int rc;         /* Integer return code */
53433   int usableSize; /* Usable size of the page */
53434 
53435   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53436   assert( pPage->pBt );
53437   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53438   assert( nByte>=0 );  /* Minimum cell size is 4 */
53439   assert( pPage->nFree>=nByte );
53440   assert( pPage->nOverflow==0 );
53441   usableSize = pPage->pBt->usableSize;
53442   assert( nByte < usableSize-8 );
53443 
53444   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
53445   gap = pPage->cellOffset + 2*pPage->nCell;
53446   assert( gap<=65536 );
53447   top = get2byte(&data[hdr+5]);
53448   if( gap>top ){
53449     if( top==0 ){
53450       top = 65536;
53451     }else{
53452       return SQLITE_CORRUPT_BKPT;
53453     }
53454   }
53455 
53456   /* If there is enough space between gap and top for one more cell pointer
53457   ** array entry offset, and if the freelist is not empty, then search the
53458   ** freelist looking for a free slot big enough to satisfy the request.
53459   */
53460   testcase( gap+2==top );
53461   testcase( gap+1==top );
53462   testcase( gap==top );
53463   if( gap+2<=top && (data[hdr+1] || data[hdr+2]) ){
53464     int pc, addr;
53465     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
53466       int size;            /* Size of the free slot */
53467       if( pc>usableSize-4 || pc<addr+4 ){
53468         return SQLITE_CORRUPT_BKPT;
53469       }
53470       size = get2byte(&data[pc+2]);
53471       if( size>=nByte ){
53472         int x = size - nByte;
53473         testcase( x==4 );
53474         testcase( x==3 );
53475         if( x<4 ){
53476           if( data[hdr+7]>=60 ) goto defragment_page;
53477           /* Remove the slot from the free-list. Update the number of
53478           ** fragmented bytes within the page. */
53479           memcpy(&data[addr], &data[pc], 2);
53480           data[hdr+7] += (u8)x;
53481         }else if( size+pc > usableSize ){
53482           return SQLITE_CORRUPT_BKPT;
53483         }else{
53484           /* The slot remains on the free-list. Reduce its size to account
53485           ** for the portion used by the new allocation. */
53486           put2byte(&data[pc+2], x);
53487         }
53488         *pIdx = pc + x;
53489         return SQLITE_OK;
53490       }
53491     }
53492   }
53493 
53494   /* The request could not be fulfilled using a freelist slot.  Check
53495   ** to see if defragmentation is necessary.
53496   */
53497   testcase( gap+2+nByte==top );
53498   if( gap+2+nByte>top ){
53499 defragment_page:
53500     testcase( pPage->nCell==0 );
53501     rc = defragmentPage(pPage);
53502     if( rc ) return rc;
53503     top = get2byteNotZero(&data[hdr+5]);
53504     assert( gap+nByte<=top );
53505   }
53506 
53507 
53508   /* Allocate memory from the gap in between the cell pointer array
53509   ** and the cell content area.  The btreeInitPage() call has already
53510   ** validated the freelist.  Given that the freelist is valid, there
53511   ** is no way that the allocation can extend off the end of the page.
53512   ** The assert() below verifies the previous sentence.
53513   */
53514   top -= nByte;
53515   put2byte(&data[hdr+5], top);
53516   assert( top+nByte <= (int)pPage->pBt->usableSize );
53517   *pIdx = top;
53518   return SQLITE_OK;
53519 }
53520 
53521 /*
53522 ** Return a section of the pPage->aData to the freelist.
53523 ** The first byte of the new free block is pPage->aData[iStart]
53524 ** and the size of the block is iSize bytes.
53525 **
53526 ** Adjacent freeblocks are coalesced.
53527 **
53528 ** Note that even though the freeblock list was checked by btreeInitPage(),
53529 ** that routine will not detect overlap between cells or freeblocks.  Nor
53530 ** does it detect cells or freeblocks that encrouch into the reserved bytes
53531 ** at the end of the page.  So do additional corruption checks inside this
53532 ** routine and return SQLITE_CORRUPT if any problems are found.
53533 */
53534 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
53535   u16 iPtr;                             /* Address of ptr to next freeblock */
53536   u16 iFreeBlk;                         /* Address of the next freeblock */
53537   u8 hdr;                               /* Page header size.  0 or 100 */
53538   u8 nFrag = 0;                         /* Reduction in fragmentation */
53539   u16 iOrigSize = iSize;                /* Original value of iSize */
53540   u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
53541   u32 iEnd = iStart + iSize;            /* First byte past the iStart buffer */
53542   unsigned char *data = pPage->aData;   /* Page content */
53543 
53544   assert( pPage->pBt!=0 );
53545   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53546   assert( iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
53547   assert( iEnd <= pPage->pBt->usableSize );
53548   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53549   assert( iSize>=4 );   /* Minimum cell size is 4 */
53550   assert( iStart<=iLast );
53551 
53552   /* Overwrite deleted information with zeros when the secure_delete
53553   ** option is enabled */
53554   if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
53555     memset(&data[iStart], 0, iSize);
53556   }
53557 
53558   /* The list of freeblocks must be in ascending order.  Find the
53559   ** spot on the list where iStart should be inserted.
53560   */
53561   hdr = pPage->hdrOffset;
53562   iPtr = hdr + 1;
53563   if( data[iPtr+1]==0 && data[iPtr]==0 ){
53564     iFreeBlk = 0;  /* Shortcut for the case when the freelist is empty */
53565   }else{
53566     while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){
53567       if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT;
53568       iPtr = iFreeBlk;
53569     }
53570     if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
53571     assert( iFreeBlk>iPtr || iFreeBlk==0 );
53572 
53573     /* At this point:
53574     **    iFreeBlk:   First freeblock after iStart, or zero if none
53575     **    iPtr:       The address of a pointer iFreeBlk
53576     **
53577     ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
53578     */
53579     if( iFreeBlk && iEnd+3>=iFreeBlk ){
53580       nFrag = iFreeBlk - iEnd;
53581       if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
53582       iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
53583       iSize = iEnd - iStart;
53584       iFreeBlk = get2byte(&data[iFreeBlk]);
53585     }
53586 
53587     /* If iPtr is another freeblock (that is, if iPtr is not the freelist
53588     ** pointer in the page header) then check to see if iStart should be
53589     ** coalesced onto the end of iPtr.
53590     */
53591     if( iPtr>hdr+1 ){
53592       int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
53593       if( iPtrEnd+3>=iStart ){
53594         if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
53595         nFrag += iStart - iPtrEnd;
53596         iSize = iEnd - iPtr;
53597         iStart = iPtr;
53598       }
53599     }
53600     if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
53601     data[hdr+7] -= nFrag;
53602   }
53603   if( iStart==get2byte(&data[hdr+5]) ){
53604     /* The new freeblock is at the beginning of the cell content area,
53605     ** so just extend the cell content area rather than create another
53606     ** freelist entry */
53607     if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
53608     put2byte(&data[hdr+1], iFreeBlk);
53609     put2byte(&data[hdr+5], iEnd);
53610   }else{
53611     /* Insert the new freeblock into the freelist */
53612     put2byte(&data[iPtr], iStart);
53613     put2byte(&data[iStart], iFreeBlk);
53614     put2byte(&data[iStart+2], iSize);
53615   }
53616   pPage->nFree += iOrigSize;
53617   return SQLITE_OK;
53618 }
53619 
53620 /*
53621 ** Decode the flags byte (the first byte of the header) for a page
53622 ** and initialize fields of the MemPage structure accordingly.
53623 **
53624 ** Only the following combinations are supported.  Anything different
53625 ** indicates a corrupt database files:
53626 **
53627 **         PTF_ZERODATA
53628 **         PTF_ZERODATA | PTF_LEAF
53629 **         PTF_LEAFDATA | PTF_INTKEY
53630 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
53631 */
53632 static int decodeFlags(MemPage *pPage, int flagByte){
53633   BtShared *pBt;     /* A copy of pPage->pBt */
53634 
53635   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
53636   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53637   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
53638   flagByte &= ~PTF_LEAF;
53639   pPage->childPtrSize = 4-4*pPage->leaf;
53640   pBt = pPage->pBt;
53641   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
53642     pPage->intKey = 1;
53643     pPage->intKeyLeaf = pPage->leaf;
53644     pPage->noPayload = !pPage->leaf;
53645     pPage->maxLocal = pBt->maxLeaf;
53646     pPage->minLocal = pBt->minLeaf;
53647   }else if( flagByte==PTF_ZERODATA ){
53648     pPage->intKey = 0;
53649     pPage->intKeyLeaf = 0;
53650     pPage->noPayload = 0;
53651     pPage->maxLocal = pBt->maxLocal;
53652     pPage->minLocal = pBt->minLocal;
53653   }else{
53654     return SQLITE_CORRUPT_BKPT;
53655   }
53656   pPage->max1bytePayload = pBt->max1bytePayload;
53657   return SQLITE_OK;
53658 }
53659 
53660 /*
53661 ** Initialize the auxiliary information for a disk block.
53662 **
53663 ** Return SQLITE_OK on success.  If we see that the page does
53664 ** not contain a well-formed database page, then return
53665 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
53666 ** guarantee that the page is well-formed.  It only shows that
53667 ** we failed to detect any corruption.
53668 */
53669 static int btreeInitPage(MemPage *pPage){
53670 
53671   assert( pPage->pBt!=0 );
53672   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53673   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
53674   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
53675   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
53676 
53677   if( !pPage->isInit ){
53678     u16 pc;            /* Address of a freeblock within pPage->aData[] */
53679     u8 hdr;            /* Offset to beginning of page header */
53680     u8 *data;          /* Equal to pPage->aData */
53681     BtShared *pBt;        /* The main btree structure */
53682     int usableSize;    /* Amount of usable space on each page */
53683     u16 cellOffset;    /* Offset from start of page to first cell pointer */
53684     int nFree;         /* Number of unused bytes on the page */
53685     int top;           /* First byte of the cell content area */
53686     int iCellFirst;    /* First allowable cell or freeblock offset */
53687     int iCellLast;     /* Last possible cell or freeblock offset */
53688 
53689     pBt = pPage->pBt;
53690 
53691     hdr = pPage->hdrOffset;
53692     data = pPage->aData;
53693     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
53694     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
53695     pPage->maskPage = (u16)(pBt->pageSize - 1);
53696     pPage->nOverflow = 0;
53697     usableSize = pBt->usableSize;
53698     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
53699     pPage->aDataEnd = &data[usableSize];
53700     pPage->aCellIdx = &data[cellOffset];
53701     top = get2byteNotZero(&data[hdr+5]);
53702     pPage->nCell = get2byte(&data[hdr+3]);
53703     if( pPage->nCell>MX_CELL(pBt) ){
53704       /* To many cells for a single page.  The page must be corrupt */
53705       return SQLITE_CORRUPT_BKPT;
53706     }
53707     testcase( pPage->nCell==MX_CELL(pBt) );
53708 
53709     /* A malformed database page might cause us to read past the end
53710     ** of page when parsing a cell.
53711     **
53712     ** The following block of code checks early to see if a cell extends
53713     ** past the end of a page boundary and causes SQLITE_CORRUPT to be
53714     ** returned if it does.
53715     */
53716     iCellFirst = cellOffset + 2*pPage->nCell;
53717     iCellLast = usableSize - 4;
53718 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
53719     {
53720       int i;            /* Index into the cell pointer array */
53721       int sz;           /* Size of a cell */
53722 
53723       if( !pPage->leaf ) iCellLast--;
53724       for(i=0; i<pPage->nCell; i++){
53725         pc = get2byte(&data[cellOffset+i*2]);
53726         testcase( pc==iCellFirst );
53727         testcase( pc==iCellLast );
53728         if( pc<iCellFirst || pc>iCellLast ){
53729           return SQLITE_CORRUPT_BKPT;
53730         }
53731         sz = cellSizePtr(pPage, &data[pc]);
53732         testcase( pc+sz==usableSize );
53733         if( pc+sz>usableSize ){
53734           return SQLITE_CORRUPT_BKPT;
53735         }
53736       }
53737       if( !pPage->leaf ) iCellLast++;
53738     }
53739 #endif
53740 
53741     /* Compute the total free space on the page */
53742     pc = get2byte(&data[hdr+1]);
53743     nFree = data[hdr+7] + top;
53744     while( pc>0 ){
53745       u16 next, size;
53746       if( pc<iCellFirst || pc>iCellLast ){
53747         /* Start of free block is off the page */
53748         return SQLITE_CORRUPT_BKPT;
53749       }
53750       next = get2byte(&data[pc]);
53751       size = get2byte(&data[pc+2]);
53752       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
53753         /* Free blocks must be in ascending order. And the last byte of
53754         ** the free-block must lie on the database page.  */
53755         return SQLITE_CORRUPT_BKPT;
53756       }
53757       nFree = nFree + size;
53758       pc = next;
53759     }
53760 
53761     /* At this point, nFree contains the sum of the offset to the start
53762     ** of the cell-content area plus the number of free bytes within
53763     ** the cell-content area. If this is greater than the usable-size
53764     ** of the page, then the page must be corrupted. This check also
53765     ** serves to verify that the offset to the start of the cell-content
53766     ** area, according to the page header, lies within the page.
53767     */
53768     if( nFree>usableSize ){
53769       return SQLITE_CORRUPT_BKPT;
53770     }
53771     pPage->nFree = (u16)(nFree - iCellFirst);
53772     pPage->isInit = 1;
53773   }
53774   return SQLITE_OK;
53775 }
53776 
53777 /*
53778 ** Set up a raw page so that it looks like a database page holding
53779 ** no entries.
53780 */
53781 static void zeroPage(MemPage *pPage, int flags){
53782   unsigned char *data = pPage->aData;
53783   BtShared *pBt = pPage->pBt;
53784   u8 hdr = pPage->hdrOffset;
53785   u16 first;
53786 
53787   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
53788   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
53789   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
53790   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53791   assert( sqlite3_mutex_held(pBt->mutex) );
53792   if( pBt->btsFlags & BTS_SECURE_DELETE ){
53793     memset(&data[hdr], 0, pBt->usableSize - hdr);
53794   }
53795   data[hdr] = (char)flags;
53796   first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
53797   memset(&data[hdr+1], 0, 4);
53798   data[hdr+7] = 0;
53799   put2byte(&data[hdr+5], pBt->usableSize);
53800   pPage->nFree = (u16)(pBt->usableSize - first);
53801   decodeFlags(pPage, flags);
53802   pPage->cellOffset = first;
53803   pPage->aDataEnd = &data[pBt->usableSize];
53804   pPage->aCellIdx = &data[first];
53805   pPage->nOverflow = 0;
53806   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
53807   pPage->maskPage = (u16)(pBt->pageSize - 1);
53808   pPage->nCell = 0;
53809   pPage->isInit = 1;
53810 }
53811 
53812 
53813 /*
53814 ** Convert a DbPage obtained from the pager into a MemPage used by
53815 ** the btree layer.
53816 */
53817 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
53818   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
53819   pPage->aData = sqlite3PagerGetData(pDbPage);
53820   pPage->pDbPage = pDbPage;
53821   pPage->pBt = pBt;
53822   pPage->pgno = pgno;
53823   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
53824   return pPage;
53825 }
53826 
53827 /*
53828 ** Get a page from the pager.  Initialize the MemPage.pBt and
53829 ** MemPage.aData elements if needed.
53830 **
53831 ** If the noContent flag is set, it means that we do not care about
53832 ** the content of the page at this time.  So do not go to the disk
53833 ** to fetch the content.  Just fill in the content with zeros for now.
53834 ** If in the future we call sqlite3PagerWrite() on this page, that
53835 ** means we have started to be concerned about content and the disk
53836 ** read should occur at that point.
53837 */
53838 static int btreeGetPage(
53839   BtShared *pBt,       /* The btree */
53840   Pgno pgno,           /* Number of the page to fetch */
53841   MemPage **ppPage,    /* Return the page in this parameter */
53842   int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
53843 ){
53844   int rc;
53845   DbPage *pDbPage;
53846 
53847   assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
53848   assert( sqlite3_mutex_held(pBt->mutex) );
53849   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
53850   if( rc ) return rc;
53851   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
53852   return SQLITE_OK;
53853 }
53854 
53855 /*
53856 ** Retrieve a page from the pager cache. If the requested page is not
53857 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
53858 ** MemPage.aData elements if needed.
53859 */
53860 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
53861   DbPage *pDbPage;
53862   assert( sqlite3_mutex_held(pBt->mutex) );
53863   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
53864   if( pDbPage ){
53865     return btreePageFromDbPage(pDbPage, pgno, pBt);
53866   }
53867   return 0;
53868 }
53869 
53870 /*
53871 ** Return the size of the database file in pages. If there is any kind of
53872 ** error, return ((unsigned int)-1).
53873 */
53874 static Pgno btreePagecount(BtShared *pBt){
53875   return pBt->nPage;
53876 }
53877 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
53878   assert( sqlite3BtreeHoldsMutex(p) );
53879   assert( ((p->pBt->nPage)&0x8000000)==0 );
53880   return btreePagecount(p->pBt);
53881 }
53882 
53883 /*
53884 ** Get a page from the pager and initialize it.  This routine is just a
53885 ** convenience wrapper around separate calls to btreeGetPage() and
53886 ** btreeInitPage().
53887 **
53888 ** If an error occurs, then the value *ppPage is set to is undefined. It
53889 ** may remain unchanged, or it may be set to an invalid value.
53890 */
53891 static int getAndInitPage(
53892   BtShared *pBt,                  /* The database file */
53893   Pgno pgno,                      /* Number of the page to get */
53894   MemPage **ppPage,               /* Write the page pointer here */
53895   int bReadonly                   /* PAGER_GET_READONLY or 0 */
53896 ){
53897   int rc;
53898   assert( sqlite3_mutex_held(pBt->mutex) );
53899   assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 );
53900 
53901   if( pgno>btreePagecount(pBt) ){
53902     rc = SQLITE_CORRUPT_BKPT;
53903   }else{
53904     rc = btreeGetPage(pBt, pgno, ppPage, bReadonly);
53905     if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
53906       rc = btreeInitPage(*ppPage);
53907       if( rc!=SQLITE_OK ){
53908         releasePage(*ppPage);
53909       }
53910     }
53911   }
53912 
53913   testcase( pgno==0 );
53914   assert( pgno!=0 || rc==SQLITE_CORRUPT );
53915   return rc;
53916 }
53917 
53918 /*
53919 ** Release a MemPage.  This should be called once for each prior
53920 ** call to btreeGetPage.
53921 */
53922 static void releasePage(MemPage *pPage){
53923   if( pPage ){
53924     assert( pPage->aData );
53925     assert( pPage->pBt );
53926     assert( pPage->pDbPage!=0 );
53927     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
53928     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
53929     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53930     sqlite3PagerUnrefNotNull(pPage->pDbPage);
53931   }
53932 }
53933 
53934 /*
53935 ** During a rollback, when the pager reloads information into the cache
53936 ** so that the cache is restored to its original state at the start of
53937 ** the transaction, for each page restored this routine is called.
53938 **
53939 ** This routine needs to reset the extra data section at the end of the
53940 ** page to agree with the restored data.
53941 */
53942 static void pageReinit(DbPage *pData){
53943   MemPage *pPage;
53944   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
53945   assert( sqlite3PagerPageRefcount(pData)>0 );
53946   if( pPage->isInit ){
53947     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53948     pPage->isInit = 0;
53949     if( sqlite3PagerPageRefcount(pData)>1 ){
53950       /* pPage might not be a btree page;  it might be an overflow page
53951       ** or ptrmap page or a free page.  In those cases, the following
53952       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
53953       ** But no harm is done by this.  And it is very important that
53954       ** btreeInitPage() be called on every btree page so we make
53955       ** the call for every page that comes in for re-initing. */
53956       btreeInitPage(pPage);
53957     }
53958   }
53959 }
53960 
53961 /*
53962 ** Invoke the busy handler for a btree.
53963 */
53964 static int btreeInvokeBusyHandler(void *pArg){
53965   BtShared *pBt = (BtShared*)pArg;
53966   assert( pBt->db );
53967   assert( sqlite3_mutex_held(pBt->db->mutex) );
53968   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
53969 }
53970 
53971 /*
53972 ** Open a database file.
53973 **
53974 ** zFilename is the name of the database file.  If zFilename is NULL
53975 ** then an ephemeral database is created.  The ephemeral database might
53976 ** be exclusively in memory, or it might use a disk-based memory cache.
53977 ** Either way, the ephemeral database will be automatically deleted
53978 ** when sqlite3BtreeClose() is called.
53979 **
53980 ** If zFilename is ":memory:" then an in-memory database is created
53981 ** that is automatically destroyed when it is closed.
53982 **
53983 ** The "flags" parameter is a bitmask that might contain bits like
53984 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
53985 **
53986 ** If the database is already opened in the same database connection
53987 ** and we are in shared cache mode, then the open will fail with an
53988 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
53989 ** objects in the same database connection since doing so will lead
53990 ** to problems with locking.
53991 */
53992 SQLITE_PRIVATE int sqlite3BtreeOpen(
53993   sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
53994   const char *zFilename,  /* Name of the file containing the BTree database */
53995   sqlite3 *db,            /* Associated database handle */
53996   Btree **ppBtree,        /* Pointer to new Btree object written here */
53997   int flags,              /* Options */
53998   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
53999 ){
54000   BtShared *pBt = 0;             /* Shared part of btree structure */
54001   Btree *p;                      /* Handle to return */
54002   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
54003   int rc = SQLITE_OK;            /* Result code from this function */
54004   u8 nReserve;                   /* Byte of unused space on each page */
54005   unsigned char zDbHeader[100];  /* Database header content */
54006 
54007   /* True if opening an ephemeral, temporary database */
54008   const int isTempDb = zFilename==0 || zFilename[0]==0;
54009 
54010   /* Set the variable isMemdb to true for an in-memory database, or
54011   ** false for a file-based database.
54012   */
54013 #ifdef SQLITE_OMIT_MEMORYDB
54014   const int isMemdb = 0;
54015 #else
54016   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
54017                        || (isTempDb && sqlite3TempInMemory(db))
54018                        || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
54019 #endif
54020 
54021   assert( db!=0 );
54022   assert( pVfs!=0 );
54023   assert( sqlite3_mutex_held(db->mutex) );
54024   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
54025 
54026   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
54027   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
54028 
54029   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
54030   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
54031 
54032   if( isMemdb ){
54033     flags |= BTREE_MEMORY;
54034   }
54035   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
54036     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
54037   }
54038   p = sqlite3MallocZero(sizeof(Btree));
54039   if( !p ){
54040     return SQLITE_NOMEM;
54041   }
54042   p->inTrans = TRANS_NONE;
54043   p->db = db;
54044 #ifndef SQLITE_OMIT_SHARED_CACHE
54045   p->lock.pBtree = p;
54046   p->lock.iTable = 1;
54047 #endif
54048 
54049 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
54050   /*
54051   ** If this Btree is a candidate for shared cache, try to find an
54052   ** existing BtShared object that we can share with
54053   */
54054   if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
54055     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
54056       int nFullPathname = pVfs->mxPathname+1;
54057       char *zFullPathname = sqlite3Malloc(nFullPathname);
54058       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
54059       p->sharable = 1;
54060       if( !zFullPathname ){
54061         sqlite3_free(p);
54062         return SQLITE_NOMEM;
54063       }
54064       if( isMemdb ){
54065         memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
54066       }else{
54067         rc = sqlite3OsFullPathname(pVfs, zFilename,
54068                                    nFullPathname, zFullPathname);
54069         if( rc ){
54070           sqlite3_free(zFullPathname);
54071           sqlite3_free(p);
54072           return rc;
54073         }
54074       }
54075 #if SQLITE_THREADSAFE
54076       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
54077       sqlite3_mutex_enter(mutexOpen);
54078       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
54079       sqlite3_mutex_enter(mutexShared);
54080 #endif
54081       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
54082         assert( pBt->nRef>0 );
54083         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
54084                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
54085           int iDb;
54086           for(iDb=db->nDb-1; iDb>=0; iDb--){
54087             Btree *pExisting = db->aDb[iDb].pBt;
54088             if( pExisting && pExisting->pBt==pBt ){
54089               sqlite3_mutex_leave(mutexShared);
54090               sqlite3_mutex_leave(mutexOpen);
54091               sqlite3_free(zFullPathname);
54092               sqlite3_free(p);
54093               return SQLITE_CONSTRAINT;
54094             }
54095           }
54096           p->pBt = pBt;
54097           pBt->nRef++;
54098           break;
54099         }
54100       }
54101       sqlite3_mutex_leave(mutexShared);
54102       sqlite3_free(zFullPathname);
54103     }
54104 #ifdef SQLITE_DEBUG
54105     else{
54106       /* In debug mode, we mark all persistent databases as sharable
54107       ** even when they are not.  This exercises the locking code and
54108       ** gives more opportunity for asserts(sqlite3_mutex_held())
54109       ** statements to find locking problems.
54110       */
54111       p->sharable = 1;
54112     }
54113 #endif
54114   }
54115 #endif
54116   if( pBt==0 ){
54117     /*
54118     ** The following asserts make sure that structures used by the btree are
54119     ** the right size.  This is to guard against size changes that result
54120     ** when compiling on a different architecture.
54121     */
54122     assert( sizeof(i64)==8 || sizeof(i64)==4 );
54123     assert( sizeof(u64)==8 || sizeof(u64)==4 );
54124     assert( sizeof(u32)==4 );
54125     assert( sizeof(u16)==2 );
54126     assert( sizeof(Pgno)==4 );
54127 
54128     pBt = sqlite3MallocZero( sizeof(*pBt) );
54129     if( pBt==0 ){
54130       rc = SQLITE_NOMEM;
54131       goto btree_open_out;
54132     }
54133     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
54134                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
54135     if( rc==SQLITE_OK ){
54136       sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
54137       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
54138     }
54139     if( rc!=SQLITE_OK ){
54140       goto btree_open_out;
54141     }
54142     pBt->openFlags = (u8)flags;
54143     pBt->db = db;
54144     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
54145     p->pBt = pBt;
54146 
54147     pBt->pCursor = 0;
54148     pBt->pPage1 = 0;
54149     if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
54150 #ifdef SQLITE_SECURE_DELETE
54151     pBt->btsFlags |= BTS_SECURE_DELETE;
54152 #endif
54153     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
54154     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
54155          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
54156       pBt->pageSize = 0;
54157 #ifndef SQLITE_OMIT_AUTOVACUUM
54158       /* If the magic name ":memory:" will create an in-memory database, then
54159       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
54160       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
54161       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
54162       ** regular file-name. In this case the auto-vacuum applies as per normal.
54163       */
54164       if( zFilename && !isMemdb ){
54165         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
54166         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
54167       }
54168 #endif
54169       nReserve = 0;
54170     }else{
54171       nReserve = zDbHeader[20];
54172       pBt->btsFlags |= BTS_PAGESIZE_FIXED;
54173 #ifndef SQLITE_OMIT_AUTOVACUUM
54174       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
54175       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
54176 #endif
54177     }
54178     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
54179     if( rc ) goto btree_open_out;
54180     pBt->usableSize = pBt->pageSize - nReserve;
54181     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
54182 
54183 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
54184     /* Add the new BtShared object to the linked list sharable BtShareds.
54185     */
54186     if( p->sharable ){
54187       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
54188       pBt->nRef = 1;
54189       MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
54190       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
54191         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
54192         if( pBt->mutex==0 ){
54193           rc = SQLITE_NOMEM;
54194           db->mallocFailed = 0;
54195           goto btree_open_out;
54196         }
54197       }
54198       sqlite3_mutex_enter(mutexShared);
54199       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
54200       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
54201       sqlite3_mutex_leave(mutexShared);
54202     }
54203 #endif
54204   }
54205 
54206 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
54207   /* If the new Btree uses a sharable pBtShared, then link the new
54208   ** Btree into the list of all sharable Btrees for the same connection.
54209   ** The list is kept in ascending order by pBt address.
54210   */
54211   if( p->sharable ){
54212     int i;
54213     Btree *pSib;
54214     for(i=0; i<db->nDb; i++){
54215       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
54216         while( pSib->pPrev ){ pSib = pSib->pPrev; }
54217         if( p->pBt<pSib->pBt ){
54218           p->pNext = pSib;
54219           p->pPrev = 0;
54220           pSib->pPrev = p;
54221         }else{
54222           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
54223             pSib = pSib->pNext;
54224           }
54225           p->pNext = pSib->pNext;
54226           p->pPrev = pSib;
54227           if( p->pNext ){
54228             p->pNext->pPrev = p;
54229           }
54230           pSib->pNext = p;
54231         }
54232         break;
54233       }
54234     }
54235   }
54236 #endif
54237   *ppBtree = p;
54238 
54239 btree_open_out:
54240   if( rc!=SQLITE_OK ){
54241     if( pBt && pBt->pPager ){
54242       sqlite3PagerClose(pBt->pPager);
54243     }
54244     sqlite3_free(pBt);
54245     sqlite3_free(p);
54246     *ppBtree = 0;
54247   }else{
54248     /* If the B-Tree was successfully opened, set the pager-cache size to the
54249     ** default value. Except, when opening on an existing shared pager-cache,
54250     ** do not change the pager-cache size.
54251     */
54252     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
54253       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
54254     }
54255   }
54256   if( mutexOpen ){
54257     assert( sqlite3_mutex_held(mutexOpen) );
54258     sqlite3_mutex_leave(mutexOpen);
54259   }
54260   return rc;
54261 }
54262 
54263 /*
54264 ** Decrement the BtShared.nRef counter.  When it reaches zero,
54265 ** remove the BtShared structure from the sharing list.  Return
54266 ** true if the BtShared.nRef counter reaches zero and return
54267 ** false if it is still positive.
54268 */
54269 static int removeFromSharingList(BtShared *pBt){
54270 #ifndef SQLITE_OMIT_SHARED_CACHE
54271   MUTEX_LOGIC( sqlite3_mutex *pMaster; )
54272   BtShared *pList;
54273   int removed = 0;
54274 
54275   assert( sqlite3_mutex_notheld(pBt->mutex) );
54276   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
54277   sqlite3_mutex_enter(pMaster);
54278   pBt->nRef--;
54279   if( pBt->nRef<=0 ){
54280     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
54281       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
54282     }else{
54283       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
54284       while( ALWAYS(pList) && pList->pNext!=pBt ){
54285         pList=pList->pNext;
54286       }
54287       if( ALWAYS(pList) ){
54288         pList->pNext = pBt->pNext;
54289       }
54290     }
54291     if( SQLITE_THREADSAFE ){
54292       sqlite3_mutex_free(pBt->mutex);
54293     }
54294     removed = 1;
54295   }
54296   sqlite3_mutex_leave(pMaster);
54297   return removed;
54298 #else
54299   return 1;
54300 #endif
54301 }
54302 
54303 /*
54304 ** Make sure pBt->pTmpSpace points to an allocation of
54305 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
54306 ** pointer.
54307 */
54308 static void allocateTempSpace(BtShared *pBt){
54309   if( !pBt->pTmpSpace ){
54310     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
54311 
54312     /* One of the uses of pBt->pTmpSpace is to format cells before
54313     ** inserting them into a leaf page (function fillInCell()). If
54314     ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
54315     ** by the various routines that manipulate binary cells. Which
54316     ** can mean that fillInCell() only initializes the first 2 or 3
54317     ** bytes of pTmpSpace, but that the first 4 bytes are copied from
54318     ** it into a database page. This is not actually a problem, but it
54319     ** does cause a valgrind error when the 1 or 2 bytes of unitialized
54320     ** data is passed to system call write(). So to avoid this error,
54321     ** zero the first 4 bytes of temp space here.
54322     **
54323     ** Also:  Provide four bytes of initialized space before the
54324     ** beginning of pTmpSpace as an area available to prepend the
54325     ** left-child pointer to the beginning of a cell.
54326     */
54327     if( pBt->pTmpSpace ){
54328       memset(pBt->pTmpSpace, 0, 8);
54329       pBt->pTmpSpace += 4;
54330     }
54331   }
54332 }
54333 
54334 /*
54335 ** Free the pBt->pTmpSpace allocation
54336 */
54337 static void freeTempSpace(BtShared *pBt){
54338   if( pBt->pTmpSpace ){
54339     pBt->pTmpSpace -= 4;
54340     sqlite3PageFree(pBt->pTmpSpace);
54341     pBt->pTmpSpace = 0;
54342   }
54343 }
54344 
54345 /*
54346 ** Close an open database and invalidate all cursors.
54347 */
54348 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
54349   BtShared *pBt = p->pBt;
54350   BtCursor *pCur;
54351 
54352   /* Close all cursors opened via this handle.  */
54353   assert( sqlite3_mutex_held(p->db->mutex) );
54354   sqlite3BtreeEnter(p);
54355   pCur = pBt->pCursor;
54356   while( pCur ){
54357     BtCursor *pTmp = pCur;
54358     pCur = pCur->pNext;
54359     if( pTmp->pBtree==p ){
54360       sqlite3BtreeCloseCursor(pTmp);
54361     }
54362   }
54363 
54364   /* Rollback any active transaction and free the handle structure.
54365   ** The call to sqlite3BtreeRollback() drops any table-locks held by
54366   ** this handle.
54367   */
54368   sqlite3BtreeRollback(p, SQLITE_OK, 0);
54369   sqlite3BtreeLeave(p);
54370 
54371   /* If there are still other outstanding references to the shared-btree
54372   ** structure, return now. The remainder of this procedure cleans
54373   ** up the shared-btree.
54374   */
54375   assert( p->wantToLock==0 && p->locked==0 );
54376   if( !p->sharable || removeFromSharingList(pBt) ){
54377     /* The pBt is no longer on the sharing list, so we can access
54378     ** it without having to hold the mutex.
54379     **
54380     ** Clean out and delete the BtShared object.
54381     */
54382     assert( !pBt->pCursor );
54383     sqlite3PagerClose(pBt->pPager);
54384     if( pBt->xFreeSchema && pBt->pSchema ){
54385       pBt->xFreeSchema(pBt->pSchema);
54386     }
54387     sqlite3DbFree(0, pBt->pSchema);
54388     freeTempSpace(pBt);
54389     sqlite3_free(pBt);
54390   }
54391 
54392 #ifndef SQLITE_OMIT_SHARED_CACHE
54393   assert( p->wantToLock==0 );
54394   assert( p->locked==0 );
54395   if( p->pPrev ) p->pPrev->pNext = p->pNext;
54396   if( p->pNext ) p->pNext->pPrev = p->pPrev;
54397 #endif
54398 
54399   sqlite3_free(p);
54400   return SQLITE_OK;
54401 }
54402 
54403 /*
54404 ** Change the limit on the number of pages allowed in the cache.
54405 **
54406 ** The maximum number of cache pages is set to the absolute
54407 ** value of mxPage.  If mxPage is negative, the pager will
54408 ** operate asynchronously - it will not stop to do fsync()s
54409 ** to insure data is written to the disk surface before
54410 ** continuing.  Transactions still work if synchronous is off,
54411 ** and the database cannot be corrupted if this program
54412 ** crashes.  But if the operating system crashes or there is
54413 ** an abrupt power failure when synchronous is off, the database
54414 ** could be left in an inconsistent and unrecoverable state.
54415 ** Synchronous is on by default so database corruption is not
54416 ** normally a worry.
54417 */
54418 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
54419   BtShared *pBt = p->pBt;
54420   assert( sqlite3_mutex_held(p->db->mutex) );
54421   sqlite3BtreeEnter(p);
54422   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
54423   sqlite3BtreeLeave(p);
54424   return SQLITE_OK;
54425 }
54426 
54427 #if SQLITE_MAX_MMAP_SIZE>0
54428 /*
54429 ** Change the limit on the amount of the database file that may be
54430 ** memory mapped.
54431 */
54432 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
54433   BtShared *pBt = p->pBt;
54434   assert( sqlite3_mutex_held(p->db->mutex) );
54435   sqlite3BtreeEnter(p);
54436   sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
54437   sqlite3BtreeLeave(p);
54438   return SQLITE_OK;
54439 }
54440 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
54441 
54442 /*
54443 ** Change the way data is synced to disk in order to increase or decrease
54444 ** how well the database resists damage due to OS crashes and power
54445 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
54446 ** there is a high probability of damage)  Level 2 is the default.  There
54447 ** is a very low but non-zero probability of damage.  Level 3 reduces the
54448 ** probability of damage to near zero but with a write performance reduction.
54449 */
54450 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
54451 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
54452   Btree *p,              /* The btree to set the safety level on */
54453   unsigned pgFlags       /* Various PAGER_* flags */
54454 ){
54455   BtShared *pBt = p->pBt;
54456   assert( sqlite3_mutex_held(p->db->mutex) );
54457   sqlite3BtreeEnter(p);
54458   sqlite3PagerSetFlags(pBt->pPager, pgFlags);
54459   sqlite3BtreeLeave(p);
54460   return SQLITE_OK;
54461 }
54462 #endif
54463 
54464 /*
54465 ** Return TRUE if the given btree is set to safety level 1.  In other
54466 ** words, return TRUE if no sync() occurs on the disk files.
54467 */
54468 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
54469   BtShared *pBt = p->pBt;
54470   int rc;
54471   assert( sqlite3_mutex_held(p->db->mutex) );
54472   sqlite3BtreeEnter(p);
54473   assert( pBt && pBt->pPager );
54474   rc = sqlite3PagerNosync(pBt->pPager);
54475   sqlite3BtreeLeave(p);
54476   return rc;
54477 }
54478 
54479 /*
54480 ** Change the default pages size and the number of reserved bytes per page.
54481 ** Or, if the page size has already been fixed, return SQLITE_READONLY
54482 ** without changing anything.
54483 **
54484 ** The page size must be a power of 2 between 512 and 65536.  If the page
54485 ** size supplied does not meet this constraint then the page size is not
54486 ** changed.
54487 **
54488 ** Page sizes are constrained to be a power of two so that the region
54489 ** of the database file used for locking (beginning at PENDING_BYTE,
54490 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
54491 ** at the beginning of a page.
54492 **
54493 ** If parameter nReserve is less than zero, then the number of reserved
54494 ** bytes per page is left unchanged.
54495 **
54496 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
54497 ** and autovacuum mode can no longer be changed.
54498 */
54499 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
54500   int rc = SQLITE_OK;
54501   BtShared *pBt = p->pBt;
54502   assert( nReserve>=-1 && nReserve<=255 );
54503   sqlite3BtreeEnter(p);
54504   if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
54505     sqlite3BtreeLeave(p);
54506     return SQLITE_READONLY;
54507   }
54508   if( nReserve<0 ){
54509     nReserve = pBt->pageSize - pBt->usableSize;
54510   }
54511   assert( nReserve>=0 && nReserve<=255 );
54512   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
54513         ((pageSize-1)&pageSize)==0 ){
54514     assert( (pageSize & 7)==0 );
54515     assert( !pBt->pPage1 && !pBt->pCursor );
54516     pBt->pageSize = (u32)pageSize;
54517     freeTempSpace(pBt);
54518   }
54519   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
54520   pBt->usableSize = pBt->pageSize - (u16)nReserve;
54521   if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
54522   sqlite3BtreeLeave(p);
54523   return rc;
54524 }
54525 
54526 /*
54527 ** Return the currently defined page size
54528 */
54529 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
54530   return p->pBt->pageSize;
54531 }
54532 
54533 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
54534 /*
54535 ** This function is similar to sqlite3BtreeGetReserve(), except that it
54536 ** may only be called if it is guaranteed that the b-tree mutex is already
54537 ** held.
54538 **
54539 ** This is useful in one special case in the backup API code where it is
54540 ** known that the shared b-tree mutex is held, but the mutex on the
54541 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
54542 ** were to be called, it might collide with some other operation on the
54543 ** database handle that owns *p, causing undefined behavior.
54544 */
54545 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
54546   assert( sqlite3_mutex_held(p->pBt->mutex) );
54547   return p->pBt->pageSize - p->pBt->usableSize;
54548 }
54549 #endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
54550 
54551 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
54552 /*
54553 ** Return the number of bytes of space at the end of every page that
54554 ** are intentually left unused.  This is the "reserved" space that is
54555 ** sometimes used by extensions.
54556 */
54557 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
54558   int n;
54559   sqlite3BtreeEnter(p);
54560   n = p->pBt->pageSize - p->pBt->usableSize;
54561   sqlite3BtreeLeave(p);
54562   return n;
54563 }
54564 
54565 /*
54566 ** Set the maximum page count for a database if mxPage is positive.
54567 ** No changes are made if mxPage is 0 or negative.
54568 ** Regardless of the value of mxPage, return the maximum page count.
54569 */
54570 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
54571   int n;
54572   sqlite3BtreeEnter(p);
54573   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
54574   sqlite3BtreeLeave(p);
54575   return n;
54576 }
54577 
54578 /*
54579 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
54580 ** then make no changes.  Always return the value of the BTS_SECURE_DELETE
54581 ** setting after the change.
54582 */
54583 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
54584   int b;
54585   if( p==0 ) return 0;
54586   sqlite3BtreeEnter(p);
54587   if( newFlag>=0 ){
54588     p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
54589     if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
54590   }
54591   b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
54592   sqlite3BtreeLeave(p);
54593   return b;
54594 }
54595 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
54596 
54597 /*
54598 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
54599 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
54600 ** is disabled. The default value for the auto-vacuum property is
54601 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
54602 */
54603 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
54604 #ifdef SQLITE_OMIT_AUTOVACUUM
54605   return SQLITE_READONLY;
54606 #else
54607   BtShared *pBt = p->pBt;
54608   int rc = SQLITE_OK;
54609   u8 av = (u8)autoVacuum;
54610 
54611   sqlite3BtreeEnter(p);
54612   if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
54613     rc = SQLITE_READONLY;
54614   }else{
54615     pBt->autoVacuum = av ?1:0;
54616     pBt->incrVacuum = av==2 ?1:0;
54617   }
54618   sqlite3BtreeLeave(p);
54619   return rc;
54620 #endif
54621 }
54622 
54623 /*
54624 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
54625 ** enabled 1 is returned. Otherwise 0.
54626 */
54627 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
54628 #ifdef SQLITE_OMIT_AUTOVACUUM
54629   return BTREE_AUTOVACUUM_NONE;
54630 #else
54631   int rc;
54632   sqlite3BtreeEnter(p);
54633   rc = (
54634     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
54635     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
54636     BTREE_AUTOVACUUM_INCR
54637   );
54638   sqlite3BtreeLeave(p);
54639   return rc;
54640 #endif
54641 }
54642 
54643 
54644 /*
54645 ** Get a reference to pPage1 of the database file.  This will
54646 ** also acquire a readlock on that file.
54647 **
54648 ** SQLITE_OK is returned on success.  If the file is not a
54649 ** well-formed database file, then SQLITE_CORRUPT is returned.
54650 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
54651 ** is returned if we run out of memory.
54652 */
54653 static int lockBtree(BtShared *pBt){
54654   int rc;              /* Result code from subfunctions */
54655   MemPage *pPage1;     /* Page 1 of the database file */
54656   int nPage;           /* Number of pages in the database */
54657   int nPageFile = 0;   /* Number of pages in the database file */
54658   int nPageHeader;     /* Number of pages in the database according to hdr */
54659 
54660   assert( sqlite3_mutex_held(pBt->mutex) );
54661   assert( pBt->pPage1==0 );
54662   rc = sqlite3PagerSharedLock(pBt->pPager);
54663   if( rc!=SQLITE_OK ) return rc;
54664   rc = btreeGetPage(pBt, 1, &pPage1, 0);
54665   if( rc!=SQLITE_OK ) return rc;
54666 
54667   /* Do some checking to help insure the file we opened really is
54668   ** a valid database file.
54669   */
54670   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
54671   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
54672   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
54673     nPage = nPageFile;
54674   }
54675   if( nPage>0 ){
54676     u32 pageSize;
54677     u32 usableSize;
54678     u8 *page1 = pPage1->aData;
54679     rc = SQLITE_NOTADB;
54680     if( memcmp(page1, zMagicHeader, 16)!=0 ){
54681       goto page1_init_failed;
54682     }
54683 
54684 #ifdef SQLITE_OMIT_WAL
54685     if( page1[18]>1 ){
54686       pBt->btsFlags |= BTS_READ_ONLY;
54687     }
54688     if( page1[19]>1 ){
54689       goto page1_init_failed;
54690     }
54691 #else
54692     if( page1[18]>2 ){
54693       pBt->btsFlags |= BTS_READ_ONLY;
54694     }
54695     if( page1[19]>2 ){
54696       goto page1_init_failed;
54697     }
54698 
54699     /* If the write version is set to 2, this database should be accessed
54700     ** in WAL mode. If the log is not already open, open it now. Then
54701     ** return SQLITE_OK and return without populating BtShared.pPage1.
54702     ** The caller detects this and calls this function again. This is
54703     ** required as the version of page 1 currently in the page1 buffer
54704     ** may not be the latest version - there may be a newer one in the log
54705     ** file.
54706     */
54707     if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
54708       int isOpen = 0;
54709       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
54710       if( rc!=SQLITE_OK ){
54711         goto page1_init_failed;
54712       }else if( isOpen==0 ){
54713         releasePage(pPage1);
54714         return SQLITE_OK;
54715       }
54716       rc = SQLITE_NOTADB;
54717     }
54718 #endif
54719 
54720     /* The maximum embedded fraction must be exactly 25%.  And the minimum
54721     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
54722     ** The original design allowed these amounts to vary, but as of
54723     ** version 3.6.0, we require them to be fixed.
54724     */
54725     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
54726       goto page1_init_failed;
54727     }
54728     pageSize = (page1[16]<<8) | (page1[17]<<16);
54729     if( ((pageSize-1)&pageSize)!=0
54730      || pageSize>SQLITE_MAX_PAGE_SIZE
54731      || pageSize<=256
54732     ){
54733       goto page1_init_failed;
54734     }
54735     assert( (pageSize & 7)==0 );
54736     usableSize = pageSize - page1[20];
54737     if( (u32)pageSize!=pBt->pageSize ){
54738       /* After reading the first page of the database assuming a page size
54739       ** of BtShared.pageSize, we have discovered that the page-size is
54740       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
54741       ** zero and return SQLITE_OK. The caller will call this function
54742       ** again with the correct page-size.
54743       */
54744       releasePage(pPage1);
54745       pBt->usableSize = usableSize;
54746       pBt->pageSize = pageSize;
54747       freeTempSpace(pBt);
54748       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
54749                                    pageSize-usableSize);
54750       return rc;
54751     }
54752     if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
54753       rc = SQLITE_CORRUPT_BKPT;
54754       goto page1_init_failed;
54755     }
54756     if( usableSize<480 ){
54757       goto page1_init_failed;
54758     }
54759     pBt->pageSize = pageSize;
54760     pBt->usableSize = usableSize;
54761 #ifndef SQLITE_OMIT_AUTOVACUUM
54762     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
54763     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
54764 #endif
54765   }
54766 
54767   /* maxLocal is the maximum amount of payload to store locally for
54768   ** a cell.  Make sure it is small enough so that at least minFanout
54769   ** cells can will fit on one page.  We assume a 10-byte page header.
54770   ** Besides the payload, the cell must store:
54771   **     2-byte pointer to the cell
54772   **     4-byte child pointer
54773   **     9-byte nKey value
54774   **     4-byte nData value
54775   **     4-byte overflow page pointer
54776   ** So a cell consists of a 2-byte pointer, a header which is as much as
54777   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
54778   ** page pointer.
54779   */
54780   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
54781   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
54782   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
54783   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
54784   if( pBt->maxLocal>127 ){
54785     pBt->max1bytePayload = 127;
54786   }else{
54787     pBt->max1bytePayload = (u8)pBt->maxLocal;
54788   }
54789   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
54790   pBt->pPage1 = pPage1;
54791   pBt->nPage = nPage;
54792   return SQLITE_OK;
54793 
54794 page1_init_failed:
54795   releasePage(pPage1);
54796   pBt->pPage1 = 0;
54797   return rc;
54798 }
54799 
54800 #ifndef NDEBUG
54801 /*
54802 ** Return the number of cursors open on pBt. This is for use
54803 ** in assert() expressions, so it is only compiled if NDEBUG is not
54804 ** defined.
54805 **
54806 ** Only write cursors are counted if wrOnly is true.  If wrOnly is
54807 ** false then all cursors are counted.
54808 **
54809 ** For the purposes of this routine, a cursor is any cursor that
54810 ** is capable of reading or writing to the database.  Cursors that
54811 ** have been tripped into the CURSOR_FAULT state are not counted.
54812 */
54813 static int countValidCursors(BtShared *pBt, int wrOnly){
54814   BtCursor *pCur;
54815   int r = 0;
54816   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
54817     if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
54818      && pCur->eState!=CURSOR_FAULT ) r++;
54819   }
54820   return r;
54821 }
54822 #endif
54823 
54824 /*
54825 ** If there are no outstanding cursors and we are not in the middle
54826 ** of a transaction but there is a read lock on the database, then
54827 ** this routine unrefs the first page of the database file which
54828 ** has the effect of releasing the read lock.
54829 **
54830 ** If there is a transaction in progress, this routine is a no-op.
54831 */
54832 static void unlockBtreeIfUnused(BtShared *pBt){
54833   assert( sqlite3_mutex_held(pBt->mutex) );
54834   assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
54835   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
54836     MemPage *pPage1 = pBt->pPage1;
54837     assert( pPage1->aData );
54838     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
54839     pBt->pPage1 = 0;
54840     releasePage(pPage1);
54841   }
54842 }
54843 
54844 /*
54845 ** If pBt points to an empty file then convert that empty file
54846 ** into a new empty database by initializing the first page of
54847 ** the database.
54848 */
54849 static int newDatabase(BtShared *pBt){
54850   MemPage *pP1;
54851   unsigned char *data;
54852   int rc;
54853 
54854   assert( sqlite3_mutex_held(pBt->mutex) );
54855   if( pBt->nPage>0 ){
54856     return SQLITE_OK;
54857   }
54858   pP1 = pBt->pPage1;
54859   assert( pP1!=0 );
54860   data = pP1->aData;
54861   rc = sqlite3PagerWrite(pP1->pDbPage);
54862   if( rc ) return rc;
54863   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
54864   assert( sizeof(zMagicHeader)==16 );
54865   data[16] = (u8)((pBt->pageSize>>8)&0xff);
54866   data[17] = (u8)((pBt->pageSize>>16)&0xff);
54867   data[18] = 1;
54868   data[19] = 1;
54869   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
54870   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
54871   data[21] = 64;
54872   data[22] = 32;
54873   data[23] = 32;
54874   memset(&data[24], 0, 100-24);
54875   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
54876   pBt->btsFlags |= BTS_PAGESIZE_FIXED;
54877 #ifndef SQLITE_OMIT_AUTOVACUUM
54878   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
54879   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
54880   put4byte(&data[36 + 4*4], pBt->autoVacuum);
54881   put4byte(&data[36 + 7*4], pBt->incrVacuum);
54882 #endif
54883   pBt->nPage = 1;
54884   data[31] = 1;
54885   return SQLITE_OK;
54886 }
54887 
54888 /*
54889 ** Initialize the first page of the database file (creating a database
54890 ** consisting of a single page and no schema objects). Return SQLITE_OK
54891 ** if successful, or an SQLite error code otherwise.
54892 */
54893 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
54894   int rc;
54895   sqlite3BtreeEnter(p);
54896   p->pBt->nPage = 0;
54897   rc = newDatabase(p->pBt);
54898   sqlite3BtreeLeave(p);
54899   return rc;
54900 }
54901 
54902 /*
54903 ** Attempt to start a new transaction. A write-transaction
54904 ** is started if the second argument is nonzero, otherwise a read-
54905 ** transaction.  If the second argument is 2 or more and exclusive
54906 ** transaction is started, meaning that no other process is allowed
54907 ** to access the database.  A preexisting transaction may not be
54908 ** upgraded to exclusive by calling this routine a second time - the
54909 ** exclusivity flag only works for a new transaction.
54910 **
54911 ** A write-transaction must be started before attempting any
54912 ** changes to the database.  None of the following routines
54913 ** will work unless a transaction is started first:
54914 **
54915 **      sqlite3BtreeCreateTable()
54916 **      sqlite3BtreeCreateIndex()
54917 **      sqlite3BtreeClearTable()
54918 **      sqlite3BtreeDropTable()
54919 **      sqlite3BtreeInsert()
54920 **      sqlite3BtreeDelete()
54921 **      sqlite3BtreeUpdateMeta()
54922 **
54923 ** If an initial attempt to acquire the lock fails because of lock contention
54924 ** and the database was previously unlocked, then invoke the busy handler
54925 ** if there is one.  But if there was previously a read-lock, do not
54926 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
54927 ** returned when there is already a read-lock in order to avoid a deadlock.
54928 **
54929 ** Suppose there are two processes A and B.  A has a read lock and B has
54930 ** a reserved lock.  B tries to promote to exclusive but is blocked because
54931 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
54932 ** One or the other of the two processes must give way or there can be
54933 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
54934 ** when A already has a read lock, we encourage A to give up and let B
54935 ** proceed.
54936 */
54937 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
54938   sqlite3 *pBlock = 0;
54939   BtShared *pBt = p->pBt;
54940   int rc = SQLITE_OK;
54941 
54942   sqlite3BtreeEnter(p);
54943   btreeIntegrity(p);
54944 
54945   /* If the btree is already in a write-transaction, or it
54946   ** is already in a read-transaction and a read-transaction
54947   ** is requested, this is a no-op.
54948   */
54949   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
54950     goto trans_begun;
54951   }
54952   assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
54953 
54954   /* Write transactions are not possible on a read-only database */
54955   if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
54956     rc = SQLITE_READONLY;
54957     goto trans_begun;
54958   }
54959 
54960 #ifndef SQLITE_OMIT_SHARED_CACHE
54961   /* If another database handle has already opened a write transaction
54962   ** on this shared-btree structure and a second write transaction is
54963   ** requested, return SQLITE_LOCKED.
54964   */
54965   if( (wrflag && pBt->inTransaction==TRANS_WRITE)
54966    || (pBt->btsFlags & BTS_PENDING)!=0
54967   ){
54968     pBlock = pBt->pWriter->db;
54969   }else if( wrflag>1 ){
54970     BtLock *pIter;
54971     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
54972       if( pIter->pBtree!=p ){
54973         pBlock = pIter->pBtree->db;
54974         break;
54975       }
54976     }
54977   }
54978   if( pBlock ){
54979     sqlite3ConnectionBlocked(p->db, pBlock);
54980     rc = SQLITE_LOCKED_SHAREDCACHE;
54981     goto trans_begun;
54982   }
54983 #endif
54984 
54985   /* Any read-only or read-write transaction implies a read-lock on
54986   ** page 1. So if some other shared-cache client already has a write-lock
54987   ** on page 1, the transaction cannot be opened. */
54988   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
54989   if( SQLITE_OK!=rc ) goto trans_begun;
54990 
54991   pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
54992   if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
54993   do {
54994     /* Call lockBtree() until either pBt->pPage1 is populated or
54995     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
54996     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
54997     ** reading page 1 it discovers that the page-size of the database
54998     ** file is not pBt->pageSize. In this case lockBtree() will update
54999     ** pBt->pageSize to the page-size of the file on disk.
55000     */
55001     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
55002 
55003     if( rc==SQLITE_OK && wrflag ){
55004       if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
55005         rc = SQLITE_READONLY;
55006       }else{
55007         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
55008         if( rc==SQLITE_OK ){
55009           rc = newDatabase(pBt);
55010         }
55011       }
55012     }
55013 
55014     if( rc!=SQLITE_OK ){
55015       unlockBtreeIfUnused(pBt);
55016     }
55017   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
55018           btreeInvokeBusyHandler(pBt) );
55019 
55020   if( rc==SQLITE_OK ){
55021     if( p->inTrans==TRANS_NONE ){
55022       pBt->nTransaction++;
55023 #ifndef SQLITE_OMIT_SHARED_CACHE
55024       if( p->sharable ){
55025         assert( p->lock.pBtree==p && p->lock.iTable==1 );
55026         p->lock.eLock = READ_LOCK;
55027         p->lock.pNext = pBt->pLock;
55028         pBt->pLock = &p->lock;
55029       }
55030 #endif
55031     }
55032     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
55033     if( p->inTrans>pBt->inTransaction ){
55034       pBt->inTransaction = p->inTrans;
55035     }
55036     if( wrflag ){
55037       MemPage *pPage1 = pBt->pPage1;
55038 #ifndef SQLITE_OMIT_SHARED_CACHE
55039       assert( !pBt->pWriter );
55040       pBt->pWriter = p;
55041       pBt->btsFlags &= ~BTS_EXCLUSIVE;
55042       if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
55043 #endif
55044 
55045       /* If the db-size header field is incorrect (as it may be if an old
55046       ** client has been writing the database file), update it now. Doing
55047       ** this sooner rather than later means the database size can safely
55048       ** re-read the database size from page 1 if a savepoint or transaction
55049       ** rollback occurs within the transaction.
55050       */
55051       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
55052         rc = sqlite3PagerWrite(pPage1->pDbPage);
55053         if( rc==SQLITE_OK ){
55054           put4byte(&pPage1->aData[28], pBt->nPage);
55055         }
55056       }
55057     }
55058   }
55059 
55060 
55061 trans_begun:
55062   if( rc==SQLITE_OK && wrflag ){
55063     /* This call makes sure that the pager has the correct number of
55064     ** open savepoints. If the second parameter is greater than 0 and
55065     ** the sub-journal is not already open, then it will be opened here.
55066     */
55067     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
55068   }
55069 
55070   btreeIntegrity(p);
55071   sqlite3BtreeLeave(p);
55072   return rc;
55073 }
55074 
55075 #ifndef SQLITE_OMIT_AUTOVACUUM
55076 
55077 /*
55078 ** Set the pointer-map entries for all children of page pPage. Also, if
55079 ** pPage contains cells that point to overflow pages, set the pointer
55080 ** map entries for the overflow pages as well.
55081 */
55082 static int setChildPtrmaps(MemPage *pPage){
55083   int i;                             /* Counter variable */
55084   int nCell;                         /* Number of cells in page pPage */
55085   int rc;                            /* Return code */
55086   BtShared *pBt = pPage->pBt;
55087   u8 isInitOrig = pPage->isInit;
55088   Pgno pgno = pPage->pgno;
55089 
55090   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55091   rc = btreeInitPage(pPage);
55092   if( rc!=SQLITE_OK ){
55093     goto set_child_ptrmaps_out;
55094   }
55095   nCell = pPage->nCell;
55096 
55097   for(i=0; i<nCell; i++){
55098     u8 *pCell = findCell(pPage, i);
55099 
55100     ptrmapPutOvflPtr(pPage, pCell, &rc);
55101 
55102     if( !pPage->leaf ){
55103       Pgno childPgno = get4byte(pCell);
55104       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
55105     }
55106   }
55107 
55108   if( !pPage->leaf ){
55109     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
55110     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
55111   }
55112 
55113 set_child_ptrmaps_out:
55114   pPage->isInit = isInitOrig;
55115   return rc;
55116 }
55117 
55118 /*
55119 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
55120 ** that it points to iTo. Parameter eType describes the type of pointer to
55121 ** be modified, as  follows:
55122 **
55123 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
55124 **                   page of pPage.
55125 **
55126 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
55127 **                   page pointed to by one of the cells on pPage.
55128 **
55129 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
55130 **                   overflow page in the list.
55131 */
55132 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
55133   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55134   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55135   if( eType==PTRMAP_OVERFLOW2 ){
55136     /* The pointer is always the first 4 bytes of the page in this case.  */
55137     if( get4byte(pPage->aData)!=iFrom ){
55138       return SQLITE_CORRUPT_BKPT;
55139     }
55140     put4byte(pPage->aData, iTo);
55141   }else{
55142     u8 isInitOrig = pPage->isInit;
55143     int i;
55144     int nCell;
55145 
55146     btreeInitPage(pPage);
55147     nCell = pPage->nCell;
55148 
55149     for(i=0; i<nCell; i++){
55150       u8 *pCell = findCell(pPage, i);
55151       if( eType==PTRMAP_OVERFLOW1 ){
55152         CellInfo info;
55153         btreeParseCellPtr(pPage, pCell, &info);
55154         if( info.iOverflow
55155          && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
55156          && iFrom==get4byte(&pCell[info.iOverflow])
55157         ){
55158           put4byte(&pCell[info.iOverflow], iTo);
55159           break;
55160         }
55161       }else{
55162         if( get4byte(pCell)==iFrom ){
55163           put4byte(pCell, iTo);
55164           break;
55165         }
55166       }
55167     }
55168 
55169     if( i==nCell ){
55170       if( eType!=PTRMAP_BTREE ||
55171           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
55172         return SQLITE_CORRUPT_BKPT;
55173       }
55174       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
55175     }
55176 
55177     pPage->isInit = isInitOrig;
55178   }
55179   return SQLITE_OK;
55180 }
55181 
55182 
55183 /*
55184 ** Move the open database page pDbPage to location iFreePage in the
55185 ** database. The pDbPage reference remains valid.
55186 **
55187 ** The isCommit flag indicates that there is no need to remember that
55188 ** the journal needs to be sync()ed before database page pDbPage->pgno
55189 ** can be written to. The caller has already promised not to write to that
55190 ** page.
55191 */
55192 static int relocatePage(
55193   BtShared *pBt,           /* Btree */
55194   MemPage *pDbPage,        /* Open page to move */
55195   u8 eType,                /* Pointer map 'type' entry for pDbPage */
55196   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
55197   Pgno iFreePage,          /* The location to move pDbPage to */
55198   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
55199 ){
55200   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
55201   Pgno iDbPage = pDbPage->pgno;
55202   Pager *pPager = pBt->pPager;
55203   int rc;
55204 
55205   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
55206       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
55207   assert( sqlite3_mutex_held(pBt->mutex) );
55208   assert( pDbPage->pBt==pBt );
55209 
55210   /* Move page iDbPage from its current location to page number iFreePage */
55211   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
55212       iDbPage, iFreePage, iPtrPage, eType));
55213   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
55214   if( rc!=SQLITE_OK ){
55215     return rc;
55216   }
55217   pDbPage->pgno = iFreePage;
55218 
55219   /* If pDbPage was a btree-page, then it may have child pages and/or cells
55220   ** that point to overflow pages. The pointer map entries for all these
55221   ** pages need to be changed.
55222   **
55223   ** If pDbPage is an overflow page, then the first 4 bytes may store a
55224   ** pointer to a subsequent overflow page. If this is the case, then
55225   ** the pointer map needs to be updated for the subsequent overflow page.
55226   */
55227   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
55228     rc = setChildPtrmaps(pDbPage);
55229     if( rc!=SQLITE_OK ){
55230       return rc;
55231     }
55232   }else{
55233     Pgno nextOvfl = get4byte(pDbPage->aData);
55234     if( nextOvfl!=0 ){
55235       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
55236       if( rc!=SQLITE_OK ){
55237         return rc;
55238       }
55239     }
55240   }
55241 
55242   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
55243   ** that it points at iFreePage. Also fix the pointer map entry for
55244   ** iPtrPage.
55245   */
55246   if( eType!=PTRMAP_ROOTPAGE ){
55247     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
55248     if( rc!=SQLITE_OK ){
55249       return rc;
55250     }
55251     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
55252     if( rc!=SQLITE_OK ){
55253       releasePage(pPtrPage);
55254       return rc;
55255     }
55256     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
55257     releasePage(pPtrPage);
55258     if( rc==SQLITE_OK ){
55259       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
55260     }
55261   }
55262   return rc;
55263 }
55264 
55265 /* Forward declaration required by incrVacuumStep(). */
55266 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
55267 
55268 /*
55269 ** Perform a single step of an incremental-vacuum. If successful, return
55270 ** SQLITE_OK. If there is no work to do (and therefore no point in
55271 ** calling this function again), return SQLITE_DONE. Or, if an error
55272 ** occurs, return some other error code.
55273 **
55274 ** More specifically, this function attempts to re-organize the database so
55275 ** that the last page of the file currently in use is no longer in use.
55276 **
55277 ** Parameter nFin is the number of pages that this database would contain
55278 ** were this function called until it returns SQLITE_DONE.
55279 **
55280 ** If the bCommit parameter is non-zero, this function assumes that the
55281 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
55282 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
55283 ** operation, or false for an incremental vacuum.
55284 */
55285 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
55286   Pgno nFreeList;           /* Number of pages still on the free-list */
55287   int rc;
55288 
55289   assert( sqlite3_mutex_held(pBt->mutex) );
55290   assert( iLastPg>nFin );
55291 
55292   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
55293     u8 eType;
55294     Pgno iPtrPage;
55295 
55296     nFreeList = get4byte(&pBt->pPage1->aData[36]);
55297     if( nFreeList==0 ){
55298       return SQLITE_DONE;
55299     }
55300 
55301     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
55302     if( rc!=SQLITE_OK ){
55303       return rc;
55304     }
55305     if( eType==PTRMAP_ROOTPAGE ){
55306       return SQLITE_CORRUPT_BKPT;
55307     }
55308 
55309     if( eType==PTRMAP_FREEPAGE ){
55310       if( bCommit==0 ){
55311         /* Remove the page from the files free-list. This is not required
55312         ** if bCommit is non-zero. In that case, the free-list will be
55313         ** truncated to zero after this function returns, so it doesn't
55314         ** matter if it still contains some garbage entries.
55315         */
55316         Pgno iFreePg;
55317         MemPage *pFreePg;
55318         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
55319         if( rc!=SQLITE_OK ){
55320           return rc;
55321         }
55322         assert( iFreePg==iLastPg );
55323         releasePage(pFreePg);
55324       }
55325     } else {
55326       Pgno iFreePg;             /* Index of free page to move pLastPg to */
55327       MemPage *pLastPg;
55328       u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
55329       Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
55330 
55331       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
55332       if( rc!=SQLITE_OK ){
55333         return rc;
55334       }
55335 
55336       /* If bCommit is zero, this loop runs exactly once and page pLastPg
55337       ** is swapped with the first free page pulled off the free list.
55338       **
55339       ** On the other hand, if bCommit is greater than zero, then keep
55340       ** looping until a free-page located within the first nFin pages
55341       ** of the file is found.
55342       */
55343       if( bCommit==0 ){
55344         eMode = BTALLOC_LE;
55345         iNear = nFin;
55346       }
55347       do {
55348         MemPage *pFreePg;
55349         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
55350         if( rc!=SQLITE_OK ){
55351           releasePage(pLastPg);
55352           return rc;
55353         }
55354         releasePage(pFreePg);
55355       }while( bCommit && iFreePg>nFin );
55356       assert( iFreePg<iLastPg );
55357 
55358       rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
55359       releasePage(pLastPg);
55360       if( rc!=SQLITE_OK ){
55361         return rc;
55362       }
55363     }
55364   }
55365 
55366   if( bCommit==0 ){
55367     do {
55368       iLastPg--;
55369     }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
55370     pBt->bDoTruncate = 1;
55371     pBt->nPage = iLastPg;
55372   }
55373   return SQLITE_OK;
55374 }
55375 
55376 /*
55377 ** The database opened by the first argument is an auto-vacuum database
55378 ** nOrig pages in size containing nFree free pages. Return the expected
55379 ** size of the database in pages following an auto-vacuum operation.
55380 */
55381 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
55382   int nEntry;                     /* Number of entries on one ptrmap page */
55383   Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
55384   Pgno nFin;                      /* Return value */
55385 
55386   nEntry = pBt->usableSize/5;
55387   nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
55388   nFin = nOrig - nFree - nPtrmap;
55389   if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
55390     nFin--;
55391   }
55392   while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
55393     nFin--;
55394   }
55395 
55396   return nFin;
55397 }
55398 
55399 /*
55400 ** A write-transaction must be opened before calling this function.
55401 ** It performs a single unit of work towards an incremental vacuum.
55402 **
55403 ** If the incremental vacuum is finished after this function has run,
55404 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
55405 ** SQLITE_OK is returned. Otherwise an SQLite error code.
55406 */
55407 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
55408   int rc;
55409   BtShared *pBt = p->pBt;
55410 
55411   sqlite3BtreeEnter(p);
55412   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
55413   if( !pBt->autoVacuum ){
55414     rc = SQLITE_DONE;
55415   }else{
55416     Pgno nOrig = btreePagecount(pBt);
55417     Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
55418     Pgno nFin = finalDbSize(pBt, nOrig, nFree);
55419 
55420     if( nOrig<nFin ){
55421       rc = SQLITE_CORRUPT_BKPT;
55422     }else if( nFree>0 ){
55423       rc = saveAllCursors(pBt, 0, 0);
55424       if( rc==SQLITE_OK ){
55425         invalidateAllOverflowCache(pBt);
55426         rc = incrVacuumStep(pBt, nFin, nOrig, 0);
55427       }
55428       if( rc==SQLITE_OK ){
55429         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
55430         put4byte(&pBt->pPage1->aData[28], pBt->nPage);
55431       }
55432     }else{
55433       rc = SQLITE_DONE;
55434     }
55435   }
55436   sqlite3BtreeLeave(p);
55437   return rc;
55438 }
55439 
55440 /*
55441 ** This routine is called prior to sqlite3PagerCommit when a transaction
55442 ** is committed for an auto-vacuum database.
55443 **
55444 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
55445 ** the database file should be truncated to during the commit process.
55446 ** i.e. the database has been reorganized so that only the first *pnTrunc
55447 ** pages are in use.
55448 */
55449 static int autoVacuumCommit(BtShared *pBt){
55450   int rc = SQLITE_OK;
55451   Pager *pPager = pBt->pPager;
55452   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
55453 
55454   assert( sqlite3_mutex_held(pBt->mutex) );
55455   invalidateAllOverflowCache(pBt);
55456   assert(pBt->autoVacuum);
55457   if( !pBt->incrVacuum ){
55458     Pgno nFin;         /* Number of pages in database after autovacuuming */
55459     Pgno nFree;        /* Number of pages on the freelist initially */
55460     Pgno iFree;        /* The next page to be freed */
55461     Pgno nOrig;        /* Database size before freeing */
55462 
55463     nOrig = btreePagecount(pBt);
55464     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
55465       /* It is not possible to create a database for which the final page
55466       ** is either a pointer-map page or the pending-byte page. If one
55467       ** is encountered, this indicates corruption.
55468       */
55469       return SQLITE_CORRUPT_BKPT;
55470     }
55471 
55472     nFree = get4byte(&pBt->pPage1->aData[36]);
55473     nFin = finalDbSize(pBt, nOrig, nFree);
55474     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
55475     if( nFin<nOrig ){
55476       rc = saveAllCursors(pBt, 0, 0);
55477     }
55478     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
55479       rc = incrVacuumStep(pBt, nFin, iFree, 1);
55480     }
55481     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
55482       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
55483       put4byte(&pBt->pPage1->aData[32], 0);
55484       put4byte(&pBt->pPage1->aData[36], 0);
55485       put4byte(&pBt->pPage1->aData[28], nFin);
55486       pBt->bDoTruncate = 1;
55487       pBt->nPage = nFin;
55488     }
55489     if( rc!=SQLITE_OK ){
55490       sqlite3PagerRollback(pPager);
55491     }
55492   }
55493 
55494   assert( nRef>=sqlite3PagerRefcount(pPager) );
55495   return rc;
55496 }
55497 
55498 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
55499 # define setChildPtrmaps(x) SQLITE_OK
55500 #endif
55501 
55502 /*
55503 ** This routine does the first phase of a two-phase commit.  This routine
55504 ** causes a rollback journal to be created (if it does not already exist)
55505 ** and populated with enough information so that if a power loss occurs
55506 ** the database can be restored to its original state by playing back
55507 ** the journal.  Then the contents of the journal are flushed out to
55508 ** the disk.  After the journal is safely on oxide, the changes to the
55509 ** database are written into the database file and flushed to oxide.
55510 ** At the end of this call, the rollback journal still exists on the
55511 ** disk and we are still holding all locks, so the transaction has not
55512 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
55513 ** commit process.
55514 **
55515 ** This call is a no-op if no write-transaction is currently active on pBt.
55516 **
55517 ** Otherwise, sync the database file for the btree pBt. zMaster points to
55518 ** the name of a master journal file that should be written into the
55519 ** individual journal file, or is NULL, indicating no master journal file
55520 ** (single database transaction).
55521 **
55522 ** When this is called, the master journal should already have been
55523 ** created, populated with this journal pointer and synced to disk.
55524 **
55525 ** Once this is routine has returned, the only thing required to commit
55526 ** the write-transaction for this database file is to delete the journal.
55527 */
55528 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
55529   int rc = SQLITE_OK;
55530   if( p->inTrans==TRANS_WRITE ){
55531     BtShared *pBt = p->pBt;
55532     sqlite3BtreeEnter(p);
55533 #ifndef SQLITE_OMIT_AUTOVACUUM
55534     if( pBt->autoVacuum ){
55535       rc = autoVacuumCommit(pBt);
55536       if( rc!=SQLITE_OK ){
55537         sqlite3BtreeLeave(p);
55538         return rc;
55539       }
55540     }
55541     if( pBt->bDoTruncate ){
55542       sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
55543     }
55544 #endif
55545     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
55546     sqlite3BtreeLeave(p);
55547   }
55548   return rc;
55549 }
55550 
55551 /*
55552 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
55553 ** at the conclusion of a transaction.
55554 */
55555 static void btreeEndTransaction(Btree *p){
55556   BtShared *pBt = p->pBt;
55557   sqlite3 *db = p->db;
55558   assert( sqlite3BtreeHoldsMutex(p) );
55559 
55560 #ifndef SQLITE_OMIT_AUTOVACUUM
55561   pBt->bDoTruncate = 0;
55562 #endif
55563   if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
55564     /* If there are other active statements that belong to this database
55565     ** handle, downgrade to a read-only transaction. The other statements
55566     ** may still be reading from the database.  */
55567     downgradeAllSharedCacheTableLocks(p);
55568     p->inTrans = TRANS_READ;
55569   }else{
55570     /* If the handle had any kind of transaction open, decrement the
55571     ** transaction count of the shared btree. If the transaction count
55572     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
55573     ** call below will unlock the pager.  */
55574     if( p->inTrans!=TRANS_NONE ){
55575       clearAllSharedCacheTableLocks(p);
55576       pBt->nTransaction--;
55577       if( 0==pBt->nTransaction ){
55578         pBt->inTransaction = TRANS_NONE;
55579       }
55580     }
55581 
55582     /* Set the current transaction state to TRANS_NONE and unlock the
55583     ** pager if this call closed the only read or write transaction.  */
55584     p->inTrans = TRANS_NONE;
55585     unlockBtreeIfUnused(pBt);
55586   }
55587 
55588   btreeIntegrity(p);
55589 }
55590 
55591 /*
55592 ** Commit the transaction currently in progress.
55593 **
55594 ** This routine implements the second phase of a 2-phase commit.  The
55595 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
55596 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
55597 ** routine did all the work of writing information out to disk and flushing the
55598 ** contents so that they are written onto the disk platter.  All this
55599 ** routine has to do is delete or truncate or zero the header in the
55600 ** the rollback journal (which causes the transaction to commit) and
55601 ** drop locks.
55602 **
55603 ** Normally, if an error occurs while the pager layer is attempting to
55604 ** finalize the underlying journal file, this function returns an error and
55605 ** the upper layer will attempt a rollback. However, if the second argument
55606 ** is non-zero then this b-tree transaction is part of a multi-file
55607 ** transaction. In this case, the transaction has already been committed
55608 ** (by deleting a master journal file) and the caller will ignore this
55609 ** functions return code. So, even if an error occurs in the pager layer,
55610 ** reset the b-tree objects internal state to indicate that the write
55611 ** transaction has been closed. This is quite safe, as the pager will have
55612 ** transitioned to the error state.
55613 **
55614 ** This will release the write lock on the database file.  If there
55615 ** are no active cursors, it also releases the read lock.
55616 */
55617 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
55618 
55619   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
55620   sqlite3BtreeEnter(p);
55621   btreeIntegrity(p);
55622 
55623   /* If the handle has a write-transaction open, commit the shared-btrees
55624   ** transaction and set the shared state to TRANS_READ.
55625   */
55626   if( p->inTrans==TRANS_WRITE ){
55627     int rc;
55628     BtShared *pBt = p->pBt;
55629     assert( pBt->inTransaction==TRANS_WRITE );
55630     assert( pBt->nTransaction>0 );
55631     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
55632     if( rc!=SQLITE_OK && bCleanup==0 ){
55633       sqlite3BtreeLeave(p);
55634       return rc;
55635     }
55636     pBt->inTransaction = TRANS_READ;
55637     btreeClearHasContent(pBt);
55638   }
55639 
55640   btreeEndTransaction(p);
55641   sqlite3BtreeLeave(p);
55642   return SQLITE_OK;
55643 }
55644 
55645 /*
55646 ** Do both phases of a commit.
55647 */
55648 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
55649   int rc;
55650   sqlite3BtreeEnter(p);
55651   rc = sqlite3BtreeCommitPhaseOne(p, 0);
55652   if( rc==SQLITE_OK ){
55653     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
55654   }
55655   sqlite3BtreeLeave(p);
55656   return rc;
55657 }
55658 
55659 /*
55660 ** This routine sets the state to CURSOR_FAULT and the error
55661 ** code to errCode for every cursor on any BtShared that pBtree
55662 ** references.  Or if the writeOnly flag is set to 1, then only
55663 ** trip write cursors and leave read cursors unchanged.
55664 **
55665 ** Every cursor is a candidate to be tripped, including cursors
55666 ** that belong to other database connections that happen to be
55667 ** sharing the cache with pBtree.
55668 **
55669 ** This routine gets called when a rollback occurs. If the writeOnly
55670 ** flag is true, then only write-cursors need be tripped - read-only
55671 ** cursors save their current positions so that they may continue
55672 ** following the rollback. Or, if writeOnly is false, all cursors are
55673 ** tripped. In general, writeOnly is false if the transaction being
55674 ** rolled back modified the database schema. In this case b-tree root
55675 ** pages may be moved or deleted from the database altogether, making
55676 ** it unsafe for read cursors to continue.
55677 **
55678 ** If the writeOnly flag is true and an error is encountered while
55679 ** saving the current position of a read-only cursor, all cursors,
55680 ** including all read-cursors are tripped.
55681 **
55682 ** SQLITE_OK is returned if successful, or if an error occurs while
55683 ** saving a cursor position, an SQLite error code.
55684 */
55685 SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
55686   BtCursor *p;
55687   int rc = SQLITE_OK;
55688 
55689   assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
55690   if( pBtree ){
55691     sqlite3BtreeEnter(pBtree);
55692     for(p=pBtree->pBt->pCursor; p; p=p->pNext){
55693       int i;
55694       if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
55695         if( p->eState==CURSOR_VALID ){
55696           rc = saveCursorPosition(p);
55697           if( rc!=SQLITE_OK ){
55698             (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
55699             break;
55700           }
55701         }
55702       }else{
55703         sqlite3BtreeClearCursor(p);
55704         p->eState = CURSOR_FAULT;
55705         p->skipNext = errCode;
55706       }
55707       for(i=0; i<=p->iPage; i++){
55708         releasePage(p->apPage[i]);
55709         p->apPage[i] = 0;
55710       }
55711     }
55712     sqlite3BtreeLeave(pBtree);
55713   }
55714   return rc;
55715 }
55716 
55717 /*
55718 ** Rollback the transaction in progress.
55719 **
55720 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
55721 ** Only write cursors are tripped if writeOnly is true but all cursors are
55722 ** tripped if writeOnly is false.  Any attempt to use
55723 ** a tripped cursor will result in an error.
55724 **
55725 ** This will release the write lock on the database file.  If there
55726 ** are no active cursors, it also releases the read lock.
55727 */
55728 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
55729   int rc;
55730   BtShared *pBt = p->pBt;
55731   MemPage *pPage1;
55732 
55733   assert( writeOnly==1 || writeOnly==0 );
55734   assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
55735   sqlite3BtreeEnter(p);
55736   if( tripCode==SQLITE_OK ){
55737     rc = tripCode = saveAllCursors(pBt, 0, 0);
55738     if( rc ) writeOnly = 0;
55739   }else{
55740     rc = SQLITE_OK;
55741   }
55742   if( tripCode ){
55743     int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
55744     assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
55745     if( rc2!=SQLITE_OK ) rc = rc2;
55746   }
55747   btreeIntegrity(p);
55748 
55749   if( p->inTrans==TRANS_WRITE ){
55750     int rc2;
55751 
55752     assert( TRANS_WRITE==pBt->inTransaction );
55753     rc2 = sqlite3PagerRollback(pBt->pPager);
55754     if( rc2!=SQLITE_OK ){
55755       rc = rc2;
55756     }
55757 
55758     /* The rollback may have destroyed the pPage1->aData value.  So
55759     ** call btreeGetPage() on page 1 again to make
55760     ** sure pPage1->aData is set correctly. */
55761     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
55762       int nPage = get4byte(28+(u8*)pPage1->aData);
55763       testcase( nPage==0 );
55764       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
55765       testcase( pBt->nPage!=nPage );
55766       pBt->nPage = nPage;
55767       releasePage(pPage1);
55768     }
55769     assert( countValidCursors(pBt, 1)==0 );
55770     pBt->inTransaction = TRANS_READ;
55771     btreeClearHasContent(pBt);
55772   }
55773 
55774   btreeEndTransaction(p);
55775   sqlite3BtreeLeave(p);
55776   return rc;
55777 }
55778 
55779 /*
55780 ** Start a statement subtransaction. The subtransaction can be rolled
55781 ** back independently of the main transaction. You must start a transaction
55782 ** before starting a subtransaction. The subtransaction is ended automatically
55783 ** if the main transaction commits or rolls back.
55784 **
55785 ** Statement subtransactions are used around individual SQL statements
55786 ** that are contained within a BEGIN...COMMIT block.  If a constraint
55787 ** error occurs within the statement, the effect of that one statement
55788 ** can be rolled back without having to rollback the entire transaction.
55789 **
55790 ** A statement sub-transaction is implemented as an anonymous savepoint. The
55791 ** value passed as the second parameter is the total number of savepoints,
55792 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
55793 ** are no active savepoints and no other statement-transactions open,
55794 ** iStatement is 1. This anonymous savepoint can be released or rolled back
55795 ** using the sqlite3BtreeSavepoint() function.
55796 */
55797 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
55798   int rc;
55799   BtShared *pBt = p->pBt;
55800   sqlite3BtreeEnter(p);
55801   assert( p->inTrans==TRANS_WRITE );
55802   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
55803   assert( iStatement>0 );
55804   assert( iStatement>p->db->nSavepoint );
55805   assert( pBt->inTransaction==TRANS_WRITE );
55806   /* At the pager level, a statement transaction is a savepoint with
55807   ** an index greater than all savepoints created explicitly using
55808   ** SQL statements. It is illegal to open, release or rollback any
55809   ** such savepoints while the statement transaction savepoint is active.
55810   */
55811   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
55812   sqlite3BtreeLeave(p);
55813   return rc;
55814 }
55815 
55816 /*
55817 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
55818 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
55819 ** savepoint identified by parameter iSavepoint, depending on the value
55820 ** of op.
55821 **
55822 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
55823 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
55824 ** contents of the entire transaction are rolled back. This is different
55825 ** from a normal transaction rollback, as no locks are released and the
55826 ** transaction remains open.
55827 */
55828 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
55829   int rc = SQLITE_OK;
55830   if( p && p->inTrans==TRANS_WRITE ){
55831     BtShared *pBt = p->pBt;
55832     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
55833     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
55834     sqlite3BtreeEnter(p);
55835     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
55836     if( rc==SQLITE_OK ){
55837       if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
55838         pBt->nPage = 0;
55839       }
55840       rc = newDatabase(pBt);
55841       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
55842 
55843       /* The database size was written into the offset 28 of the header
55844       ** when the transaction started, so we know that the value at offset
55845       ** 28 is nonzero. */
55846       assert( pBt->nPage>0 );
55847     }
55848     sqlite3BtreeLeave(p);
55849   }
55850   return rc;
55851 }
55852 
55853 /*
55854 ** Create a new cursor for the BTree whose root is on the page
55855 ** iTable. If a read-only cursor is requested, it is assumed that
55856 ** the caller already has at least a read-only transaction open
55857 ** on the database already. If a write-cursor is requested, then
55858 ** the caller is assumed to have an open write transaction.
55859 **
55860 ** If wrFlag==0, then the cursor can only be used for reading.
55861 ** If wrFlag==1, then the cursor can be used for reading or for
55862 ** writing if other conditions for writing are also met.  These
55863 ** are the conditions that must be met in order for writing to
55864 ** be allowed:
55865 **
55866 ** 1:  The cursor must have been opened with wrFlag==1
55867 **
55868 ** 2:  Other database connections that share the same pager cache
55869 **     but which are not in the READ_UNCOMMITTED state may not have
55870 **     cursors open with wrFlag==0 on the same table.  Otherwise
55871 **     the changes made by this write cursor would be visible to
55872 **     the read cursors in the other database connection.
55873 **
55874 ** 3:  The database must be writable (not on read-only media)
55875 **
55876 ** 4:  There must be an active transaction.
55877 **
55878 ** No checking is done to make sure that page iTable really is the
55879 ** root page of a b-tree.  If it is not, then the cursor acquired
55880 ** will not work correctly.
55881 **
55882 ** It is assumed that the sqlite3BtreeCursorZero() has been called
55883 ** on pCur to initialize the memory space prior to invoking this routine.
55884 */
55885 static int btreeCursor(
55886   Btree *p,                              /* The btree */
55887   int iTable,                            /* Root page of table to open */
55888   int wrFlag,                            /* 1 to write. 0 read-only */
55889   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
55890   BtCursor *pCur                         /* Space for new cursor */
55891 ){
55892   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
55893 
55894   assert( sqlite3BtreeHoldsMutex(p) );
55895   assert( wrFlag==0 || wrFlag==1 );
55896 
55897   /* The following assert statements verify that if this is a sharable
55898   ** b-tree database, the connection is holding the required table locks,
55899   ** and that no other connection has any open cursor that conflicts with
55900   ** this lock.  */
55901   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
55902   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
55903 
55904   /* Assert that the caller has opened the required transaction. */
55905   assert( p->inTrans>TRANS_NONE );
55906   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
55907   assert( pBt->pPage1 && pBt->pPage1->aData );
55908 
55909   if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
55910     return SQLITE_READONLY;
55911   }
55912   if( wrFlag ){
55913     allocateTempSpace(pBt);
55914     if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM;
55915   }
55916   if( iTable==1 && btreePagecount(pBt)==0 ){
55917     assert( wrFlag==0 );
55918     iTable = 0;
55919   }
55920 
55921   /* Now that no other errors can occur, finish filling in the BtCursor
55922   ** variables and link the cursor into the BtShared list.  */
55923   pCur->pgnoRoot = (Pgno)iTable;
55924   pCur->iPage = -1;
55925   pCur->pKeyInfo = pKeyInfo;
55926   pCur->pBtree = p;
55927   pCur->pBt = pBt;
55928   assert( wrFlag==0 || wrFlag==BTCF_WriteFlag );
55929   pCur->curFlags = wrFlag;
55930   pCur->pNext = pBt->pCursor;
55931   if( pCur->pNext ){
55932     pCur->pNext->pPrev = pCur;
55933   }
55934   pBt->pCursor = pCur;
55935   pCur->eState = CURSOR_INVALID;
55936   return SQLITE_OK;
55937 }
55938 SQLITE_PRIVATE int sqlite3BtreeCursor(
55939   Btree *p,                                   /* The btree */
55940   int iTable,                                 /* Root page of table to open */
55941   int wrFlag,                                 /* 1 to write. 0 read-only */
55942   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
55943   BtCursor *pCur                              /* Write new cursor here */
55944 ){
55945   int rc;
55946   sqlite3BtreeEnter(p);
55947   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
55948   sqlite3BtreeLeave(p);
55949   return rc;
55950 }
55951 
55952 /*
55953 ** Return the size of a BtCursor object in bytes.
55954 **
55955 ** This interfaces is needed so that users of cursors can preallocate
55956 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
55957 ** to users so they cannot do the sizeof() themselves - they must call
55958 ** this routine.
55959 */
55960 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
55961   return ROUND8(sizeof(BtCursor));
55962 }
55963 
55964 /*
55965 ** Initialize memory that will be converted into a BtCursor object.
55966 **
55967 ** The simple approach here would be to memset() the entire object
55968 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
55969 ** do not need to be zeroed and they are large, so we can save a lot
55970 ** of run-time by skipping the initialization of those elements.
55971 */
55972 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
55973   memset(p, 0, offsetof(BtCursor, iPage));
55974 }
55975 
55976 /*
55977 ** Close a cursor.  The read lock on the database file is released
55978 ** when the last cursor is closed.
55979 */
55980 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
55981   Btree *pBtree = pCur->pBtree;
55982   if( pBtree ){
55983     int i;
55984     BtShared *pBt = pCur->pBt;
55985     sqlite3BtreeEnter(pBtree);
55986     sqlite3BtreeClearCursor(pCur);
55987     if( pCur->pPrev ){
55988       pCur->pPrev->pNext = pCur->pNext;
55989     }else{
55990       pBt->pCursor = pCur->pNext;
55991     }
55992     if( pCur->pNext ){
55993       pCur->pNext->pPrev = pCur->pPrev;
55994     }
55995     for(i=0; i<=pCur->iPage; i++){
55996       releasePage(pCur->apPage[i]);
55997     }
55998     unlockBtreeIfUnused(pBt);
55999     sqlite3DbFree(pBtree->db, pCur->aOverflow);
56000     /* sqlite3_free(pCur); */
56001     sqlite3BtreeLeave(pBtree);
56002   }
56003   return SQLITE_OK;
56004 }
56005 
56006 /*
56007 ** Make sure the BtCursor* given in the argument has a valid
56008 ** BtCursor.info structure.  If it is not already valid, call
56009 ** btreeParseCell() to fill it in.
56010 **
56011 ** BtCursor.info is a cache of the information in the current cell.
56012 ** Using this cache reduces the number of calls to btreeParseCell().
56013 **
56014 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
56015 ** compiler to crash when getCellInfo() is implemented as a macro.
56016 ** But there is a measureable speed advantage to using the macro on gcc
56017 ** (when less compiler optimizations like -Os or -O0 are used and the
56018 ** compiler is not doing aggressive inlining.)  So we use a real function
56019 ** for MSVC and a macro for everything else.  Ticket #2457.
56020 */
56021 #ifndef NDEBUG
56022   static void assertCellInfo(BtCursor *pCur){
56023     CellInfo info;
56024     int iPage = pCur->iPage;
56025     memset(&info, 0, sizeof(info));
56026     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
56027     assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
56028   }
56029 #else
56030   #define assertCellInfo(x)
56031 #endif
56032 #ifdef _MSC_VER
56033   /* Use a real function in MSVC to work around bugs in that compiler. */
56034   static void getCellInfo(BtCursor *pCur){
56035     if( pCur->info.nSize==0 ){
56036       int iPage = pCur->iPage;
56037       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
56038       pCur->curFlags |= BTCF_ValidNKey;
56039     }else{
56040       assertCellInfo(pCur);
56041     }
56042   }
56043 #else /* if not _MSC_VER */
56044   /* Use a macro in all other compilers so that the function is inlined */
56045 #define getCellInfo(pCur)                                                      \
56046   if( pCur->info.nSize==0 ){                                                   \
56047     int iPage = pCur->iPage;                                                   \
56048     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);        \
56049     pCur->curFlags |= BTCF_ValidNKey;                                          \
56050   }else{                                                                       \
56051     assertCellInfo(pCur);                                                      \
56052   }
56053 #endif /* _MSC_VER */
56054 
56055 #ifndef NDEBUG  /* The next routine used only within assert() statements */
56056 /*
56057 ** Return true if the given BtCursor is valid.  A valid cursor is one
56058 ** that is currently pointing to a row in a (non-empty) table.
56059 ** This is a verification routine is used only within assert() statements.
56060 */
56061 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
56062   return pCur && pCur->eState==CURSOR_VALID;
56063 }
56064 #endif /* NDEBUG */
56065 
56066 /*
56067 ** Set *pSize to the size of the buffer needed to hold the value of
56068 ** the key for the current entry.  If the cursor is not pointing
56069 ** to a valid entry, *pSize is set to 0.
56070 **
56071 ** For a table with the INTKEY flag set, this routine returns the key
56072 ** itself, not the number of bytes in the key.
56073 **
56074 ** The caller must position the cursor prior to invoking this routine.
56075 **
56076 ** This routine cannot fail.  It always returns SQLITE_OK.
56077 */
56078 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
56079   assert( cursorHoldsMutex(pCur) );
56080   assert( pCur->eState==CURSOR_VALID );
56081   getCellInfo(pCur);
56082   *pSize = pCur->info.nKey;
56083   return SQLITE_OK;
56084 }
56085 
56086 /*
56087 ** Set *pSize to the number of bytes of data in the entry the
56088 ** cursor currently points to.
56089 **
56090 ** The caller must guarantee that the cursor is pointing to a non-NULL
56091 ** valid entry.  In other words, the calling procedure must guarantee
56092 ** that the cursor has Cursor.eState==CURSOR_VALID.
56093 **
56094 ** Failure is not possible.  This function always returns SQLITE_OK.
56095 ** It might just as well be a procedure (returning void) but we continue
56096 ** to return an integer result code for historical reasons.
56097 */
56098 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
56099   assert( cursorHoldsMutex(pCur) );
56100   assert( pCur->eState==CURSOR_VALID );
56101   assert( pCur->apPage[pCur->iPage]->intKeyLeaf==1 );
56102   getCellInfo(pCur);
56103   *pSize = pCur->info.nPayload;
56104   return SQLITE_OK;
56105 }
56106 
56107 /*
56108 ** Given the page number of an overflow page in the database (parameter
56109 ** ovfl), this function finds the page number of the next page in the
56110 ** linked list of overflow pages. If possible, it uses the auto-vacuum
56111 ** pointer-map data instead of reading the content of page ovfl to do so.
56112 **
56113 ** If an error occurs an SQLite error code is returned. Otherwise:
56114 **
56115 ** The page number of the next overflow page in the linked list is
56116 ** written to *pPgnoNext. If page ovfl is the last page in its linked
56117 ** list, *pPgnoNext is set to zero.
56118 **
56119 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
56120 ** to page number pOvfl was obtained, then *ppPage is set to point to that
56121 ** reference. It is the responsibility of the caller to call releasePage()
56122 ** on *ppPage to free the reference. In no reference was obtained (because
56123 ** the pointer-map was used to obtain the value for *pPgnoNext), then
56124 ** *ppPage is set to zero.
56125 */
56126 static int getOverflowPage(
56127   BtShared *pBt,               /* The database file */
56128   Pgno ovfl,                   /* Current overflow page number */
56129   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
56130   Pgno *pPgnoNext              /* OUT: Next overflow page number */
56131 ){
56132   Pgno next = 0;
56133   MemPage *pPage = 0;
56134   int rc = SQLITE_OK;
56135 
56136   assert( sqlite3_mutex_held(pBt->mutex) );
56137   assert(pPgnoNext);
56138 
56139 #ifndef SQLITE_OMIT_AUTOVACUUM
56140   /* Try to find the next page in the overflow list using the
56141   ** autovacuum pointer-map pages. Guess that the next page in
56142   ** the overflow list is page number (ovfl+1). If that guess turns
56143   ** out to be wrong, fall back to loading the data of page
56144   ** number ovfl to determine the next page number.
56145   */
56146   if( pBt->autoVacuum ){
56147     Pgno pgno;
56148     Pgno iGuess = ovfl+1;
56149     u8 eType;
56150 
56151     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
56152       iGuess++;
56153     }
56154 
56155     if( iGuess<=btreePagecount(pBt) ){
56156       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
56157       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
56158         next = iGuess;
56159         rc = SQLITE_DONE;
56160       }
56161     }
56162   }
56163 #endif
56164 
56165   assert( next==0 || rc==SQLITE_DONE );
56166   if( rc==SQLITE_OK ){
56167     rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
56168     assert( rc==SQLITE_OK || pPage==0 );
56169     if( rc==SQLITE_OK ){
56170       next = get4byte(pPage->aData);
56171     }
56172   }
56173 
56174   *pPgnoNext = next;
56175   if( ppPage ){
56176     *ppPage = pPage;
56177   }else{
56178     releasePage(pPage);
56179   }
56180   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
56181 }
56182 
56183 /*
56184 ** Copy data from a buffer to a page, or from a page to a buffer.
56185 **
56186 ** pPayload is a pointer to data stored on database page pDbPage.
56187 ** If argument eOp is false, then nByte bytes of data are copied
56188 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
56189 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
56190 ** of data are copied from the buffer pBuf to pPayload.
56191 **
56192 ** SQLITE_OK is returned on success, otherwise an error code.
56193 */
56194 static int copyPayload(
56195   void *pPayload,           /* Pointer to page data */
56196   void *pBuf,               /* Pointer to buffer */
56197   int nByte,                /* Number of bytes to copy */
56198   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
56199   DbPage *pDbPage           /* Page containing pPayload */
56200 ){
56201   if( eOp ){
56202     /* Copy data from buffer to page (a write operation) */
56203     int rc = sqlite3PagerWrite(pDbPage);
56204     if( rc!=SQLITE_OK ){
56205       return rc;
56206     }
56207     memcpy(pPayload, pBuf, nByte);
56208   }else{
56209     /* Copy data from page to buffer (a read operation) */
56210     memcpy(pBuf, pPayload, nByte);
56211   }
56212   return SQLITE_OK;
56213 }
56214 
56215 /*
56216 ** This function is used to read or overwrite payload information
56217 ** for the entry that the pCur cursor is pointing to. The eOp
56218 ** argument is interpreted as follows:
56219 **
56220 **   0: The operation is a read. Populate the overflow cache.
56221 **   1: The operation is a write. Populate the overflow cache.
56222 **   2: The operation is a read. Do not populate the overflow cache.
56223 **
56224 ** A total of "amt" bytes are read or written beginning at "offset".
56225 ** Data is read to or from the buffer pBuf.
56226 **
56227 ** The content being read or written might appear on the main page
56228 ** or be scattered out on multiple overflow pages.
56229 **
56230 ** If the current cursor entry uses one or more overflow pages and the
56231 ** eOp argument is not 2, this function may allocate space for and lazily
56232 ** populates the overflow page-list cache array (BtCursor.aOverflow).
56233 ** Subsequent calls use this cache to make seeking to the supplied offset
56234 ** more efficient.
56235 **
56236 ** Once an overflow page-list cache has been allocated, it may be
56237 ** invalidated if some other cursor writes to the same table, or if
56238 ** the cursor is moved to a different row. Additionally, in auto-vacuum
56239 ** mode, the following events may invalidate an overflow page-list cache.
56240 **
56241 **   * An incremental vacuum,
56242 **   * A commit in auto_vacuum="full" mode,
56243 **   * Creating a table (may require moving an overflow page).
56244 */
56245 static int accessPayload(
56246   BtCursor *pCur,      /* Cursor pointing to entry to read from */
56247   u32 offset,          /* Begin reading this far into payload */
56248   u32 amt,             /* Read this many bytes */
56249   unsigned char *pBuf, /* Write the bytes into this buffer */
56250   int eOp              /* zero to read. non-zero to write. */
56251 ){
56252   unsigned char *aPayload;
56253   int rc = SQLITE_OK;
56254   int iIdx = 0;
56255   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
56256   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
56257 #ifdef SQLITE_DIRECT_OVERFLOW_READ
56258   unsigned char * const pBufStart = pBuf;
56259   int bEnd;                                 /* True if reading to end of data */
56260 #endif
56261 
56262   assert( pPage );
56263   assert( pCur->eState==CURSOR_VALID );
56264   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
56265   assert( cursorHoldsMutex(pCur) );
56266   assert( eOp!=2 || offset==0 );    /* Always start from beginning for eOp==2 */
56267 
56268   getCellInfo(pCur);
56269   aPayload = pCur->info.pPayload;
56270 #ifdef SQLITE_DIRECT_OVERFLOW_READ
56271   bEnd = offset+amt==pCur->info.nPayload;
56272 #endif
56273   assert( offset+amt <= pCur->info.nPayload );
56274 
56275   if( &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] ){
56276     /* Trying to read or write past the end of the data is an error */
56277     return SQLITE_CORRUPT_BKPT;
56278   }
56279 
56280   /* Check if data must be read/written to/from the btree page itself. */
56281   if( offset<pCur->info.nLocal ){
56282     int a = amt;
56283     if( a+offset>pCur->info.nLocal ){
56284       a = pCur->info.nLocal - offset;
56285     }
56286     rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
56287     offset = 0;
56288     pBuf += a;
56289     amt -= a;
56290   }else{
56291     offset -= pCur->info.nLocal;
56292   }
56293 
56294   if( rc==SQLITE_OK && amt>0 ){
56295     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
56296     Pgno nextPage;
56297 
56298     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
56299 
56300     /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
56301     ** Except, do not allocate aOverflow[] for eOp==2.
56302     **
56303     ** The aOverflow[] array is sized at one entry for each overflow page
56304     ** in the overflow chain. The page number of the first overflow page is
56305     ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
56306     ** means "not yet known" (the cache is lazily populated).
56307     */
56308     if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
56309       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
56310       if( nOvfl>pCur->nOvflAlloc ){
56311         Pgno *aNew = (Pgno*)sqlite3DbRealloc(
56312             pCur->pBtree->db, pCur->aOverflow, nOvfl*2*sizeof(Pgno)
56313         );
56314         if( aNew==0 ){
56315           rc = SQLITE_NOMEM;
56316         }else{
56317           pCur->nOvflAlloc = nOvfl*2;
56318           pCur->aOverflow = aNew;
56319         }
56320       }
56321       if( rc==SQLITE_OK ){
56322         memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
56323         pCur->curFlags |= BTCF_ValidOvfl;
56324       }
56325     }
56326 
56327     /* If the overflow page-list cache has been allocated and the
56328     ** entry for the first required overflow page is valid, skip
56329     ** directly to it.
56330     */
56331     if( (pCur->curFlags & BTCF_ValidOvfl)!=0
56332      && pCur->aOverflow[offset/ovflSize]
56333     ){
56334       iIdx = (offset/ovflSize);
56335       nextPage = pCur->aOverflow[iIdx];
56336       offset = (offset%ovflSize);
56337     }
56338 
56339     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
56340 
56341       /* If required, populate the overflow page-list cache. */
56342       if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
56343         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
56344         pCur->aOverflow[iIdx] = nextPage;
56345       }
56346 
56347       if( offset>=ovflSize ){
56348         /* The only reason to read this page is to obtain the page
56349         ** number for the next page in the overflow chain. The page
56350         ** data is not required. So first try to lookup the overflow
56351         ** page-list cache, if any, then fall back to the getOverflowPage()
56352         ** function.
56353         **
56354         ** Note that the aOverflow[] array must be allocated because eOp!=2
56355         ** here.  If eOp==2, then offset==0 and this branch is never taken.
56356         */
56357         assert( eOp!=2 );
56358         assert( pCur->curFlags & BTCF_ValidOvfl );
56359         if( pCur->aOverflow[iIdx+1] ){
56360           nextPage = pCur->aOverflow[iIdx+1];
56361         }else{
56362           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
56363         }
56364         offset -= ovflSize;
56365       }else{
56366         /* Need to read this page properly. It contains some of the
56367         ** range of data that is being read (eOp==0) or written (eOp!=0).
56368         */
56369 #ifdef SQLITE_DIRECT_OVERFLOW_READ
56370         sqlite3_file *fd;
56371 #endif
56372         int a = amt;
56373         if( a + offset > ovflSize ){
56374           a = ovflSize - offset;
56375         }
56376 
56377 #ifdef SQLITE_DIRECT_OVERFLOW_READ
56378         /* If all the following are true:
56379         **
56380         **   1) this is a read operation, and
56381         **   2) data is required from the start of this overflow page, and
56382         **   3) the database is file-backed, and
56383         **   4) there is no open write-transaction, and
56384         **   5) the database is not a WAL database,
56385         **   6) all data from the page is being read.
56386         **   7) at least 4 bytes have already been read into the output buffer
56387         **
56388         ** then data can be read directly from the database file into the
56389         ** output buffer, bypassing the page-cache altogether. This speeds
56390         ** up loading large records that span many overflow pages.
56391         */
56392         if( (eOp&0x01)==0                                      /* (1) */
56393          && offset==0                                          /* (2) */
56394          && (bEnd || a==ovflSize)                              /* (6) */
56395          && pBt->inTransaction==TRANS_READ                     /* (4) */
56396          && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
56397          && pBt->pPage1->aData[19]==0x01                       /* (5) */
56398          && &pBuf[-4]>=pBufStart                               /* (7) */
56399         ){
56400           u8 aSave[4];
56401           u8 *aWrite = &pBuf[-4];
56402           assert( aWrite>=pBufStart );                         /* hence (7) */
56403           memcpy(aSave, aWrite, 4);
56404           rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
56405           nextPage = get4byte(aWrite);
56406           memcpy(aWrite, aSave, 4);
56407         }else
56408 #endif
56409 
56410         {
56411           DbPage *pDbPage;
56412           rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
56413               ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
56414           );
56415           if( rc==SQLITE_OK ){
56416             aPayload = sqlite3PagerGetData(pDbPage);
56417             nextPage = get4byte(aPayload);
56418             rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
56419             sqlite3PagerUnref(pDbPage);
56420             offset = 0;
56421           }
56422         }
56423         amt -= a;
56424         pBuf += a;
56425       }
56426     }
56427   }
56428 
56429   if( rc==SQLITE_OK && amt>0 ){
56430     return SQLITE_CORRUPT_BKPT;
56431   }
56432   return rc;
56433 }
56434 
56435 /*
56436 ** Read part of the key associated with cursor pCur.  Exactly
56437 ** "amt" bytes will be transferred into pBuf[].  The transfer
56438 ** begins at "offset".
56439 **
56440 ** The caller must ensure that pCur is pointing to a valid row
56441 ** in the table.
56442 **
56443 ** Return SQLITE_OK on success or an error code if anything goes
56444 ** wrong.  An error is returned if "offset+amt" is larger than
56445 ** the available payload.
56446 */
56447 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
56448   assert( cursorHoldsMutex(pCur) );
56449   assert( pCur->eState==CURSOR_VALID );
56450   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
56451   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
56452   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
56453 }
56454 
56455 /*
56456 ** Read part of the data associated with cursor pCur.  Exactly
56457 ** "amt" bytes will be transfered into pBuf[].  The transfer
56458 ** begins at "offset".
56459 **
56460 ** Return SQLITE_OK on success or an error code if anything goes
56461 ** wrong.  An error is returned if "offset+amt" is larger than
56462 ** the available payload.
56463 */
56464 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
56465   int rc;
56466 
56467 #ifndef SQLITE_OMIT_INCRBLOB
56468   if ( pCur->eState==CURSOR_INVALID ){
56469     return SQLITE_ABORT;
56470   }
56471 #endif
56472 
56473   assert( cursorHoldsMutex(pCur) );
56474   rc = restoreCursorPosition(pCur);
56475   if( rc==SQLITE_OK ){
56476     assert( pCur->eState==CURSOR_VALID );
56477     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
56478     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
56479     rc = accessPayload(pCur, offset, amt, pBuf, 0);
56480   }
56481   return rc;
56482 }
56483 
56484 /*
56485 ** Return a pointer to payload information from the entry that the
56486 ** pCur cursor is pointing to.  The pointer is to the beginning of
56487 ** the key if index btrees (pPage->intKey==0) and is the data for
56488 ** table btrees (pPage->intKey==1). The number of bytes of available
56489 ** key/data is written into *pAmt.  If *pAmt==0, then the value
56490 ** returned will not be a valid pointer.
56491 **
56492 ** This routine is an optimization.  It is common for the entire key
56493 ** and data to fit on the local page and for there to be no overflow
56494 ** pages.  When that is so, this routine can be used to access the
56495 ** key and data without making a copy.  If the key and/or data spills
56496 ** onto overflow pages, then accessPayload() must be used to reassemble
56497 ** the key/data and copy it into a preallocated buffer.
56498 **
56499 ** The pointer returned by this routine looks directly into the cached
56500 ** page of the database.  The data might change or move the next time
56501 ** any btree routine is called.
56502 */
56503 static const void *fetchPayload(
56504   BtCursor *pCur,      /* Cursor pointing to entry to read from */
56505   u32 *pAmt            /* Write the number of available bytes here */
56506 ){
56507   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
56508   assert( pCur->eState==CURSOR_VALID );
56509   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
56510   assert( cursorHoldsMutex(pCur) );
56511   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
56512   assert( pCur->info.nSize>0 );
56513   *pAmt = pCur->info.nLocal;
56514   return (void*)pCur->info.pPayload;
56515 }
56516 
56517 
56518 /*
56519 ** For the entry that cursor pCur is point to, return as
56520 ** many bytes of the key or data as are available on the local
56521 ** b-tree page.  Write the number of available bytes into *pAmt.
56522 **
56523 ** The pointer returned is ephemeral.  The key/data may move
56524 ** or be destroyed on the next call to any Btree routine,
56525 ** including calls from other threads against the same cache.
56526 ** Hence, a mutex on the BtShared should be held prior to calling
56527 ** this routine.
56528 **
56529 ** These routines is used to get quick access to key and data
56530 ** in the common case where no overflow pages are used.
56531 */
56532 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
56533   return fetchPayload(pCur, pAmt);
56534 }
56535 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
56536   return fetchPayload(pCur, pAmt);
56537 }
56538 
56539 
56540 /*
56541 ** Move the cursor down to a new child page.  The newPgno argument is the
56542 ** page number of the child page to move to.
56543 **
56544 ** This function returns SQLITE_CORRUPT if the page-header flags field of
56545 ** the new child page does not match the flags field of the parent (i.e.
56546 ** if an intkey page appears to be the parent of a non-intkey page, or
56547 ** vice-versa).
56548 */
56549 static int moveToChild(BtCursor *pCur, u32 newPgno){
56550   int rc;
56551   int i = pCur->iPage;
56552   MemPage *pNewPage;
56553   BtShared *pBt = pCur->pBt;
56554 
56555   assert( cursorHoldsMutex(pCur) );
56556   assert( pCur->eState==CURSOR_VALID );
56557   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
56558   assert( pCur->iPage>=0 );
56559   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
56560     return SQLITE_CORRUPT_BKPT;
56561   }
56562   rc = getAndInitPage(pBt, newPgno, &pNewPage,
56563                (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
56564   if( rc ) return rc;
56565   pCur->apPage[i+1] = pNewPage;
56566   pCur->aiIdx[i+1] = 0;
56567   pCur->iPage++;
56568 
56569   pCur->info.nSize = 0;
56570   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
56571   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
56572     return SQLITE_CORRUPT_BKPT;
56573   }
56574   return SQLITE_OK;
56575 }
56576 
56577 #if 0
56578 /*
56579 ** Page pParent is an internal (non-leaf) tree page. This function
56580 ** asserts that page number iChild is the left-child if the iIdx'th
56581 ** cell in page pParent. Or, if iIdx is equal to the total number of
56582 ** cells in pParent, that page number iChild is the right-child of
56583 ** the page.
56584 */
56585 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
56586   assert( iIdx<=pParent->nCell );
56587   if( iIdx==pParent->nCell ){
56588     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
56589   }else{
56590     assert( get4byte(findCell(pParent, iIdx))==iChild );
56591   }
56592 }
56593 #else
56594 #  define assertParentIndex(x,y,z)
56595 #endif
56596 
56597 /*
56598 ** Move the cursor up to the parent page.
56599 **
56600 ** pCur->idx is set to the cell index that contains the pointer
56601 ** to the page we are coming from.  If we are coming from the
56602 ** right-most child page then pCur->idx is set to one more than
56603 ** the largest cell index.
56604 */
56605 static void moveToParent(BtCursor *pCur){
56606   assert( cursorHoldsMutex(pCur) );
56607   assert( pCur->eState==CURSOR_VALID );
56608   assert( pCur->iPage>0 );
56609   assert( pCur->apPage[pCur->iPage] );
56610 
56611   /* UPDATE: It is actually possible for the condition tested by the assert
56612   ** below to be untrue if the database file is corrupt. This can occur if
56613   ** one cursor has modified page pParent while a reference to it is held
56614   ** by a second cursor. Which can only happen if a single page is linked
56615   ** into more than one b-tree structure in a corrupt database.  */
56616 #if 0
56617   assertParentIndex(
56618     pCur->apPage[pCur->iPage-1],
56619     pCur->aiIdx[pCur->iPage-1],
56620     pCur->apPage[pCur->iPage]->pgno
56621   );
56622 #endif
56623   testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
56624 
56625   releasePage(pCur->apPage[pCur->iPage]);
56626   pCur->iPage--;
56627   pCur->info.nSize = 0;
56628   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
56629 }
56630 
56631 /*
56632 ** Move the cursor to point to the root page of its b-tree structure.
56633 **
56634 ** If the table has a virtual root page, then the cursor is moved to point
56635 ** to the virtual root page instead of the actual root page. A table has a
56636 ** virtual root page when the actual root page contains no cells and a
56637 ** single child page. This can only happen with the table rooted at page 1.
56638 **
56639 ** If the b-tree structure is empty, the cursor state is set to
56640 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
56641 ** cell located on the root (or virtual root) page and the cursor state
56642 ** is set to CURSOR_VALID.
56643 **
56644 ** If this function returns successfully, it may be assumed that the
56645 ** page-header flags indicate that the [virtual] root-page is the expected
56646 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
56647 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
56648 ** indicating a table b-tree, or if the caller did specify a KeyInfo
56649 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
56650 ** b-tree).
56651 */
56652 static int moveToRoot(BtCursor *pCur){
56653   MemPage *pRoot;
56654   int rc = SQLITE_OK;
56655 
56656   assert( cursorHoldsMutex(pCur) );
56657   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
56658   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
56659   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
56660   if( pCur->eState>=CURSOR_REQUIRESEEK ){
56661     if( pCur->eState==CURSOR_FAULT ){
56662       assert( pCur->skipNext!=SQLITE_OK );
56663       return pCur->skipNext;
56664     }
56665     sqlite3BtreeClearCursor(pCur);
56666   }
56667 
56668   if( pCur->iPage>=0 ){
56669     while( pCur->iPage ) releasePage(pCur->apPage[pCur->iPage--]);
56670   }else if( pCur->pgnoRoot==0 ){
56671     pCur->eState = CURSOR_INVALID;
56672     return SQLITE_OK;
56673   }else{
56674     rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
56675                  (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
56676     if( rc!=SQLITE_OK ){
56677       pCur->eState = CURSOR_INVALID;
56678       return rc;
56679     }
56680     pCur->iPage = 0;
56681   }
56682   pRoot = pCur->apPage[0];
56683   assert( pRoot->pgno==pCur->pgnoRoot );
56684 
56685   /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
56686   ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
56687   ** NULL, the caller expects a table b-tree. If this is not the case,
56688   ** return an SQLITE_CORRUPT error.
56689   **
56690   ** Earlier versions of SQLite assumed that this test could not fail
56691   ** if the root page was already loaded when this function was called (i.e.
56692   ** if pCur->iPage>=0). But this is not so if the database is corrupted
56693   ** in such a way that page pRoot is linked into a second b-tree table
56694   ** (or the freelist).  */
56695   assert( pRoot->intKey==1 || pRoot->intKey==0 );
56696   if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
56697     return SQLITE_CORRUPT_BKPT;
56698   }
56699 
56700   pCur->aiIdx[0] = 0;
56701   pCur->info.nSize = 0;
56702   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
56703 
56704   if( pRoot->nCell>0 ){
56705     pCur->eState = CURSOR_VALID;
56706   }else if( !pRoot->leaf ){
56707     Pgno subpage;
56708     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
56709     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
56710     pCur->eState = CURSOR_VALID;
56711     rc = moveToChild(pCur, subpage);
56712   }else{
56713     pCur->eState = CURSOR_INVALID;
56714   }
56715   return rc;
56716 }
56717 
56718 /*
56719 ** Move the cursor down to the left-most leaf entry beneath the
56720 ** entry to which it is currently pointing.
56721 **
56722 ** The left-most leaf is the one with the smallest key - the first
56723 ** in ascending order.
56724 */
56725 static int moveToLeftmost(BtCursor *pCur){
56726   Pgno pgno;
56727   int rc = SQLITE_OK;
56728   MemPage *pPage;
56729 
56730   assert( cursorHoldsMutex(pCur) );
56731   assert( pCur->eState==CURSOR_VALID );
56732   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
56733     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
56734     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
56735     rc = moveToChild(pCur, pgno);
56736   }
56737   return rc;
56738 }
56739 
56740 /*
56741 ** Move the cursor down to the right-most leaf entry beneath the
56742 ** page to which it is currently pointing.  Notice the difference
56743 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
56744 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
56745 ** finds the right-most entry beneath the *page*.
56746 **
56747 ** The right-most entry is the one with the largest key - the last
56748 ** key in ascending order.
56749 */
56750 static int moveToRightmost(BtCursor *pCur){
56751   Pgno pgno;
56752   int rc = SQLITE_OK;
56753   MemPage *pPage = 0;
56754 
56755   assert( cursorHoldsMutex(pCur) );
56756   assert( pCur->eState==CURSOR_VALID );
56757   while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
56758     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
56759     pCur->aiIdx[pCur->iPage] = pPage->nCell;
56760     rc = moveToChild(pCur, pgno);
56761     if( rc ) return rc;
56762   }
56763   pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
56764   assert( pCur->info.nSize==0 );
56765   assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
56766   return SQLITE_OK;
56767 }
56768 
56769 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
56770 ** on success.  Set *pRes to 0 if the cursor actually points to something
56771 ** or set *pRes to 1 if the table is empty.
56772 */
56773 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
56774   int rc;
56775 
56776   assert( cursorHoldsMutex(pCur) );
56777   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
56778   rc = moveToRoot(pCur);
56779   if( rc==SQLITE_OK ){
56780     if( pCur->eState==CURSOR_INVALID ){
56781       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
56782       *pRes = 1;
56783     }else{
56784       assert( pCur->apPage[pCur->iPage]->nCell>0 );
56785       *pRes = 0;
56786       rc = moveToLeftmost(pCur);
56787     }
56788   }
56789   return rc;
56790 }
56791 
56792 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
56793 ** on success.  Set *pRes to 0 if the cursor actually points to something
56794 ** or set *pRes to 1 if the table is empty.
56795 */
56796 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
56797   int rc;
56798 
56799   assert( cursorHoldsMutex(pCur) );
56800   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
56801 
56802   /* If the cursor already points to the last entry, this is a no-op. */
56803   if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
56804 #ifdef SQLITE_DEBUG
56805     /* This block serves to assert() that the cursor really does point
56806     ** to the last entry in the b-tree. */
56807     int ii;
56808     for(ii=0; ii<pCur->iPage; ii++){
56809       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
56810     }
56811     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
56812     assert( pCur->apPage[pCur->iPage]->leaf );
56813 #endif
56814     return SQLITE_OK;
56815   }
56816 
56817   rc = moveToRoot(pCur);
56818   if( rc==SQLITE_OK ){
56819     if( CURSOR_INVALID==pCur->eState ){
56820       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
56821       *pRes = 1;
56822     }else{
56823       assert( pCur->eState==CURSOR_VALID );
56824       *pRes = 0;
56825       rc = moveToRightmost(pCur);
56826       if( rc==SQLITE_OK ){
56827         pCur->curFlags |= BTCF_AtLast;
56828       }else{
56829         pCur->curFlags &= ~BTCF_AtLast;
56830       }
56831 
56832     }
56833   }
56834   return rc;
56835 }
56836 
56837 /* Move the cursor so that it points to an entry near the key
56838 ** specified by pIdxKey or intKey.   Return a success code.
56839 **
56840 ** For INTKEY tables, the intKey parameter is used.  pIdxKey
56841 ** must be NULL.  For index tables, pIdxKey is used and intKey
56842 ** is ignored.
56843 **
56844 ** If an exact match is not found, then the cursor is always
56845 ** left pointing at a leaf page which would hold the entry if it
56846 ** were present.  The cursor might point to an entry that comes
56847 ** before or after the key.
56848 **
56849 ** An integer is written into *pRes which is the result of
56850 ** comparing the key with the entry to which the cursor is
56851 ** pointing.  The meaning of the integer written into
56852 ** *pRes is as follows:
56853 **
56854 **     *pRes<0      The cursor is left pointing at an entry that
56855 **                  is smaller than intKey/pIdxKey or if the table is empty
56856 **                  and the cursor is therefore left point to nothing.
56857 **
56858 **     *pRes==0     The cursor is left pointing at an entry that
56859 **                  exactly matches intKey/pIdxKey.
56860 **
56861 **     *pRes>0      The cursor is left pointing at an entry that
56862 **                  is larger than intKey/pIdxKey.
56863 **
56864 */
56865 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
56866   BtCursor *pCur,          /* The cursor to be moved */
56867   UnpackedRecord *pIdxKey, /* Unpacked index key */
56868   i64 intKey,              /* The table key */
56869   int biasRight,           /* If true, bias the search to the high end */
56870   int *pRes                /* Write search results here */
56871 ){
56872   int rc;
56873   RecordCompare xRecordCompare;
56874 
56875   assert( cursorHoldsMutex(pCur) );
56876   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
56877   assert( pRes );
56878   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
56879 
56880   /* If the cursor is already positioned at the point we are trying
56881   ** to move to, then just return without doing any work */
56882   if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
56883    && pCur->apPage[0]->intKey
56884   ){
56885     if( pCur->info.nKey==intKey ){
56886       *pRes = 0;
56887       return SQLITE_OK;
56888     }
56889     if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
56890       *pRes = -1;
56891       return SQLITE_OK;
56892     }
56893   }
56894 
56895   if( pIdxKey ){
56896     xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
56897     pIdxKey->errCode = 0;
56898     assert( pIdxKey->default_rc==1
56899          || pIdxKey->default_rc==0
56900          || pIdxKey->default_rc==-1
56901     );
56902   }else{
56903     xRecordCompare = 0; /* All keys are integers */
56904   }
56905 
56906   rc = moveToRoot(pCur);
56907   if( rc ){
56908     return rc;
56909   }
56910   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
56911   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
56912   assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
56913   if( pCur->eState==CURSOR_INVALID ){
56914     *pRes = -1;
56915     assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
56916     return SQLITE_OK;
56917   }
56918   assert( pCur->apPage[0]->intKey || pIdxKey );
56919   for(;;){
56920     int lwr, upr, idx, c;
56921     Pgno chldPg;
56922     MemPage *pPage = pCur->apPage[pCur->iPage];
56923     u8 *pCell;                          /* Pointer to current cell in pPage */
56924 
56925     /* pPage->nCell must be greater than zero. If this is the root-page
56926     ** the cursor would have been INVALID above and this for(;;) loop
56927     ** not run. If this is not the root-page, then the moveToChild() routine
56928     ** would have already detected db corruption. Similarly, pPage must
56929     ** be the right kind (index or table) of b-tree page. Otherwise
56930     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
56931     assert( pPage->nCell>0 );
56932     assert( pPage->intKey==(pIdxKey==0) );
56933     lwr = 0;
56934     upr = pPage->nCell-1;
56935     assert( biasRight==0 || biasRight==1 );
56936     idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
56937     pCur->aiIdx[pCur->iPage] = (u16)idx;
56938     if( xRecordCompare==0 ){
56939       for(;;){
56940         i64 nCellKey;
56941         pCell = findCell(pPage, idx) + pPage->childPtrSize;
56942         if( pPage->intKeyLeaf ){
56943           while( 0x80 <= *(pCell++) ){
56944             if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
56945           }
56946         }
56947         getVarint(pCell, (u64*)&nCellKey);
56948         if( nCellKey<intKey ){
56949           lwr = idx+1;
56950           if( lwr>upr ){ c = -1; break; }
56951         }else if( nCellKey>intKey ){
56952           upr = idx-1;
56953           if( lwr>upr ){ c = +1; break; }
56954         }else{
56955           assert( nCellKey==intKey );
56956           pCur->curFlags |= BTCF_ValidNKey;
56957           pCur->info.nKey = nCellKey;
56958           pCur->aiIdx[pCur->iPage] = (u16)idx;
56959           if( !pPage->leaf ){
56960             lwr = idx;
56961             goto moveto_next_layer;
56962           }else{
56963             *pRes = 0;
56964             rc = SQLITE_OK;
56965             goto moveto_finish;
56966           }
56967         }
56968         assert( lwr+upr>=0 );
56969         idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
56970       }
56971     }else{
56972       for(;;){
56973         int nCell;
56974         pCell = findCell(pPage, idx) + pPage->childPtrSize;
56975 
56976         /* The maximum supported page-size is 65536 bytes. This means that
56977         ** the maximum number of record bytes stored on an index B-Tree
56978         ** page is less than 16384 bytes and may be stored as a 2-byte
56979         ** varint. This information is used to attempt to avoid parsing
56980         ** the entire cell by checking for the cases where the record is
56981         ** stored entirely within the b-tree page by inspecting the first
56982         ** 2 bytes of the cell.
56983         */
56984         nCell = pCell[0];
56985         if( nCell<=pPage->max1bytePayload ){
56986           /* This branch runs if the record-size field of the cell is a
56987           ** single byte varint and the record fits entirely on the main
56988           ** b-tree page.  */
56989           testcase( pCell+nCell+1==pPage->aDataEnd );
56990           c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
56991         }else if( !(pCell[1] & 0x80)
56992           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
56993         ){
56994           /* The record-size field is a 2 byte varint and the record
56995           ** fits entirely on the main b-tree page.  */
56996           testcase( pCell+nCell+2==pPage->aDataEnd );
56997           c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
56998         }else{
56999           /* The record flows over onto one or more overflow pages. In
57000           ** this case the whole cell needs to be parsed, a buffer allocated
57001           ** and accessPayload() used to retrieve the record into the
57002           ** buffer before VdbeRecordCompare() can be called. */
57003           void *pCellKey;
57004           u8 * const pCellBody = pCell - pPage->childPtrSize;
57005           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
57006           nCell = (int)pCur->info.nKey;
57007           pCellKey = sqlite3Malloc( nCell );
57008           if( pCellKey==0 ){
57009             rc = SQLITE_NOMEM;
57010             goto moveto_finish;
57011           }
57012           pCur->aiIdx[pCur->iPage] = (u16)idx;
57013           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
57014           if( rc ){
57015             sqlite3_free(pCellKey);
57016             goto moveto_finish;
57017           }
57018           c = xRecordCompare(nCell, pCellKey, pIdxKey);
57019           sqlite3_free(pCellKey);
57020         }
57021         assert(
57022             (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
57023          && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
57024         );
57025         if( c<0 ){
57026           lwr = idx+1;
57027         }else if( c>0 ){
57028           upr = idx-1;
57029         }else{
57030           assert( c==0 );
57031           *pRes = 0;
57032           rc = SQLITE_OK;
57033           pCur->aiIdx[pCur->iPage] = (u16)idx;
57034           if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
57035           goto moveto_finish;
57036         }
57037         if( lwr>upr ) break;
57038         assert( lwr+upr>=0 );
57039         idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
57040       }
57041     }
57042     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
57043     assert( pPage->isInit );
57044     if( pPage->leaf ){
57045       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
57046       pCur->aiIdx[pCur->iPage] = (u16)idx;
57047       *pRes = c;
57048       rc = SQLITE_OK;
57049       goto moveto_finish;
57050     }
57051 moveto_next_layer:
57052     if( lwr>=pPage->nCell ){
57053       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
57054     }else{
57055       chldPg = get4byte(findCell(pPage, lwr));
57056     }
57057     pCur->aiIdx[pCur->iPage] = (u16)lwr;
57058     rc = moveToChild(pCur, chldPg);
57059     if( rc ) break;
57060   }
57061 moveto_finish:
57062   pCur->info.nSize = 0;
57063   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
57064   return rc;
57065 }
57066 
57067 
57068 /*
57069 ** Return TRUE if the cursor is not pointing at an entry of the table.
57070 **
57071 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
57072 ** past the last entry in the table or sqlite3BtreePrev() moves past
57073 ** the first entry.  TRUE is also returned if the table is empty.
57074 */
57075 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
57076   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
57077   ** have been deleted? This API will need to change to return an error code
57078   ** as well as the boolean result value.
57079   */
57080   return (CURSOR_VALID!=pCur->eState);
57081 }
57082 
57083 /*
57084 ** Advance the cursor to the next entry in the database.  If
57085 ** successful then set *pRes=0.  If the cursor
57086 ** was already pointing to the last entry in the database before
57087 ** this routine was called, then set *pRes=1.
57088 **
57089 ** The main entry point is sqlite3BtreeNext().  That routine is optimized
57090 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
57091 ** to the next cell on the current page.  The (slower) btreeNext() helper
57092 ** routine is called when it is necessary to move to a different page or
57093 ** to restore the cursor.
57094 **
57095 ** The calling function will set *pRes to 0 or 1.  The initial *pRes value
57096 ** will be 1 if the cursor being stepped corresponds to an SQL index and
57097 ** if this routine could have been skipped if that SQL index had been
57098 ** a unique index.  Otherwise the caller will have set *pRes to zero.
57099 ** Zero is the common case. The btree implementation is free to use the
57100 ** initial *pRes value as a hint to improve performance, but the current
57101 ** SQLite btree implementation does not. (Note that the comdb2 btree
57102 ** implementation does use this hint, however.)
57103 */
57104 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
57105   int rc;
57106   int idx;
57107   MemPage *pPage;
57108 
57109   assert( cursorHoldsMutex(pCur) );
57110   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
57111   assert( *pRes==0 );
57112   if( pCur->eState!=CURSOR_VALID ){
57113     assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
57114     rc = restoreCursorPosition(pCur);
57115     if( rc!=SQLITE_OK ){
57116       return rc;
57117     }
57118     if( CURSOR_INVALID==pCur->eState ){
57119       *pRes = 1;
57120       return SQLITE_OK;
57121     }
57122     if( pCur->skipNext ){
57123       assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
57124       pCur->eState = CURSOR_VALID;
57125       if( pCur->skipNext>0 ){
57126         pCur->skipNext = 0;
57127         return SQLITE_OK;
57128       }
57129       pCur->skipNext = 0;
57130     }
57131   }
57132 
57133   pPage = pCur->apPage[pCur->iPage];
57134   idx = ++pCur->aiIdx[pCur->iPage];
57135   assert( pPage->isInit );
57136 
57137   /* If the database file is corrupt, it is possible for the value of idx
57138   ** to be invalid here. This can only occur if a second cursor modifies
57139   ** the page while cursor pCur is holding a reference to it. Which can
57140   ** only happen if the database is corrupt in such a way as to link the
57141   ** page into more than one b-tree structure. */
57142   testcase( idx>pPage->nCell );
57143 
57144   if( idx>=pPage->nCell ){
57145     if( !pPage->leaf ){
57146       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
57147       if( rc ) return rc;
57148       return moveToLeftmost(pCur);
57149     }
57150     do{
57151       if( pCur->iPage==0 ){
57152         *pRes = 1;
57153         pCur->eState = CURSOR_INVALID;
57154         return SQLITE_OK;
57155       }
57156       moveToParent(pCur);
57157       pPage = pCur->apPage[pCur->iPage];
57158     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
57159     if( pPage->intKey ){
57160       return sqlite3BtreeNext(pCur, pRes);
57161     }else{
57162       return SQLITE_OK;
57163     }
57164   }
57165   if( pPage->leaf ){
57166     return SQLITE_OK;
57167   }else{
57168     return moveToLeftmost(pCur);
57169   }
57170 }
57171 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
57172   MemPage *pPage;
57173   assert( cursorHoldsMutex(pCur) );
57174   assert( pRes!=0 );
57175   assert( *pRes==0 || *pRes==1 );
57176   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
57177   pCur->info.nSize = 0;
57178   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
57179   *pRes = 0;
57180   if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
57181   pPage = pCur->apPage[pCur->iPage];
57182   if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
57183     pCur->aiIdx[pCur->iPage]--;
57184     return btreeNext(pCur, pRes);
57185   }
57186   if( pPage->leaf ){
57187     return SQLITE_OK;
57188   }else{
57189     return moveToLeftmost(pCur);
57190   }
57191 }
57192 
57193 /*
57194 ** Step the cursor to the back to the previous entry in the database.  If
57195 ** successful then set *pRes=0.  If the cursor
57196 ** was already pointing to the first entry in the database before
57197 ** this routine was called, then set *pRes=1.
57198 **
57199 ** The main entry point is sqlite3BtreePrevious().  That routine is optimized
57200 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
57201 ** to the previous cell on the current page.  The (slower) btreePrevious()
57202 ** helper routine is called when it is necessary to move to a different page
57203 ** or to restore the cursor.
57204 **
57205 ** The calling function will set *pRes to 0 or 1.  The initial *pRes value
57206 ** will be 1 if the cursor being stepped corresponds to an SQL index and
57207 ** if this routine could have been skipped if that SQL index had been
57208 ** a unique index.  Otherwise the caller will have set *pRes to zero.
57209 ** Zero is the common case. The btree implementation is free to use the
57210 ** initial *pRes value as a hint to improve performance, but the current
57211 ** SQLite btree implementation does not. (Note that the comdb2 btree
57212 ** implementation does use this hint, however.)
57213 */
57214 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
57215   int rc;
57216   MemPage *pPage;
57217 
57218   assert( cursorHoldsMutex(pCur) );
57219   assert( pRes!=0 );
57220   assert( *pRes==0 );
57221   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
57222   assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
57223   assert( pCur->info.nSize==0 );
57224   if( pCur->eState!=CURSOR_VALID ){
57225     rc = restoreCursorPosition(pCur);
57226     if( rc!=SQLITE_OK ){
57227       return rc;
57228     }
57229     if( CURSOR_INVALID==pCur->eState ){
57230       *pRes = 1;
57231       return SQLITE_OK;
57232     }
57233     if( pCur->skipNext ){
57234       assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
57235       pCur->eState = CURSOR_VALID;
57236       if( pCur->skipNext<0 ){
57237         pCur->skipNext = 0;
57238         return SQLITE_OK;
57239       }
57240       pCur->skipNext = 0;
57241     }
57242   }
57243 
57244   pPage = pCur->apPage[pCur->iPage];
57245   assert( pPage->isInit );
57246   if( !pPage->leaf ){
57247     int idx = pCur->aiIdx[pCur->iPage];
57248     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
57249     if( rc ) return rc;
57250     rc = moveToRightmost(pCur);
57251   }else{
57252     while( pCur->aiIdx[pCur->iPage]==0 ){
57253       if( pCur->iPage==0 ){
57254         pCur->eState = CURSOR_INVALID;
57255         *pRes = 1;
57256         return SQLITE_OK;
57257       }
57258       moveToParent(pCur);
57259     }
57260     assert( pCur->info.nSize==0 );
57261     assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
57262 
57263     pCur->aiIdx[pCur->iPage]--;
57264     pPage = pCur->apPage[pCur->iPage];
57265     if( pPage->intKey && !pPage->leaf ){
57266       rc = sqlite3BtreePrevious(pCur, pRes);
57267     }else{
57268       rc = SQLITE_OK;
57269     }
57270   }
57271   return rc;
57272 }
57273 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
57274   assert( cursorHoldsMutex(pCur) );
57275   assert( pRes!=0 );
57276   assert( *pRes==0 || *pRes==1 );
57277   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
57278   *pRes = 0;
57279   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
57280   pCur->info.nSize = 0;
57281   if( pCur->eState!=CURSOR_VALID
57282    || pCur->aiIdx[pCur->iPage]==0
57283    || pCur->apPage[pCur->iPage]->leaf==0
57284   ){
57285     return btreePrevious(pCur, pRes);
57286   }
57287   pCur->aiIdx[pCur->iPage]--;
57288   return SQLITE_OK;
57289 }
57290 
57291 /*
57292 ** Allocate a new page from the database file.
57293 **
57294 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
57295 ** has already been called on the new page.)  The new page has also
57296 ** been referenced and the calling routine is responsible for calling
57297 ** sqlite3PagerUnref() on the new page when it is done.
57298 **
57299 ** SQLITE_OK is returned on success.  Any other return value indicates
57300 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
57301 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
57302 **
57303 ** If the "nearby" parameter is not 0, then an effort is made to
57304 ** locate a page close to the page number "nearby".  This can be used in an
57305 ** attempt to keep related pages close to each other in the database file,
57306 ** which in turn can make database access faster.
57307 **
57308 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
57309 ** anywhere on the free-list, then it is guaranteed to be returned.  If
57310 ** eMode is BTALLOC_LT then the page returned will be less than or equal
57311 ** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
57312 ** are no restrictions on which page is returned.
57313 */
57314 static int allocateBtreePage(
57315   BtShared *pBt,         /* The btree */
57316   MemPage **ppPage,      /* Store pointer to the allocated page here */
57317   Pgno *pPgno,           /* Store the page number here */
57318   Pgno nearby,           /* Search for a page near this one */
57319   u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
57320 ){
57321   MemPage *pPage1;
57322   int rc;
57323   u32 n;     /* Number of pages on the freelist */
57324   u32 k;     /* Number of leaves on the trunk of the freelist */
57325   MemPage *pTrunk = 0;
57326   MemPage *pPrevTrunk = 0;
57327   Pgno mxPage;     /* Total size of the database file */
57328 
57329   assert( sqlite3_mutex_held(pBt->mutex) );
57330   assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
57331   pPage1 = pBt->pPage1;
57332   mxPage = btreePagecount(pBt);
57333   n = get4byte(&pPage1->aData[36]);
57334   testcase( n==mxPage-1 );
57335   if( n>=mxPage ){
57336     return SQLITE_CORRUPT_BKPT;
57337   }
57338   if( n>0 ){
57339     /* There are pages on the freelist.  Reuse one of those pages. */
57340     Pgno iTrunk;
57341     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
57342 
57343     /* If eMode==BTALLOC_EXACT and a query of the pointer-map
57344     ** shows that the page 'nearby' is somewhere on the free-list, then
57345     ** the entire-list will be searched for that page.
57346     */
57347 #ifndef SQLITE_OMIT_AUTOVACUUM
57348     if( eMode==BTALLOC_EXACT ){
57349       if( nearby<=mxPage ){
57350         u8 eType;
57351         assert( nearby>0 );
57352         assert( pBt->autoVacuum );
57353         rc = ptrmapGet(pBt, nearby, &eType, 0);
57354         if( rc ) return rc;
57355         if( eType==PTRMAP_FREEPAGE ){
57356           searchList = 1;
57357         }
57358       }
57359     }else if( eMode==BTALLOC_LE ){
57360       searchList = 1;
57361     }
57362 #endif
57363 
57364     /* Decrement the free-list count by 1. Set iTrunk to the index of the
57365     ** first free-list trunk page. iPrevTrunk is initially 1.
57366     */
57367     rc = sqlite3PagerWrite(pPage1->pDbPage);
57368     if( rc ) return rc;
57369     put4byte(&pPage1->aData[36], n-1);
57370 
57371     /* The code within this loop is run only once if the 'searchList' variable
57372     ** is not true. Otherwise, it runs once for each trunk-page on the
57373     ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
57374     ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
57375     */
57376     do {
57377       pPrevTrunk = pTrunk;
57378       if( pPrevTrunk ){
57379         iTrunk = get4byte(&pPrevTrunk->aData[0]);
57380       }else{
57381         iTrunk = get4byte(&pPage1->aData[32]);
57382       }
57383       testcase( iTrunk==mxPage );
57384       if( iTrunk>mxPage ){
57385         rc = SQLITE_CORRUPT_BKPT;
57386       }else{
57387         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
57388       }
57389       if( rc ){
57390         pTrunk = 0;
57391         goto end_allocate_page;
57392       }
57393       assert( pTrunk!=0 );
57394       assert( pTrunk->aData!=0 );
57395 
57396       k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
57397       if( k==0 && !searchList ){
57398         /* The trunk has no leaves and the list is not being searched.
57399         ** So extract the trunk page itself and use it as the newly
57400         ** allocated page */
57401         assert( pPrevTrunk==0 );
57402         rc = sqlite3PagerWrite(pTrunk->pDbPage);
57403         if( rc ){
57404           goto end_allocate_page;
57405         }
57406         *pPgno = iTrunk;
57407         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
57408         *ppPage = pTrunk;
57409         pTrunk = 0;
57410         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
57411       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
57412         /* Value of k is out of range.  Database corruption */
57413         rc = SQLITE_CORRUPT_BKPT;
57414         goto end_allocate_page;
57415 #ifndef SQLITE_OMIT_AUTOVACUUM
57416       }else if( searchList
57417             && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
57418       ){
57419         /* The list is being searched and this trunk page is the page
57420         ** to allocate, regardless of whether it has leaves.
57421         */
57422         *pPgno = iTrunk;
57423         *ppPage = pTrunk;
57424         searchList = 0;
57425         rc = sqlite3PagerWrite(pTrunk->pDbPage);
57426         if( rc ){
57427           goto end_allocate_page;
57428         }
57429         if( k==0 ){
57430           if( !pPrevTrunk ){
57431             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
57432           }else{
57433             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
57434             if( rc!=SQLITE_OK ){
57435               goto end_allocate_page;
57436             }
57437             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
57438           }
57439         }else{
57440           /* The trunk page is required by the caller but it contains
57441           ** pointers to free-list leaves. The first leaf becomes a trunk
57442           ** page in this case.
57443           */
57444           MemPage *pNewTrunk;
57445           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
57446           if( iNewTrunk>mxPage ){
57447             rc = SQLITE_CORRUPT_BKPT;
57448             goto end_allocate_page;
57449           }
57450           testcase( iNewTrunk==mxPage );
57451           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
57452           if( rc!=SQLITE_OK ){
57453             goto end_allocate_page;
57454           }
57455           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
57456           if( rc!=SQLITE_OK ){
57457             releasePage(pNewTrunk);
57458             goto end_allocate_page;
57459           }
57460           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
57461           put4byte(&pNewTrunk->aData[4], k-1);
57462           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
57463           releasePage(pNewTrunk);
57464           if( !pPrevTrunk ){
57465             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
57466             put4byte(&pPage1->aData[32], iNewTrunk);
57467           }else{
57468             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
57469             if( rc ){
57470               goto end_allocate_page;
57471             }
57472             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
57473           }
57474         }
57475         pTrunk = 0;
57476         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
57477 #endif
57478       }else if( k>0 ){
57479         /* Extract a leaf from the trunk */
57480         u32 closest;
57481         Pgno iPage;
57482         unsigned char *aData = pTrunk->aData;
57483         if( nearby>0 ){
57484           u32 i;
57485           closest = 0;
57486           if( eMode==BTALLOC_LE ){
57487             for(i=0; i<k; i++){
57488               iPage = get4byte(&aData[8+i*4]);
57489               if( iPage<=nearby ){
57490                 closest = i;
57491                 break;
57492               }
57493             }
57494           }else{
57495             int dist;
57496             dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
57497             for(i=1; i<k; i++){
57498               int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
57499               if( d2<dist ){
57500                 closest = i;
57501                 dist = d2;
57502               }
57503             }
57504           }
57505         }else{
57506           closest = 0;
57507         }
57508 
57509         iPage = get4byte(&aData[8+closest*4]);
57510         testcase( iPage==mxPage );
57511         if( iPage>mxPage ){
57512           rc = SQLITE_CORRUPT_BKPT;
57513           goto end_allocate_page;
57514         }
57515         testcase( iPage==mxPage );
57516         if( !searchList
57517          || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
57518         ){
57519           int noContent;
57520           *pPgno = iPage;
57521           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
57522                  ": %d more free pages\n",
57523                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
57524           rc = sqlite3PagerWrite(pTrunk->pDbPage);
57525           if( rc ) goto end_allocate_page;
57526           if( closest<k-1 ){
57527             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
57528           }
57529           put4byte(&aData[4], k-1);
57530           noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
57531           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
57532           if( rc==SQLITE_OK ){
57533             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
57534             if( rc!=SQLITE_OK ){
57535               releasePage(*ppPage);
57536             }
57537           }
57538           searchList = 0;
57539         }
57540       }
57541       releasePage(pPrevTrunk);
57542       pPrevTrunk = 0;
57543     }while( searchList );
57544   }else{
57545     /* There are no pages on the freelist, so append a new page to the
57546     ** database image.
57547     **
57548     ** Normally, new pages allocated by this block can be requested from the
57549     ** pager layer with the 'no-content' flag set. This prevents the pager
57550     ** from trying to read the pages content from disk. However, if the
57551     ** current transaction has already run one or more incremental-vacuum
57552     ** steps, then the page we are about to allocate may contain content
57553     ** that is required in the event of a rollback. In this case, do
57554     ** not set the no-content flag. This causes the pager to load and journal
57555     ** the current page content before overwriting it.
57556     **
57557     ** Note that the pager will not actually attempt to load or journal
57558     ** content for any page that really does lie past the end of the database
57559     ** file on disk. So the effects of disabling the no-content optimization
57560     ** here are confined to those pages that lie between the end of the
57561     ** database image and the end of the database file.
57562     */
57563     int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
57564 
57565     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
57566     if( rc ) return rc;
57567     pBt->nPage++;
57568     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
57569 
57570 #ifndef SQLITE_OMIT_AUTOVACUUM
57571     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
57572       /* If *pPgno refers to a pointer-map page, allocate two new pages
57573       ** at the end of the file instead of one. The first allocated page
57574       ** becomes a new pointer-map page, the second is used by the caller.
57575       */
57576       MemPage *pPg = 0;
57577       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
57578       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
57579       rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
57580       if( rc==SQLITE_OK ){
57581         rc = sqlite3PagerWrite(pPg->pDbPage);
57582         releasePage(pPg);
57583       }
57584       if( rc ) return rc;
57585       pBt->nPage++;
57586       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
57587     }
57588 #endif
57589     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
57590     *pPgno = pBt->nPage;
57591 
57592     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
57593     rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
57594     if( rc ) return rc;
57595     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
57596     if( rc!=SQLITE_OK ){
57597       releasePage(*ppPage);
57598     }
57599     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
57600   }
57601 
57602   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
57603 
57604 end_allocate_page:
57605   releasePage(pTrunk);
57606   releasePage(pPrevTrunk);
57607   if( rc==SQLITE_OK ){
57608     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
57609       releasePage(*ppPage);
57610       *ppPage = 0;
57611       return SQLITE_CORRUPT_BKPT;
57612     }
57613     (*ppPage)->isInit = 0;
57614   }else{
57615     *ppPage = 0;
57616   }
57617   assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
57618   return rc;
57619 }
57620 
57621 /*
57622 ** This function is used to add page iPage to the database file free-list.
57623 ** It is assumed that the page is not already a part of the free-list.
57624 **
57625 ** The value passed as the second argument to this function is optional.
57626 ** If the caller happens to have a pointer to the MemPage object
57627 ** corresponding to page iPage handy, it may pass it as the second value.
57628 ** Otherwise, it may pass NULL.
57629 **
57630 ** If a pointer to a MemPage object is passed as the second argument,
57631 ** its reference count is not altered by this function.
57632 */
57633 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
57634   MemPage *pTrunk = 0;                /* Free-list trunk page */
57635   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
57636   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
57637   MemPage *pPage;                     /* Page being freed. May be NULL. */
57638   int rc;                             /* Return Code */
57639   int nFree;                          /* Initial number of pages on free-list */
57640 
57641   assert( sqlite3_mutex_held(pBt->mutex) );
57642   assert( iPage>1 );
57643   assert( !pMemPage || pMemPage->pgno==iPage );
57644 
57645   if( pMemPage ){
57646     pPage = pMemPage;
57647     sqlite3PagerRef(pPage->pDbPage);
57648   }else{
57649     pPage = btreePageLookup(pBt, iPage);
57650   }
57651 
57652   /* Increment the free page count on pPage1 */
57653   rc = sqlite3PagerWrite(pPage1->pDbPage);
57654   if( rc ) goto freepage_out;
57655   nFree = get4byte(&pPage1->aData[36]);
57656   put4byte(&pPage1->aData[36], nFree+1);
57657 
57658   if( pBt->btsFlags & BTS_SECURE_DELETE ){
57659     /* If the secure_delete option is enabled, then
57660     ** always fully overwrite deleted information with zeros.
57661     */
57662     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
57663      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
57664     ){
57665       goto freepage_out;
57666     }
57667     memset(pPage->aData, 0, pPage->pBt->pageSize);
57668   }
57669 
57670   /* If the database supports auto-vacuum, write an entry in the pointer-map
57671   ** to indicate that the page is free.
57672   */
57673   if( ISAUTOVACUUM ){
57674     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
57675     if( rc ) goto freepage_out;
57676   }
57677 
57678   /* Now manipulate the actual database free-list structure. There are two
57679   ** possibilities. If the free-list is currently empty, or if the first
57680   ** trunk page in the free-list is full, then this page will become a
57681   ** new free-list trunk page. Otherwise, it will become a leaf of the
57682   ** first trunk page in the current free-list. This block tests if it
57683   ** is possible to add the page as a new free-list leaf.
57684   */
57685   if( nFree!=0 ){
57686     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
57687 
57688     iTrunk = get4byte(&pPage1->aData[32]);
57689     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
57690     if( rc!=SQLITE_OK ){
57691       goto freepage_out;
57692     }
57693 
57694     nLeaf = get4byte(&pTrunk->aData[4]);
57695     assert( pBt->usableSize>32 );
57696     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
57697       rc = SQLITE_CORRUPT_BKPT;
57698       goto freepage_out;
57699     }
57700     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
57701       /* In this case there is room on the trunk page to insert the page
57702       ** being freed as a new leaf.
57703       **
57704       ** Note that the trunk page is not really full until it contains
57705       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
57706       ** coded.  But due to a coding error in versions of SQLite prior to
57707       ** 3.6.0, databases with freelist trunk pages holding more than
57708       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
57709       ** to maintain backwards compatibility with older versions of SQLite,
57710       ** we will continue to restrict the number of entries to usableSize/4 - 8
57711       ** for now.  At some point in the future (once everyone has upgraded
57712       ** to 3.6.0 or later) we should consider fixing the conditional above
57713       ** to read "usableSize/4-2" instead of "usableSize/4-8".
57714       */
57715       rc = sqlite3PagerWrite(pTrunk->pDbPage);
57716       if( rc==SQLITE_OK ){
57717         put4byte(&pTrunk->aData[4], nLeaf+1);
57718         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
57719         if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
57720           sqlite3PagerDontWrite(pPage->pDbPage);
57721         }
57722         rc = btreeSetHasContent(pBt, iPage);
57723       }
57724       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
57725       goto freepage_out;
57726     }
57727   }
57728 
57729   /* If control flows to this point, then it was not possible to add the
57730   ** the page being freed as a leaf page of the first trunk in the free-list.
57731   ** Possibly because the free-list is empty, or possibly because the
57732   ** first trunk in the free-list is full. Either way, the page being freed
57733   ** will become the new first trunk page in the free-list.
57734   */
57735   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
57736     goto freepage_out;
57737   }
57738   rc = sqlite3PagerWrite(pPage->pDbPage);
57739   if( rc!=SQLITE_OK ){
57740     goto freepage_out;
57741   }
57742   put4byte(pPage->aData, iTrunk);
57743   put4byte(&pPage->aData[4], 0);
57744   put4byte(&pPage1->aData[32], iPage);
57745   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
57746 
57747 freepage_out:
57748   if( pPage ){
57749     pPage->isInit = 0;
57750   }
57751   releasePage(pPage);
57752   releasePage(pTrunk);
57753   return rc;
57754 }
57755 static void freePage(MemPage *pPage, int *pRC){
57756   if( (*pRC)==SQLITE_OK ){
57757     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
57758   }
57759 }
57760 
57761 /*
57762 ** Free any overflow pages associated with the given Cell.  Write the
57763 ** local Cell size (the number of bytes on the original page, omitting
57764 ** overflow) into *pnSize.
57765 */
57766 static int clearCell(
57767   MemPage *pPage,          /* The page that contains the Cell */
57768   unsigned char *pCell,    /* First byte of the Cell */
57769   u16 *pnSize              /* Write the size of the Cell here */
57770 ){
57771   BtShared *pBt = pPage->pBt;
57772   CellInfo info;
57773   Pgno ovflPgno;
57774   int rc;
57775   int nOvfl;
57776   u32 ovflPageSize;
57777 
57778   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
57779   btreeParseCellPtr(pPage, pCell, &info);
57780   *pnSize = info.nSize;
57781   if( info.iOverflow==0 ){
57782     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
57783   }
57784   if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
57785     return SQLITE_CORRUPT_BKPT;  /* Cell extends past end of page */
57786   }
57787   ovflPgno = get4byte(&pCell[info.iOverflow]);
57788   assert( pBt->usableSize > 4 );
57789   ovflPageSize = pBt->usableSize - 4;
57790   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
57791   assert( ovflPgno==0 || nOvfl>0 );
57792   while( nOvfl-- ){
57793     Pgno iNext = 0;
57794     MemPage *pOvfl = 0;
57795     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
57796       /* 0 is not a legal page number and page 1 cannot be an
57797       ** overflow page. Therefore if ovflPgno<2 or past the end of the
57798       ** file the database must be corrupt. */
57799       return SQLITE_CORRUPT_BKPT;
57800     }
57801     if( nOvfl ){
57802       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
57803       if( rc ) return rc;
57804     }
57805 
57806     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
57807      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
57808     ){
57809       /* There is no reason any cursor should have an outstanding reference
57810       ** to an overflow page belonging to a cell that is being deleted/updated.
57811       ** So if there exists more than one reference to this page, then it
57812       ** must not really be an overflow page and the database must be corrupt.
57813       ** It is helpful to detect this before calling freePage2(), as
57814       ** freePage2() may zero the page contents if secure-delete mode is
57815       ** enabled. If this 'overflow' page happens to be a page that the
57816       ** caller is iterating through or using in some other way, this
57817       ** can be problematic.
57818       */
57819       rc = SQLITE_CORRUPT_BKPT;
57820     }else{
57821       rc = freePage2(pBt, pOvfl, ovflPgno);
57822     }
57823 
57824     if( pOvfl ){
57825       sqlite3PagerUnref(pOvfl->pDbPage);
57826     }
57827     if( rc ) return rc;
57828     ovflPgno = iNext;
57829   }
57830   return SQLITE_OK;
57831 }
57832 
57833 /*
57834 ** Create the byte sequence used to represent a cell on page pPage
57835 ** and write that byte sequence into pCell[].  Overflow pages are
57836 ** allocated and filled in as necessary.  The calling procedure
57837 ** is responsible for making sure sufficient space has been allocated
57838 ** for pCell[].
57839 **
57840 ** Note that pCell does not necessary need to point to the pPage->aData
57841 ** area.  pCell might point to some temporary storage.  The cell will
57842 ** be constructed in this temporary area then copied into pPage->aData
57843 ** later.
57844 */
57845 static int fillInCell(
57846   MemPage *pPage,                /* The page that contains the cell */
57847   unsigned char *pCell,          /* Complete text of the cell */
57848   const void *pKey, i64 nKey,    /* The key */
57849   const void *pData,int nData,   /* The data */
57850   int nZero,                     /* Extra zero bytes to append to pData */
57851   int *pnSize                    /* Write cell size here */
57852 ){
57853   int nPayload;
57854   const u8 *pSrc;
57855   int nSrc, n, rc;
57856   int spaceLeft;
57857   MemPage *pOvfl = 0;
57858   MemPage *pToRelease = 0;
57859   unsigned char *pPrior;
57860   unsigned char *pPayload;
57861   BtShared *pBt = pPage->pBt;
57862   Pgno pgnoOvfl = 0;
57863   int nHeader;
57864 
57865   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
57866 
57867   /* pPage is not necessarily writeable since pCell might be auxiliary
57868   ** buffer space that is separate from the pPage buffer area */
57869   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
57870             || sqlite3PagerIswriteable(pPage->pDbPage) );
57871 
57872   /* Fill in the header. */
57873   nHeader = pPage->childPtrSize;
57874   nPayload = nData + nZero;
57875   if( pPage->intKeyLeaf ){
57876     nHeader += putVarint32(&pCell[nHeader], nPayload);
57877   }else{
57878     assert( nData==0 );
57879     assert( nZero==0 );
57880   }
57881   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
57882 
57883   /* Fill in the payload size */
57884   if( pPage->intKey ){
57885     pSrc = pData;
57886     nSrc = nData;
57887     nData = 0;
57888   }else{
57889     if( NEVER(nKey>0x7fffffff || pKey==0) ){
57890       return SQLITE_CORRUPT_BKPT;
57891     }
57892     nPayload = (int)nKey;
57893     pSrc = pKey;
57894     nSrc = (int)nKey;
57895   }
57896   if( nPayload<=pPage->maxLocal ){
57897     n = nHeader + nPayload;
57898     testcase( n==3 );
57899     testcase( n==4 );
57900     if( n<4 ) n = 4;
57901     *pnSize = n;
57902     spaceLeft = nPayload;
57903     pPrior = pCell;
57904   }else{
57905     int mn = pPage->minLocal;
57906     n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
57907     testcase( n==pPage->maxLocal );
57908     testcase( n==pPage->maxLocal+1 );
57909     if( n > pPage->maxLocal ) n = mn;
57910     spaceLeft = n;
57911     *pnSize = n + nHeader + 4;
57912     pPrior = &pCell[nHeader+n];
57913   }
57914   pPayload = &pCell[nHeader];
57915 
57916   /* At this point variables should be set as follows:
57917   **
57918   **   nPayload           Total payload size in bytes
57919   **   pPayload           Begin writing payload here
57920   **   spaceLeft          Space available at pPayload.  If nPayload>spaceLeft,
57921   **                      that means content must spill into overflow pages.
57922   **   *pnSize            Size of the local cell (not counting overflow pages)
57923   **   pPrior             Where to write the pgno of the first overflow page
57924   **
57925   ** Use a call to btreeParseCellPtr() to verify that the values above
57926   ** were computed correctly.
57927   */
57928 #if SQLITE_DEBUG
57929   {
57930     CellInfo info;
57931     btreeParseCellPtr(pPage, pCell, &info);
57932     assert( nHeader=(int)(info.pPayload - pCell) );
57933     assert( info.nKey==nKey );
57934     assert( *pnSize == info.nSize );
57935     assert( spaceLeft == info.nLocal );
57936     assert( pPrior == &pCell[info.iOverflow] );
57937   }
57938 #endif
57939 
57940   /* Write the payload into the local Cell and any extra into overflow pages */
57941   while( nPayload>0 ){
57942     if( spaceLeft==0 ){
57943 #ifndef SQLITE_OMIT_AUTOVACUUM
57944       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
57945       if( pBt->autoVacuum ){
57946         do{
57947           pgnoOvfl++;
57948         } while(
57949           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
57950         );
57951       }
57952 #endif
57953       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
57954 #ifndef SQLITE_OMIT_AUTOVACUUM
57955       /* If the database supports auto-vacuum, and the second or subsequent
57956       ** overflow page is being allocated, add an entry to the pointer-map
57957       ** for that page now.
57958       **
57959       ** If this is the first overflow page, then write a partial entry
57960       ** to the pointer-map. If we write nothing to this pointer-map slot,
57961       ** then the optimistic overflow chain processing in clearCell()
57962       ** may misinterpret the uninitialized values and delete the
57963       ** wrong pages from the database.
57964       */
57965       if( pBt->autoVacuum && rc==SQLITE_OK ){
57966         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
57967         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
57968         if( rc ){
57969           releasePage(pOvfl);
57970         }
57971       }
57972 #endif
57973       if( rc ){
57974         releasePage(pToRelease);
57975         return rc;
57976       }
57977 
57978       /* If pToRelease is not zero than pPrior points into the data area
57979       ** of pToRelease.  Make sure pToRelease is still writeable. */
57980       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
57981 
57982       /* If pPrior is part of the data area of pPage, then make sure pPage
57983       ** is still writeable */
57984       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
57985             || sqlite3PagerIswriteable(pPage->pDbPage) );
57986 
57987       put4byte(pPrior, pgnoOvfl);
57988       releasePage(pToRelease);
57989       pToRelease = pOvfl;
57990       pPrior = pOvfl->aData;
57991       put4byte(pPrior, 0);
57992       pPayload = &pOvfl->aData[4];
57993       spaceLeft = pBt->usableSize - 4;
57994     }
57995     n = nPayload;
57996     if( n>spaceLeft ) n = spaceLeft;
57997 
57998     /* If pToRelease is not zero than pPayload points into the data area
57999     ** of pToRelease.  Make sure pToRelease is still writeable. */
58000     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
58001 
58002     /* If pPayload is part of the data area of pPage, then make sure pPage
58003     ** is still writeable */
58004     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
58005             || sqlite3PagerIswriteable(pPage->pDbPage) );
58006 
58007     if( nSrc>0 ){
58008       if( n>nSrc ) n = nSrc;
58009       assert( pSrc );
58010       memcpy(pPayload, pSrc, n);
58011     }else{
58012       memset(pPayload, 0, n);
58013     }
58014     nPayload -= n;
58015     pPayload += n;
58016     pSrc += n;
58017     nSrc -= n;
58018     spaceLeft -= n;
58019     if( nSrc==0 ){
58020       nSrc = nData;
58021       pSrc = pData;
58022     }
58023   }
58024   releasePage(pToRelease);
58025   return SQLITE_OK;
58026 }
58027 
58028 /*
58029 ** Remove the i-th cell from pPage.  This routine effects pPage only.
58030 ** The cell content is not freed or deallocated.  It is assumed that
58031 ** the cell content has been copied someplace else.  This routine just
58032 ** removes the reference to the cell from pPage.
58033 **
58034 ** "sz" must be the number of bytes in the cell.
58035 */
58036 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
58037   u32 pc;         /* Offset to cell content of cell being deleted */
58038   u8 *data;       /* pPage->aData */
58039   u8 *ptr;        /* Used to move bytes around within data[] */
58040   int rc;         /* The return code */
58041   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
58042 
58043   if( *pRC ) return;
58044 
58045   assert( idx>=0 && idx<pPage->nCell );
58046   assert( sz==cellSize(pPage, idx) );
58047   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
58048   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
58049   data = pPage->aData;
58050   ptr = &pPage->aCellIdx[2*idx];
58051   pc = get2byte(ptr);
58052   hdr = pPage->hdrOffset;
58053   testcase( pc==get2byte(&data[hdr+5]) );
58054   testcase( pc+sz==pPage->pBt->usableSize );
58055   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
58056     *pRC = SQLITE_CORRUPT_BKPT;
58057     return;
58058   }
58059   rc = freeSpace(pPage, pc, sz);
58060   if( rc ){
58061     *pRC = rc;
58062     return;
58063   }
58064   pPage->nCell--;
58065   memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
58066   put2byte(&data[hdr+3], pPage->nCell);
58067   pPage->nFree += 2;
58068 }
58069 
58070 /*
58071 ** Insert a new cell on pPage at cell index "i".  pCell points to the
58072 ** content of the cell.
58073 **
58074 ** If the cell content will fit on the page, then put it there.  If it
58075 ** will not fit, then make a copy of the cell content into pTemp if
58076 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
58077 ** in pPage->apOvfl[] and make it point to the cell content (either
58078 ** in pTemp or the original pCell) and also record its index.
58079 ** Allocating a new entry in pPage->aCell[] implies that
58080 ** pPage->nOverflow is incremented.
58081 */
58082 static void insertCell(
58083   MemPage *pPage,   /* Page into which we are copying */
58084   int i,            /* New cell becomes the i-th cell of the page */
58085   u8 *pCell,        /* Content of the new cell */
58086   int sz,           /* Bytes of content in pCell */
58087   u8 *pTemp,        /* Temp storage space for pCell, if needed */
58088   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
58089   int *pRC          /* Read and write return code from here */
58090 ){
58091   int idx = 0;      /* Where to write new cell content in data[] */
58092   int j;            /* Loop counter */
58093   int end;          /* First byte past the last cell pointer in data[] */
58094   int ins;          /* Index in data[] where new cell pointer is inserted */
58095   int cellOffset;   /* Address of first cell pointer in data[] */
58096   u8 *data;         /* The content of the whole page */
58097 
58098   if( *pRC ) return;
58099 
58100   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
58101   assert( MX_CELL(pPage->pBt)<=10921 );
58102   assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
58103   assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
58104   assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
58105   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
58106   /* The cell should normally be sized correctly.  However, when moving a
58107   ** malformed cell from a leaf page to an interior page, if the cell size
58108   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
58109   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
58110   ** the term after the || in the following assert(). */
58111   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
58112   if( pPage->nOverflow || sz+2>pPage->nFree ){
58113     if( pTemp ){
58114       memcpy(pTemp, pCell, sz);
58115       pCell = pTemp;
58116     }
58117     if( iChild ){
58118       put4byte(pCell, iChild);
58119     }
58120     j = pPage->nOverflow++;
58121     assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
58122     pPage->apOvfl[j] = pCell;
58123     pPage->aiOvfl[j] = (u16)i;
58124   }else{
58125     int rc = sqlite3PagerWrite(pPage->pDbPage);
58126     if( rc!=SQLITE_OK ){
58127       *pRC = rc;
58128       return;
58129     }
58130     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
58131     data = pPage->aData;
58132     cellOffset = pPage->cellOffset;
58133     end = cellOffset + 2*pPage->nCell;
58134     ins = cellOffset + 2*i;
58135     rc = allocateSpace(pPage, sz, &idx);
58136     if( rc ){ *pRC = rc; return; }
58137     /* The allocateSpace() routine guarantees the following two properties
58138     ** if it returns success */
58139     assert( idx >= end+2 );
58140     assert( idx+sz <= (int)pPage->pBt->usableSize );
58141     pPage->nCell++;
58142     pPage->nFree -= (u16)(2 + sz);
58143     memcpy(&data[idx], pCell, sz);
58144     if( iChild ){
58145       put4byte(&data[idx], iChild);
58146     }
58147     memmove(&data[ins+2], &data[ins], end-ins);
58148     put2byte(&data[ins], idx);
58149     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
58150 #ifndef SQLITE_OMIT_AUTOVACUUM
58151     if( pPage->pBt->autoVacuum ){
58152       /* The cell may contain a pointer to an overflow page. If so, write
58153       ** the entry for the overflow page into the pointer map.
58154       */
58155       ptrmapPutOvflPtr(pPage, pCell, pRC);
58156     }
58157 #endif
58158   }
58159 }
58160 
58161 /*
58162 ** Add a list of cells to a page.  The page should be initially empty.
58163 ** The cells are guaranteed to fit on the page.
58164 */
58165 static void assemblePage(
58166   MemPage *pPage,   /* The page to be assembled */
58167   int nCell,        /* The number of cells to add to this page */
58168   u8 **apCell,      /* Pointers to cell bodies */
58169   u16 *aSize        /* Sizes of the cells */
58170 ){
58171   int i;            /* Loop counter */
58172   u8 *pCellptr;     /* Address of next cell pointer */
58173   int cellbody;     /* Address of next cell body */
58174   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
58175   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
58176   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
58177 
58178   assert( pPage->nOverflow==0 );
58179   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
58180   assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
58181             && (int)MX_CELL(pPage->pBt)<=10921);
58182   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
58183 
58184   /* Check that the page has just been zeroed by zeroPage() */
58185   assert( pPage->nCell==0 );
58186   assert( get2byteNotZero(&data[hdr+5])==nUsable );
58187 
58188   pCellptr = &pPage->aCellIdx[nCell*2];
58189   cellbody = nUsable;
58190   for(i=nCell-1; i>=0; i--){
58191     u16 sz = aSize[i];
58192     pCellptr -= 2;
58193     cellbody -= sz;
58194     put2byte(pCellptr, cellbody);
58195     memcpy(&data[cellbody], apCell[i], sz);
58196   }
58197   put2byte(&data[hdr+3], nCell);
58198   put2byte(&data[hdr+5], cellbody);
58199   pPage->nFree -= (nCell*2 + nUsable - cellbody);
58200   pPage->nCell = (u16)nCell;
58201 }
58202 
58203 /*
58204 ** The following parameters determine how many adjacent pages get involved
58205 ** in a balancing operation.  NN is the number of neighbors on either side
58206 ** of the page that participate in the balancing operation.  NB is the
58207 ** total number of pages that participate, including the target page and
58208 ** NN neighbors on either side.
58209 **
58210 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
58211 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
58212 ** in exchange for a larger degradation in INSERT and UPDATE performance.
58213 ** The value of NN appears to give the best results overall.
58214 */
58215 #define NN 1             /* Number of neighbors on either side of pPage */
58216 #define NB (NN*2+1)      /* Total pages involved in the balance */
58217 
58218 
58219 #ifndef SQLITE_OMIT_QUICKBALANCE
58220 /*
58221 ** This version of balance() handles the common special case where
58222 ** a new entry is being inserted on the extreme right-end of the
58223 ** tree, in other words, when the new entry will become the largest
58224 ** entry in the tree.
58225 **
58226 ** Instead of trying to balance the 3 right-most leaf pages, just add
58227 ** a new page to the right-hand side and put the one new entry in
58228 ** that page.  This leaves the right side of the tree somewhat
58229 ** unbalanced.  But odds are that we will be inserting new entries
58230 ** at the end soon afterwards so the nearly empty page will quickly
58231 ** fill up.  On average.
58232 **
58233 ** pPage is the leaf page which is the right-most page in the tree.
58234 ** pParent is its parent.  pPage must have a single overflow entry
58235 ** which is also the right-most entry on the page.
58236 **
58237 ** The pSpace buffer is used to store a temporary copy of the divider
58238 ** cell that will be inserted into pParent. Such a cell consists of a 4
58239 ** byte page number followed by a variable length integer. In other
58240 ** words, at most 13 bytes. Hence the pSpace buffer must be at
58241 ** least 13 bytes in size.
58242 */
58243 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
58244   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
58245   MemPage *pNew;                       /* Newly allocated page */
58246   int rc;                              /* Return Code */
58247   Pgno pgnoNew;                        /* Page number of pNew */
58248 
58249   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
58250   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
58251   assert( pPage->nOverflow==1 );
58252 
58253   /* This error condition is now caught prior to reaching this function */
58254   if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
58255 
58256   /* Allocate a new page. This page will become the right-sibling of
58257   ** pPage. Make the parent page writable, so that the new divider cell
58258   ** may be inserted. If both these operations are successful, proceed.
58259   */
58260   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
58261 
58262   if( rc==SQLITE_OK ){
58263 
58264     u8 *pOut = &pSpace[4];
58265     u8 *pCell = pPage->apOvfl[0];
58266     u16 szCell = cellSizePtr(pPage, pCell);
58267     u8 *pStop;
58268 
58269     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
58270     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
58271     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
58272     assemblePage(pNew, 1, &pCell, &szCell);
58273 
58274     /* If this is an auto-vacuum database, update the pointer map
58275     ** with entries for the new page, and any pointer from the
58276     ** cell on the page to an overflow page. If either of these
58277     ** operations fails, the return code is set, but the contents
58278     ** of the parent page are still manipulated by thh code below.
58279     ** That is Ok, at this point the parent page is guaranteed to
58280     ** be marked as dirty. Returning an error code will cause a
58281     ** rollback, undoing any changes made to the parent page.
58282     */
58283     if( ISAUTOVACUUM ){
58284       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
58285       if( szCell>pNew->minLocal ){
58286         ptrmapPutOvflPtr(pNew, pCell, &rc);
58287       }
58288     }
58289 
58290     /* Create a divider cell to insert into pParent. The divider cell
58291     ** consists of a 4-byte page number (the page number of pPage) and
58292     ** a variable length key value (which must be the same value as the
58293     ** largest key on pPage).
58294     **
58295     ** To find the largest key value on pPage, first find the right-most
58296     ** cell on pPage. The first two fields of this cell are the
58297     ** record-length (a variable length integer at most 32-bits in size)
58298     ** and the key value (a variable length integer, may have any value).
58299     ** The first of the while(...) loops below skips over the record-length
58300     ** field. The second while(...) loop copies the key value from the
58301     ** cell on pPage into the pSpace buffer.
58302     */
58303     pCell = findCell(pPage, pPage->nCell-1);
58304     pStop = &pCell[9];
58305     while( (*(pCell++)&0x80) && pCell<pStop );
58306     pStop = &pCell[9];
58307     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
58308 
58309     /* Insert the new divider cell into pParent. */
58310     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
58311                0, pPage->pgno, &rc);
58312 
58313     /* Set the right-child pointer of pParent to point to the new page. */
58314     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
58315 
58316     /* Release the reference to the new page. */
58317     releasePage(pNew);
58318   }
58319 
58320   return rc;
58321 }
58322 #endif /* SQLITE_OMIT_QUICKBALANCE */
58323 
58324 #if 0
58325 /*
58326 ** This function does not contribute anything to the operation of SQLite.
58327 ** it is sometimes activated temporarily while debugging code responsible
58328 ** for setting pointer-map entries.
58329 */
58330 static int ptrmapCheckPages(MemPage **apPage, int nPage){
58331   int i, j;
58332   for(i=0; i<nPage; i++){
58333     Pgno n;
58334     u8 e;
58335     MemPage *pPage = apPage[i];
58336     BtShared *pBt = pPage->pBt;
58337     assert( pPage->isInit );
58338 
58339     for(j=0; j<pPage->nCell; j++){
58340       CellInfo info;
58341       u8 *z;
58342 
58343       z = findCell(pPage, j);
58344       btreeParseCellPtr(pPage, z, &info);
58345       if( info.iOverflow ){
58346         Pgno ovfl = get4byte(&z[info.iOverflow]);
58347         ptrmapGet(pBt, ovfl, &e, &n);
58348         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
58349       }
58350       if( !pPage->leaf ){
58351         Pgno child = get4byte(z);
58352         ptrmapGet(pBt, child, &e, &n);
58353         assert( n==pPage->pgno && e==PTRMAP_BTREE );
58354       }
58355     }
58356     if( !pPage->leaf ){
58357       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
58358       ptrmapGet(pBt, child, &e, &n);
58359       assert( n==pPage->pgno && e==PTRMAP_BTREE );
58360     }
58361   }
58362   return 1;
58363 }
58364 #endif
58365 
58366 /*
58367 ** This function is used to copy the contents of the b-tree node stored
58368 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
58369 ** the pointer-map entries for each child page are updated so that the
58370 ** parent page stored in the pointer map is page pTo. If pFrom contained
58371 ** any cells with overflow page pointers, then the corresponding pointer
58372 ** map entries are also updated so that the parent page is page pTo.
58373 **
58374 ** If pFrom is currently carrying any overflow cells (entries in the
58375 ** MemPage.apOvfl[] array), they are not copied to pTo.
58376 **
58377 ** Before returning, page pTo is reinitialized using btreeInitPage().
58378 **
58379 ** The performance of this function is not critical. It is only used by
58380 ** the balance_shallower() and balance_deeper() procedures, neither of
58381 ** which are called often under normal circumstances.
58382 */
58383 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
58384   if( (*pRC)==SQLITE_OK ){
58385     BtShared * const pBt = pFrom->pBt;
58386     u8 * const aFrom = pFrom->aData;
58387     u8 * const aTo = pTo->aData;
58388     int const iFromHdr = pFrom->hdrOffset;
58389     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
58390     int rc;
58391     int iData;
58392 
58393 
58394     assert( pFrom->isInit );
58395     assert( pFrom->nFree>=iToHdr );
58396     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
58397 
58398     /* Copy the b-tree node content from page pFrom to page pTo. */
58399     iData = get2byte(&aFrom[iFromHdr+5]);
58400     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
58401     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
58402 
58403     /* Reinitialize page pTo so that the contents of the MemPage structure
58404     ** match the new data. The initialization of pTo can actually fail under
58405     ** fairly obscure circumstances, even though it is a copy of initialized
58406     ** page pFrom.
58407     */
58408     pTo->isInit = 0;
58409     rc = btreeInitPage(pTo);
58410     if( rc!=SQLITE_OK ){
58411       *pRC = rc;
58412       return;
58413     }
58414 
58415     /* If this is an auto-vacuum database, update the pointer-map entries
58416     ** for any b-tree or overflow pages that pTo now contains the pointers to.
58417     */
58418     if( ISAUTOVACUUM ){
58419       *pRC = setChildPtrmaps(pTo);
58420     }
58421   }
58422 }
58423 
58424 /*
58425 ** This routine redistributes cells on the iParentIdx'th child of pParent
58426 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
58427 ** same amount of free space. Usually a single sibling on either side of the
58428 ** page are used in the balancing, though both siblings might come from one
58429 ** side if the page is the first or last child of its parent. If the page
58430 ** has fewer than 2 siblings (something which can only happen if the page
58431 ** is a root page or a child of a root page) then all available siblings
58432 ** participate in the balancing.
58433 **
58434 ** The number of siblings of the page might be increased or decreased by
58435 ** one or two in an effort to keep pages nearly full but not over full.
58436 **
58437 ** Note that when this routine is called, some of the cells on the page
58438 ** might not actually be stored in MemPage.aData[]. This can happen
58439 ** if the page is overfull. This routine ensures that all cells allocated
58440 ** to the page and its siblings fit into MemPage.aData[] before returning.
58441 **
58442 ** In the course of balancing the page and its siblings, cells may be
58443 ** inserted into or removed from the parent page (pParent). Doing so
58444 ** may cause the parent page to become overfull or underfull. If this
58445 ** happens, it is the responsibility of the caller to invoke the correct
58446 ** balancing routine to fix this problem (see the balance() routine).
58447 **
58448 ** If this routine fails for any reason, it might leave the database
58449 ** in a corrupted state. So if this routine fails, the database should
58450 ** be rolled back.
58451 **
58452 ** The third argument to this function, aOvflSpace, is a pointer to a
58453 ** buffer big enough to hold one page. If while inserting cells into the parent
58454 ** page (pParent) the parent page becomes overfull, this buffer is
58455 ** used to store the parent's overflow cells. Because this function inserts
58456 ** a maximum of four divider cells into the parent page, and the maximum
58457 ** size of a cell stored within an internal node is always less than 1/4
58458 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
58459 ** enough for all overflow cells.
58460 **
58461 ** If aOvflSpace is set to a null pointer, this function returns
58462 ** SQLITE_NOMEM.
58463 */
58464 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
58465 #pragma optimize("", off)
58466 #endif
58467 static int balance_nonroot(
58468   MemPage *pParent,               /* Parent page of siblings being balanced */
58469   int iParentIdx,                 /* Index of "the page" in pParent */
58470   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
58471   int isRoot,                     /* True if pParent is a root-page */
58472   int bBulk                       /* True if this call is part of a bulk load */
58473 ){
58474   BtShared *pBt;               /* The whole database */
58475   int nCell = 0;               /* Number of cells in apCell[] */
58476   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
58477   int nNew = 0;                /* Number of pages in apNew[] */
58478   int nOld;                    /* Number of pages in apOld[] */
58479   int i, j, k;                 /* Loop counters */
58480   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
58481   int rc = SQLITE_OK;          /* The return code */
58482   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
58483   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
58484   int usableSpace;             /* Bytes in pPage beyond the header */
58485   int pageFlags;               /* Value of pPage->aData[0] */
58486   int subtotal;                /* Subtotal of bytes in cells on one page */
58487   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
58488   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
58489   int szScratch;               /* Size of scratch memory requested */
58490   MemPage *apOld[NB];          /* pPage and up to two siblings */
58491   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
58492   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
58493   u8 *pRight;                  /* Location in parent of right-sibling pointer */
58494   u8 *apDiv[NB-1];             /* Divider cells in pParent */
58495   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
58496   int szNew[NB+2];             /* Combined size of cells place on i-th page */
58497   u8 **apCell = 0;             /* All cells begin balanced */
58498   u16 *szCell;                 /* Local size of all cells in apCell[] */
58499   u8 *aSpace1;                 /* Space for copies of dividers cells */
58500   Pgno pgno;                   /* Temp var to store a page number in */
58501 
58502   pBt = pParent->pBt;
58503   assert( sqlite3_mutex_held(pBt->mutex) );
58504   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
58505 
58506 #if 0
58507   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
58508 #endif
58509 
58510   /* At this point pParent may have at most one overflow cell. And if
58511   ** this overflow cell is present, it must be the cell with
58512   ** index iParentIdx. This scenario comes about when this function
58513   ** is called (indirectly) from sqlite3BtreeDelete().
58514   */
58515   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
58516   assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
58517 
58518   if( !aOvflSpace ){
58519     return SQLITE_NOMEM;
58520   }
58521 
58522   /* Find the sibling pages to balance. Also locate the cells in pParent
58523   ** that divide the siblings. An attempt is made to find NN siblings on
58524   ** either side of pPage. More siblings are taken from one side, however,
58525   ** if there are fewer than NN siblings on the other side. If pParent
58526   ** has NB or fewer children then all children of pParent are taken.
58527   **
58528   ** This loop also drops the divider cells from the parent page. This
58529   ** way, the remainder of the function does not have to deal with any
58530   ** overflow cells in the parent page, since if any existed they will
58531   ** have already been removed.
58532   */
58533   i = pParent->nOverflow + pParent->nCell;
58534   if( i<2 ){
58535     nxDiv = 0;
58536   }else{
58537     assert( bBulk==0 || bBulk==1 );
58538     if( iParentIdx==0 ){
58539       nxDiv = 0;
58540     }else if( iParentIdx==i ){
58541       nxDiv = i-2+bBulk;
58542     }else{
58543       assert( bBulk==0 );
58544       nxDiv = iParentIdx-1;
58545     }
58546     i = 2-bBulk;
58547   }
58548   nOld = i+1;
58549   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
58550     pRight = &pParent->aData[pParent->hdrOffset+8];
58551   }else{
58552     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
58553   }
58554   pgno = get4byte(pRight);
58555   while( 1 ){
58556     rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
58557     if( rc ){
58558       memset(apOld, 0, (i+1)*sizeof(MemPage*));
58559       goto balance_cleanup;
58560     }
58561     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
58562     if( (i--)==0 ) break;
58563 
58564     if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
58565       apDiv[i] = pParent->apOvfl[0];
58566       pgno = get4byte(apDiv[i]);
58567       szNew[i] = cellSizePtr(pParent, apDiv[i]);
58568       pParent->nOverflow = 0;
58569     }else{
58570       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
58571       pgno = get4byte(apDiv[i]);
58572       szNew[i] = cellSizePtr(pParent, apDiv[i]);
58573 
58574       /* Drop the cell from the parent page. apDiv[i] still points to
58575       ** the cell within the parent, even though it has been dropped.
58576       ** This is safe because dropping a cell only overwrites the first
58577       ** four bytes of it, and this function does not need the first
58578       ** four bytes of the divider cell. So the pointer is safe to use
58579       ** later on.
58580       **
58581       ** But not if we are in secure-delete mode. In secure-delete mode,
58582       ** the dropCell() routine will overwrite the entire cell with zeroes.
58583       ** In this case, temporarily copy the cell into the aOvflSpace[]
58584       ** buffer. It will be copied out again as soon as the aSpace[] buffer
58585       ** is allocated.  */
58586       if( pBt->btsFlags & BTS_SECURE_DELETE ){
58587         int iOff;
58588 
58589         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
58590         if( (iOff+szNew[i])>(int)pBt->usableSize ){
58591           rc = SQLITE_CORRUPT_BKPT;
58592           memset(apOld, 0, (i+1)*sizeof(MemPage*));
58593           goto balance_cleanup;
58594         }else{
58595           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
58596           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
58597         }
58598       }
58599       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
58600     }
58601   }
58602 
58603   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
58604   ** alignment */
58605   nMaxCells = (nMaxCells + 3)&~3;
58606 
58607   /*
58608   ** Allocate space for memory structures
58609   */
58610   k = pBt->pageSize + ROUND8(sizeof(MemPage));
58611   szScratch =
58612        nMaxCells*sizeof(u8*)                       /* apCell */
58613      + nMaxCells*sizeof(u16)                       /* szCell */
58614      + pBt->pageSize                               /* aSpace1 */
58615      + k*nOld;                                     /* Page copies (apCopy) */
58616   apCell = sqlite3ScratchMalloc( szScratch );
58617   if( apCell==0 ){
58618     rc = SQLITE_NOMEM;
58619     goto balance_cleanup;
58620   }
58621   szCell = (u16*)&apCell[nMaxCells];
58622   aSpace1 = (u8*)&szCell[nMaxCells];
58623   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
58624 
58625   /*
58626   ** Load pointers to all cells on sibling pages and the divider cells
58627   ** into the local apCell[] array.  Make copies of the divider cells
58628   ** into space obtained from aSpace1[] and remove the divider cells
58629   ** from pParent.
58630   **
58631   ** If the siblings are on leaf pages, then the child pointers of the
58632   ** divider cells are stripped from the cells before they are copied
58633   ** into aSpace1[].  In this way, all cells in apCell[] are without
58634   ** child pointers.  If siblings are not leaves, then all cell in
58635   ** apCell[] include child pointers.  Either way, all cells in apCell[]
58636   ** are alike.
58637   **
58638   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
58639   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
58640   */
58641   leafCorrection = apOld[0]->leaf*4;
58642   leafData = apOld[0]->intKeyLeaf;
58643   for(i=0; i<nOld; i++){
58644     int limit;
58645 
58646     /* Before doing anything else, take a copy of the i'th original sibling
58647     ** The rest of this function will use data from the copies rather
58648     ** that the original pages since the original pages will be in the
58649     ** process of being overwritten.  */
58650     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
58651     memcpy(pOld, apOld[i], sizeof(MemPage));
58652     pOld->aData = (void*)&pOld[1];
58653     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
58654 
58655     limit = pOld->nCell+pOld->nOverflow;
58656     if( pOld->nOverflow>0 ){
58657       for(j=0; j<limit; j++){
58658         assert( nCell<nMaxCells );
58659         apCell[nCell] = findOverflowCell(pOld, j);
58660         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
58661         nCell++;
58662       }
58663     }else{
58664       u8 *aData = pOld->aData;
58665       u16 maskPage = pOld->maskPage;
58666       u16 cellOffset = pOld->cellOffset;
58667       for(j=0; j<limit; j++){
58668         assert( nCell<nMaxCells );
58669         apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
58670         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
58671         nCell++;
58672       }
58673     }
58674     if( i<nOld-1 && !leafData){
58675       u16 sz = (u16)szNew[i];
58676       u8 *pTemp;
58677       assert( nCell<nMaxCells );
58678       szCell[nCell] = sz;
58679       pTemp = &aSpace1[iSpace1];
58680       iSpace1 += sz;
58681       assert( sz<=pBt->maxLocal+23 );
58682       assert( iSpace1 <= (int)pBt->pageSize );
58683       memcpy(pTemp, apDiv[i], sz);
58684       apCell[nCell] = pTemp+leafCorrection;
58685       assert( leafCorrection==0 || leafCorrection==4 );
58686       szCell[nCell] = szCell[nCell] - leafCorrection;
58687       if( !pOld->leaf ){
58688         assert( leafCorrection==0 );
58689         assert( pOld->hdrOffset==0 );
58690         /* The right pointer of the child page pOld becomes the left
58691         ** pointer of the divider cell */
58692         memcpy(apCell[nCell], &pOld->aData[8], 4);
58693       }else{
58694         assert( leafCorrection==4 );
58695         if( szCell[nCell]<4 ){
58696           /* Do not allow any cells smaller than 4 bytes. */
58697           szCell[nCell] = 4;
58698         }
58699       }
58700       nCell++;
58701     }
58702   }
58703 
58704   /*
58705   ** Figure out the number of pages needed to hold all nCell cells.
58706   ** Store this number in "k".  Also compute szNew[] which is the total
58707   ** size of all cells on the i-th page and cntNew[] which is the index
58708   ** in apCell[] of the cell that divides page i from page i+1.
58709   ** cntNew[k] should equal nCell.
58710   **
58711   ** Values computed by this block:
58712   **
58713   **           k: The total number of sibling pages
58714   **    szNew[i]: Spaced used on the i-th sibling page.
58715   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
58716   **              the right of the i-th sibling page.
58717   ** usableSpace: Number of bytes of space available on each sibling.
58718   **
58719   */
58720   usableSpace = pBt->usableSize - 12 + leafCorrection;
58721   for(subtotal=k=i=0; i<nCell; i++){
58722     assert( i<nMaxCells );
58723     subtotal += szCell[i] + 2;
58724     if( subtotal > usableSpace ){
58725       szNew[k] = subtotal - szCell[i];
58726       cntNew[k] = i;
58727       if( leafData ){ i--; }
58728       subtotal = 0;
58729       k++;
58730       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
58731     }
58732   }
58733   szNew[k] = subtotal;
58734   cntNew[k] = nCell;
58735   k++;
58736 
58737   /*
58738   ** The packing computed by the previous block is biased toward the siblings
58739   ** on the left side.  The left siblings are always nearly full, while the
58740   ** right-most sibling might be nearly empty.  This block of code attempts
58741   ** to adjust the packing of siblings to get a better balance.
58742   **
58743   ** This adjustment is more than an optimization.  The packing above might
58744   ** be so out of balance as to be illegal.  For example, the right-most
58745   ** sibling might be completely empty.  This adjustment is not optional.
58746   */
58747   for(i=k-1; i>0; i--){
58748     int szRight = szNew[i];  /* Size of sibling on the right */
58749     int szLeft = szNew[i-1]; /* Size of sibling on the left */
58750     int r;              /* Index of right-most cell in left sibling */
58751     int d;              /* Index of first cell to the left of right sibling */
58752 
58753     r = cntNew[i-1] - 1;
58754     d = r + 1 - leafData;
58755     assert( d<nMaxCells );
58756     assert( r<nMaxCells );
58757     while( szRight==0
58758        || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
58759     ){
58760       szRight += szCell[d] + 2;
58761       szLeft -= szCell[r] + 2;
58762       cntNew[i-1]--;
58763       r = cntNew[i-1] - 1;
58764       d = r + 1 - leafData;
58765     }
58766     szNew[i] = szRight;
58767     szNew[i-1] = szLeft;
58768   }
58769 
58770   /* Either we found one or more cells (cntnew[0])>0) or pPage is
58771   ** a virtual root page.  A virtual root page is when the real root
58772   ** page is page 1 and we are the only child of that page.
58773   **
58774   ** UPDATE:  The assert() below is not necessarily true if the database
58775   ** file is corrupt.  The corruption will be detected and reported later
58776   ** in this procedure so there is no need to act upon it now.
58777   */
58778 #if 0
58779   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
58780 #endif
58781 
58782   TRACE(("BALANCE: old: %d %d %d  ",
58783     apOld[0]->pgno,
58784     nOld>=2 ? apOld[1]->pgno : 0,
58785     nOld>=3 ? apOld[2]->pgno : 0
58786   ));
58787 
58788   /*
58789   ** Allocate k new pages.  Reuse old pages where possible.
58790   */
58791   if( apOld[0]->pgno<=1 ){
58792     rc = SQLITE_CORRUPT_BKPT;
58793     goto balance_cleanup;
58794   }
58795   pageFlags = apOld[0]->aData[0];
58796   for(i=0; i<k; i++){
58797     MemPage *pNew;
58798     if( i<nOld ){
58799       pNew = apNew[i] = apOld[i];
58800       apOld[i] = 0;
58801       rc = sqlite3PagerWrite(pNew->pDbPage);
58802       nNew++;
58803       if( rc ) goto balance_cleanup;
58804     }else{
58805       assert( i>0 );
58806       rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
58807       if( rc ) goto balance_cleanup;
58808       apNew[i] = pNew;
58809       nNew++;
58810 
58811       /* Set the pointer-map entry for the new sibling page. */
58812       if( ISAUTOVACUUM ){
58813         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
58814         if( rc!=SQLITE_OK ){
58815           goto balance_cleanup;
58816         }
58817       }
58818     }
58819   }
58820 
58821   /* Free any old pages that were not reused as new pages.
58822   */
58823   while( i<nOld ){
58824     freePage(apOld[i], &rc);
58825     if( rc ) goto balance_cleanup;
58826     releasePage(apOld[i]);
58827     apOld[i] = 0;
58828     i++;
58829   }
58830 
58831   /*
58832   ** Put the new pages in ascending order.  This helps to
58833   ** keep entries in the disk file in order so that a scan
58834   ** of the table is a linear scan through the file.  That
58835   ** in turn helps the operating system to deliver pages
58836   ** from the disk more rapidly.
58837   **
58838   ** An O(n^2) insertion sort algorithm is used, but since
58839   ** n is never more than NB (a small constant), that should
58840   ** not be a problem.
58841   **
58842   ** When NB==3, this one optimization makes the database
58843   ** about 25% faster for large insertions and deletions.
58844   */
58845   for(i=0; i<k-1; i++){
58846     int minV = apNew[i]->pgno;
58847     int minI = i;
58848     for(j=i+1; j<k; j++){
58849       if( apNew[j]->pgno<(unsigned)minV ){
58850         minI = j;
58851         minV = apNew[j]->pgno;
58852       }
58853     }
58854     if( minI>i ){
58855       MemPage *pT;
58856       pT = apNew[i];
58857       apNew[i] = apNew[minI];
58858       apNew[minI] = pT;
58859     }
58860   }
58861   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
58862     apNew[0]->pgno, szNew[0],
58863     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
58864     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
58865     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
58866     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
58867 
58868   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
58869   put4byte(pRight, apNew[nNew-1]->pgno);
58870 
58871   /*
58872   ** Evenly distribute the data in apCell[] across the new pages.
58873   ** Insert divider cells into pParent as necessary.
58874   */
58875   j = 0;
58876   for(i=0; i<nNew; i++){
58877     /* Assemble the new sibling page. */
58878     MemPage *pNew = apNew[i];
58879     assert( j<nMaxCells );
58880     zeroPage(pNew, pageFlags);
58881     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
58882     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
58883     assert( pNew->nOverflow==0 );
58884 
58885     j = cntNew[i];
58886 
58887     /* If the sibling page assembled above was not the right-most sibling,
58888     ** insert a divider cell into the parent page.
58889     */
58890     assert( i<nNew-1 || j==nCell );
58891     if( j<nCell ){
58892       u8 *pCell;
58893       u8 *pTemp;
58894       int sz;
58895 
58896       assert( j<nMaxCells );
58897       pCell = apCell[j];
58898       sz = szCell[j] + leafCorrection;
58899       pTemp = &aOvflSpace[iOvflSpace];
58900       if( !pNew->leaf ){
58901         memcpy(&pNew->aData[8], pCell, 4);
58902       }else if( leafData ){
58903         /* If the tree is a leaf-data tree, and the siblings are leaves,
58904         ** then there is no divider cell in apCell[]. Instead, the divider
58905         ** cell consists of the integer key for the right-most cell of
58906         ** the sibling-page assembled above only.
58907         */
58908         CellInfo info;
58909         j--;
58910         btreeParseCellPtr(pNew, apCell[j], &info);
58911         pCell = pTemp;
58912         sz = 4 + putVarint(&pCell[4], info.nKey);
58913         pTemp = 0;
58914       }else{
58915         pCell -= 4;
58916         /* Obscure case for non-leaf-data trees: If the cell at pCell was
58917         ** previously stored on a leaf node, and its reported size was 4
58918         ** bytes, then it may actually be smaller than this
58919         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
58920         ** any cell). But it is important to pass the correct size to
58921         ** insertCell(), so reparse the cell now.
58922         **
58923         ** Note that this can never happen in an SQLite data file, as all
58924         ** cells are at least 4 bytes. It only happens in b-trees used
58925         ** to evaluate "IN (SELECT ...)" and similar clauses.
58926         */
58927         if( szCell[j]==4 ){
58928           assert(leafCorrection==4);
58929           sz = cellSizePtr(pParent, pCell);
58930         }
58931       }
58932       iOvflSpace += sz;
58933       assert( sz<=pBt->maxLocal+23 );
58934       assert( iOvflSpace <= (int)pBt->pageSize );
58935       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
58936       if( rc!=SQLITE_OK ) goto balance_cleanup;
58937       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
58938 
58939       j++;
58940       nxDiv++;
58941     }
58942   }
58943   assert( j==nCell );
58944   assert( nOld>0 );
58945   assert( nNew>0 );
58946   if( (pageFlags & PTF_LEAF)==0 ){
58947     u8 *zChild = &apCopy[nOld-1]->aData[8];
58948     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
58949   }
58950 
58951   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
58952     /* The root page of the b-tree now contains no cells. The only sibling
58953     ** page is the right-child of the parent. Copy the contents of the
58954     ** child page into the parent, decreasing the overall height of the
58955     ** b-tree structure by one. This is described as the "balance-shallower"
58956     ** sub-algorithm in some documentation.
58957     **
58958     ** If this is an auto-vacuum database, the call to copyNodeContent()
58959     ** sets all pointer-map entries corresponding to database image pages
58960     ** for which the pointer is stored within the content being copied.
58961     **
58962     ** The second assert below verifies that the child page is defragmented
58963     ** (it must be, as it was just reconstructed using assemblePage()). This
58964     ** is important if the parent page happens to be page 1 of the database
58965     ** image.  */
58966     assert( nNew==1 );
58967     assert( apNew[0]->nFree ==
58968         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
58969     );
58970     copyNodeContent(apNew[0], pParent, &rc);
58971     freePage(apNew[0], &rc);
58972   }else if( ISAUTOVACUUM ){
58973     /* Fix the pointer-map entries for all the cells that were shifted around.
58974     ** There are several different types of pointer-map entries that need to
58975     ** be dealt with by this routine. Some of these have been set already, but
58976     ** many have not. The following is a summary:
58977     **
58978     **   1) The entries associated with new sibling pages that were not
58979     **      siblings when this function was called. These have already
58980     **      been set. We don't need to worry about old siblings that were
58981     **      moved to the free-list - the freePage() code has taken care
58982     **      of those.
58983     **
58984     **   2) The pointer-map entries associated with the first overflow
58985     **      page in any overflow chains used by new divider cells. These
58986     **      have also already been taken care of by the insertCell() code.
58987     **
58988     **   3) If the sibling pages are not leaves, then the child pages of
58989     **      cells stored on the sibling pages may need to be updated.
58990     **
58991     **   4) If the sibling pages are not internal intkey nodes, then any
58992     **      overflow pages used by these cells may need to be updated
58993     **      (internal intkey nodes never contain pointers to overflow pages).
58994     **
58995     **   5) If the sibling pages are not leaves, then the pointer-map
58996     **      entries for the right-child pages of each sibling may need
58997     **      to be updated.
58998     **
58999     ** Cases 1 and 2 are dealt with above by other code. The next
59000     ** block deals with cases 3 and 4 and the one after that, case 5. Since
59001     ** setting a pointer map entry is a relatively expensive operation, this
59002     ** code only sets pointer map entries for child or overflow pages that have
59003     ** actually moved between pages.  */
59004     MemPage *pNew = apNew[0];
59005     MemPage *pOld = apCopy[0];
59006     int nOverflow = pOld->nOverflow;
59007     int iNextOld = pOld->nCell + nOverflow;
59008     int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
59009     j = 0;                             /* Current 'old' sibling page */
59010     k = 0;                             /* Current 'new' sibling page */
59011     for(i=0; i<nCell; i++){
59012       int isDivider = 0;
59013       while( i==iNextOld ){
59014         /* Cell i is the cell immediately following the last cell on old
59015         ** sibling page j. If the siblings are not leaf pages of an
59016         ** intkey b-tree, then cell i was a divider cell. */
59017         assert( j+1 < ArraySize(apCopy) );
59018         assert( j+1 < nOld );
59019         pOld = apCopy[++j];
59020         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
59021         if( pOld->nOverflow ){
59022           nOverflow = pOld->nOverflow;
59023           iOverflow = i + !leafData + pOld->aiOvfl[0];
59024         }
59025         isDivider = !leafData;
59026       }
59027 
59028       assert(nOverflow>0 || iOverflow<i );
59029       assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
59030       assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
59031       if( i==iOverflow ){
59032         isDivider = 1;
59033         if( (--nOverflow)>0 ){
59034           iOverflow++;
59035         }
59036       }
59037 
59038       if( i==cntNew[k] ){
59039         /* Cell i is the cell immediately following the last cell on new
59040         ** sibling page k. If the siblings are not leaf pages of an
59041         ** intkey b-tree, then cell i is a divider cell.  */
59042         pNew = apNew[++k];
59043         if( !leafData ) continue;
59044       }
59045       assert( j<nOld );
59046       assert( k<nNew );
59047 
59048       /* If the cell was originally divider cell (and is not now) or
59049       ** an overflow cell, or if the cell was located on a different sibling
59050       ** page before the balancing, then the pointer map entries associated
59051       ** with any child or overflow pages need to be updated.  */
59052       if( isDivider || pOld->pgno!=pNew->pgno ){
59053         if( !leafCorrection ){
59054           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
59055         }
59056         if( szCell[i]>pNew->minLocal ){
59057           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
59058         }
59059       }
59060     }
59061 
59062     if( !leafCorrection ){
59063       for(i=0; i<nNew; i++){
59064         u32 key = get4byte(&apNew[i]->aData[8]);
59065         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
59066       }
59067     }
59068 
59069 #if 0
59070     /* The ptrmapCheckPages() contains assert() statements that verify that
59071     ** all pointer map pages are set correctly. This is helpful while
59072     ** debugging. This is usually disabled because a corrupt database may
59073     ** cause an assert() statement to fail.  */
59074     ptrmapCheckPages(apNew, nNew);
59075     ptrmapCheckPages(&pParent, 1);
59076 #endif
59077   }
59078 
59079   assert( pParent->isInit );
59080   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
59081           nOld, nNew, nCell));
59082 
59083   /*
59084   ** Cleanup before returning.
59085   */
59086 balance_cleanup:
59087   sqlite3ScratchFree(apCell);
59088   for(i=0; i<nOld; i++){
59089     releasePage(apOld[i]);
59090   }
59091   for(i=0; i<nNew; i++){
59092     releasePage(apNew[i]);
59093   }
59094 
59095   return rc;
59096 }
59097 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
59098 #pragma optimize("", on)
59099 #endif
59100 
59101 
59102 /*
59103 ** This function is called when the root page of a b-tree structure is
59104 ** overfull (has one or more overflow pages).
59105 **
59106 ** A new child page is allocated and the contents of the current root
59107 ** page, including overflow cells, are copied into the child. The root
59108 ** page is then overwritten to make it an empty page with the right-child
59109 ** pointer pointing to the new page.
59110 **
59111 ** Before returning, all pointer-map entries corresponding to pages
59112 ** that the new child-page now contains pointers to are updated. The
59113 ** entry corresponding to the new right-child pointer of the root
59114 ** page is also updated.
59115 **
59116 ** If successful, *ppChild is set to contain a reference to the child
59117 ** page and SQLITE_OK is returned. In this case the caller is required
59118 ** to call releasePage() on *ppChild exactly once. If an error occurs,
59119 ** an error code is returned and *ppChild is set to 0.
59120 */
59121 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
59122   int rc;                        /* Return value from subprocedures */
59123   MemPage *pChild = 0;           /* Pointer to a new child page */
59124   Pgno pgnoChild = 0;            /* Page number of the new child page */
59125   BtShared *pBt = pRoot->pBt;    /* The BTree */
59126 
59127   assert( pRoot->nOverflow>0 );
59128   assert( sqlite3_mutex_held(pBt->mutex) );
59129 
59130   /* Make pRoot, the root page of the b-tree, writable. Allocate a new
59131   ** page that will become the new right-child of pPage. Copy the contents
59132   ** of the node stored on pRoot into the new child page.
59133   */
59134   rc = sqlite3PagerWrite(pRoot->pDbPage);
59135   if( rc==SQLITE_OK ){
59136     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
59137     copyNodeContent(pRoot, pChild, &rc);
59138     if( ISAUTOVACUUM ){
59139       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
59140     }
59141   }
59142   if( rc ){
59143     *ppChild = 0;
59144     releasePage(pChild);
59145     return rc;
59146   }
59147   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
59148   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
59149   assert( pChild->nCell==pRoot->nCell );
59150 
59151   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
59152 
59153   /* Copy the overflow cells from pRoot to pChild */
59154   memcpy(pChild->aiOvfl, pRoot->aiOvfl,
59155          pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
59156   memcpy(pChild->apOvfl, pRoot->apOvfl,
59157          pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
59158   pChild->nOverflow = pRoot->nOverflow;
59159 
59160   /* Zero the contents of pRoot. Then install pChild as the right-child. */
59161   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
59162   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
59163 
59164   *ppChild = pChild;
59165   return SQLITE_OK;
59166 }
59167 
59168 /*
59169 ** The page that pCur currently points to has just been modified in
59170 ** some way. This function figures out if this modification means the
59171 ** tree needs to be balanced, and if so calls the appropriate balancing
59172 ** routine. Balancing routines are:
59173 **
59174 **   balance_quick()
59175 **   balance_deeper()
59176 **   balance_nonroot()
59177 */
59178 static int balance(BtCursor *pCur){
59179   int rc = SQLITE_OK;
59180   const int nMin = pCur->pBt->usableSize * 2 / 3;
59181   u8 aBalanceQuickSpace[13];
59182   u8 *pFree = 0;
59183 
59184   TESTONLY( int balance_quick_called = 0 );
59185   TESTONLY( int balance_deeper_called = 0 );
59186 
59187   do {
59188     int iPage = pCur->iPage;
59189     MemPage *pPage = pCur->apPage[iPage];
59190 
59191     if( iPage==0 ){
59192       if( pPage->nOverflow ){
59193         /* The root page of the b-tree is overfull. In this case call the
59194         ** balance_deeper() function to create a new child for the root-page
59195         ** and copy the current contents of the root-page to it. The
59196         ** next iteration of the do-loop will balance the child page.
59197         */
59198         assert( (balance_deeper_called++)==0 );
59199         rc = balance_deeper(pPage, &pCur->apPage[1]);
59200         if( rc==SQLITE_OK ){
59201           pCur->iPage = 1;
59202           pCur->aiIdx[0] = 0;
59203           pCur->aiIdx[1] = 0;
59204           assert( pCur->apPage[1]->nOverflow );
59205         }
59206       }else{
59207         break;
59208       }
59209     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
59210       break;
59211     }else{
59212       MemPage * const pParent = pCur->apPage[iPage-1];
59213       int const iIdx = pCur->aiIdx[iPage-1];
59214 
59215       rc = sqlite3PagerWrite(pParent->pDbPage);
59216       if( rc==SQLITE_OK ){
59217 #ifndef SQLITE_OMIT_QUICKBALANCE
59218         if( pPage->intKeyLeaf
59219          && pPage->nOverflow==1
59220          && pPage->aiOvfl[0]==pPage->nCell
59221          && pParent->pgno!=1
59222          && pParent->nCell==iIdx
59223         ){
59224           /* Call balance_quick() to create a new sibling of pPage on which
59225           ** to store the overflow cell. balance_quick() inserts a new cell
59226           ** into pParent, which may cause pParent overflow. If this
59227           ** happens, the next iteration of the do-loop will balance pParent
59228           ** use either balance_nonroot() or balance_deeper(). Until this
59229           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
59230           ** buffer.
59231           **
59232           ** The purpose of the following assert() is to check that only a
59233           ** single call to balance_quick() is made for each call to this
59234           ** function. If this were not verified, a subtle bug involving reuse
59235           ** of the aBalanceQuickSpace[] might sneak in.
59236           */
59237           assert( (balance_quick_called++)==0 );
59238           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
59239         }else
59240 #endif
59241         {
59242           /* In this case, call balance_nonroot() to redistribute cells
59243           ** between pPage and up to 2 of its sibling pages. This involves
59244           ** modifying the contents of pParent, which may cause pParent to
59245           ** become overfull or underfull. The next iteration of the do-loop
59246           ** will balance the parent page to correct this.
59247           **
59248           ** If the parent page becomes overfull, the overflow cell or cells
59249           ** are stored in the pSpace buffer allocated immediately below.
59250           ** A subsequent iteration of the do-loop will deal with this by
59251           ** calling balance_nonroot() (balance_deeper() may be called first,
59252           ** but it doesn't deal with overflow cells - just moves them to a
59253           ** different page). Once this subsequent call to balance_nonroot()
59254           ** has completed, it is safe to release the pSpace buffer used by
59255           ** the previous call, as the overflow cell data will have been
59256           ** copied either into the body of a database page or into the new
59257           ** pSpace buffer passed to the latter call to balance_nonroot().
59258           */
59259           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
59260           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
59261           if( pFree ){
59262             /* If pFree is not NULL, it points to the pSpace buffer used
59263             ** by a previous call to balance_nonroot(). Its contents are
59264             ** now stored either on real database pages or within the
59265             ** new pSpace buffer, so it may be safely freed here. */
59266             sqlite3PageFree(pFree);
59267           }
59268 
59269           /* The pSpace buffer will be freed after the next call to
59270           ** balance_nonroot(), or just before this function returns, whichever
59271           ** comes first. */
59272           pFree = pSpace;
59273         }
59274       }
59275 
59276       pPage->nOverflow = 0;
59277 
59278       /* The next iteration of the do-loop balances the parent page. */
59279       releasePage(pPage);
59280       pCur->iPage--;
59281     }
59282   }while( rc==SQLITE_OK );
59283 
59284   if( pFree ){
59285     sqlite3PageFree(pFree);
59286   }
59287   return rc;
59288 }
59289 
59290 
59291 /*
59292 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
59293 ** and the data is given by (pData,nData).  The cursor is used only to
59294 ** define what table the record should be inserted into.  The cursor
59295 ** is left pointing at a random location.
59296 **
59297 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
59298 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
59299 **
59300 ** If the seekResult parameter is non-zero, then a successful call to
59301 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
59302 ** been performed. seekResult is the search result returned (a negative
59303 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
59304 ** a positive value if pCur points at an entry that is larger than
59305 ** (pKey, nKey)).
59306 **
59307 ** If the seekResult parameter is non-zero, then the caller guarantees that
59308 ** cursor pCur is pointing at the existing copy of a row that is to be
59309 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
59310 ** point to any entry or to no entry at all and so this function has to seek
59311 ** the cursor before the new key can be inserted.
59312 */
59313 SQLITE_PRIVATE int sqlite3BtreeInsert(
59314   BtCursor *pCur,                /* Insert data into the table of this cursor */
59315   const void *pKey, i64 nKey,    /* The key of the new record */
59316   const void *pData, int nData,  /* The data of the new record */
59317   int nZero,                     /* Number of extra 0 bytes to append to data */
59318   int appendBias,                /* True if this is likely an append */
59319   int seekResult                 /* Result of prior MovetoUnpacked() call */
59320 ){
59321   int rc;
59322   int loc = seekResult;          /* -1: before desired location  +1: after */
59323   int szNew = 0;
59324   int idx;
59325   MemPage *pPage;
59326   Btree *p = pCur->pBtree;
59327   BtShared *pBt = p->pBt;
59328   unsigned char *oldCell;
59329   unsigned char *newCell = 0;
59330 
59331   if( pCur->eState==CURSOR_FAULT ){
59332     assert( pCur->skipNext!=SQLITE_OK );
59333     return pCur->skipNext;
59334   }
59335 
59336   assert( cursorHoldsMutex(pCur) );
59337   assert( (pCur->curFlags & BTCF_WriteFlag)!=0
59338               && pBt->inTransaction==TRANS_WRITE
59339               && (pBt->btsFlags & BTS_READ_ONLY)==0 );
59340   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
59341 
59342   /* Assert that the caller has been consistent. If this cursor was opened
59343   ** expecting an index b-tree, then the caller should be inserting blob
59344   ** keys with no associated data. If the cursor was opened expecting an
59345   ** intkey table, the caller should be inserting integer keys with a
59346   ** blob of associated data.  */
59347   assert( (pKey==0)==(pCur->pKeyInfo==0) );
59348 
59349   /* Save the positions of any other cursors open on this table.
59350   **
59351   ** In some cases, the call to btreeMoveto() below is a no-op. For
59352   ** example, when inserting data into a table with auto-generated integer
59353   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
59354   ** integer key to use. It then calls this function to actually insert the
59355   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
59356   ** that the cursor is already where it needs to be and returns without
59357   ** doing any work. To avoid thwarting these optimizations, it is important
59358   ** not to clear the cursor here.
59359   */
59360   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
59361   if( rc ) return rc;
59362 
59363   if( pCur->pKeyInfo==0 ){
59364     /* If this is an insert into a table b-tree, invalidate any incrblob
59365     ** cursors open on the row being replaced */
59366     invalidateIncrblobCursors(p, nKey, 0);
59367 
59368     /* If the cursor is currently on the last row and we are appending a
59369     ** new row onto the end, set the "loc" to avoid an unnecessary btreeMoveto()
59370     ** call */
59371     if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0
59372       && pCur->info.nKey==nKey-1 ){
59373       loc = -1;
59374     }
59375   }
59376 
59377   if( !loc ){
59378     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
59379     if( rc ) return rc;
59380   }
59381   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
59382 
59383   pPage = pCur->apPage[pCur->iPage];
59384   assert( pPage->intKey || nKey>=0 );
59385   assert( pPage->leaf || !pPage->intKey );
59386 
59387   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
59388           pCur->pgnoRoot, nKey, nData, pPage->pgno,
59389           loc==0 ? "overwrite" : "new entry"));
59390   assert( pPage->isInit );
59391   newCell = pBt->pTmpSpace;
59392   assert( newCell!=0 );
59393   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
59394   if( rc ) goto end_insert;
59395   assert( szNew==cellSizePtr(pPage, newCell) );
59396   assert( szNew <= MX_CELL_SIZE(pBt) );
59397   idx = pCur->aiIdx[pCur->iPage];
59398   if( loc==0 ){
59399     u16 szOld;
59400     assert( idx<pPage->nCell );
59401     rc = sqlite3PagerWrite(pPage->pDbPage);
59402     if( rc ){
59403       goto end_insert;
59404     }
59405     oldCell = findCell(pPage, idx);
59406     if( !pPage->leaf ){
59407       memcpy(newCell, oldCell, 4);
59408     }
59409     rc = clearCell(pPage, oldCell, &szOld);
59410     dropCell(pPage, idx, szOld, &rc);
59411     if( rc ) goto end_insert;
59412   }else if( loc<0 && pPage->nCell>0 ){
59413     assert( pPage->leaf );
59414     idx = ++pCur->aiIdx[pCur->iPage];
59415   }else{
59416     assert( pPage->leaf );
59417   }
59418   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
59419   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
59420 
59421   /* If no error has occurred and pPage has an overflow cell, call balance()
59422   ** to redistribute the cells within the tree. Since balance() may move
59423   ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
59424   ** variables.
59425   **
59426   ** Previous versions of SQLite called moveToRoot() to move the cursor
59427   ** back to the root page as balance() used to invalidate the contents
59428   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
59429   ** set the cursor state to "invalid". This makes common insert operations
59430   ** slightly faster.
59431   **
59432   ** There is a subtle but important optimization here too. When inserting
59433   ** multiple records into an intkey b-tree using a single cursor (as can
59434   ** happen while processing an "INSERT INTO ... SELECT" statement), it
59435   ** is advantageous to leave the cursor pointing to the last entry in
59436   ** the b-tree if possible. If the cursor is left pointing to the last
59437   ** entry in the table, and the next row inserted has an integer key
59438   ** larger than the largest existing key, it is possible to insert the
59439   ** row without seeking the cursor. This can be a big performance boost.
59440   */
59441   pCur->info.nSize = 0;
59442   if( rc==SQLITE_OK && pPage->nOverflow ){
59443     pCur->curFlags &= ~(BTCF_ValidNKey);
59444     rc = balance(pCur);
59445 
59446     /* Must make sure nOverflow is reset to zero even if the balance()
59447     ** fails. Internal data structure corruption will result otherwise.
59448     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
59449     ** from trying to save the current position of the cursor.  */
59450     pCur->apPage[pCur->iPage]->nOverflow = 0;
59451     pCur->eState = CURSOR_INVALID;
59452   }
59453   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
59454 
59455 end_insert:
59456   return rc;
59457 }
59458 
59459 /*
59460 ** Delete the entry that the cursor is pointing to.  The cursor
59461 ** is left pointing at an arbitrary location.
59462 */
59463 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
59464   Btree *p = pCur->pBtree;
59465   BtShared *pBt = p->pBt;
59466   int rc;                              /* Return code */
59467   MemPage *pPage;                      /* Page to delete cell from */
59468   unsigned char *pCell;                /* Pointer to cell to delete */
59469   int iCellIdx;                        /* Index of cell to delete */
59470   int iCellDepth;                      /* Depth of node containing pCell */
59471   u16 szCell;                          /* Size of the cell being deleted */
59472 
59473   assert( cursorHoldsMutex(pCur) );
59474   assert( pBt->inTransaction==TRANS_WRITE );
59475   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
59476   assert( pCur->curFlags & BTCF_WriteFlag );
59477   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
59478   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
59479 
59480   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
59481    || NEVER(pCur->eState!=CURSOR_VALID)
59482   ){
59483     return SQLITE_ERROR;  /* Something has gone awry. */
59484   }
59485 
59486   iCellDepth = pCur->iPage;
59487   iCellIdx = pCur->aiIdx[iCellDepth];
59488   pPage = pCur->apPage[iCellDepth];
59489   pCell = findCell(pPage, iCellIdx);
59490 
59491   /* If the page containing the entry to delete is not a leaf page, move
59492   ** the cursor to the largest entry in the tree that is smaller than
59493   ** the entry being deleted. This cell will replace the cell being deleted
59494   ** from the internal node. The 'previous' entry is used for this instead
59495   ** of the 'next' entry, as the previous entry is always a part of the
59496   ** sub-tree headed by the child page of the cell being deleted. This makes
59497   ** balancing the tree following the delete operation easier.  */
59498   if( !pPage->leaf ){
59499     int notUsed = 0;
59500     rc = sqlite3BtreePrevious(pCur, &notUsed);
59501     if( rc ) return rc;
59502   }
59503 
59504   /* Save the positions of any other cursors open on this table before
59505   ** making any modifications. Make the page containing the entry to be
59506   ** deleted writable. Then free any overflow pages associated with the
59507   ** entry and finally remove the cell itself from within the page.
59508   */
59509   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
59510   if( rc ) return rc;
59511 
59512   /* If this is a delete operation to remove a row from a table b-tree,
59513   ** invalidate any incrblob cursors open on the row being deleted.  */
59514   if( pCur->pKeyInfo==0 ){
59515     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
59516   }
59517 
59518   rc = sqlite3PagerWrite(pPage->pDbPage);
59519   if( rc ) return rc;
59520   rc = clearCell(pPage, pCell, &szCell);
59521   dropCell(pPage, iCellIdx, szCell, &rc);
59522   if( rc ) return rc;
59523 
59524   /* If the cell deleted was not located on a leaf page, then the cursor
59525   ** is currently pointing to the largest entry in the sub-tree headed
59526   ** by the child-page of the cell that was just deleted from an internal
59527   ** node. The cell from the leaf node needs to be moved to the internal
59528   ** node to replace the deleted cell.  */
59529   if( !pPage->leaf ){
59530     MemPage *pLeaf = pCur->apPage[pCur->iPage];
59531     int nCell;
59532     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
59533     unsigned char *pTmp;
59534 
59535     pCell = findCell(pLeaf, pLeaf->nCell-1);
59536     nCell = cellSizePtr(pLeaf, pCell);
59537     assert( MX_CELL_SIZE(pBt) >= nCell );
59538     pTmp = pBt->pTmpSpace;
59539     assert( pTmp!=0 );
59540     rc = sqlite3PagerWrite(pLeaf->pDbPage);
59541     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
59542     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
59543     if( rc ) return rc;
59544   }
59545 
59546   /* Balance the tree. If the entry deleted was located on a leaf page,
59547   ** then the cursor still points to that page. In this case the first
59548   ** call to balance() repairs the tree, and the if(...) condition is
59549   ** never true.
59550   **
59551   ** Otherwise, if the entry deleted was on an internal node page, then
59552   ** pCur is pointing to the leaf page from which a cell was removed to
59553   ** replace the cell deleted from the internal node. This is slightly
59554   ** tricky as the leaf node may be underfull, and the internal node may
59555   ** be either under or overfull. In this case run the balancing algorithm
59556   ** on the leaf node first. If the balance proceeds far enough up the
59557   ** tree that we can be sure that any problem in the internal node has
59558   ** been corrected, so be it. Otherwise, after balancing the leaf node,
59559   ** walk the cursor up the tree to the internal node and balance it as
59560   ** well.  */
59561   rc = balance(pCur);
59562   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
59563     while( pCur->iPage>iCellDepth ){
59564       releasePage(pCur->apPage[pCur->iPage--]);
59565     }
59566     rc = balance(pCur);
59567   }
59568 
59569   if( rc==SQLITE_OK ){
59570     moveToRoot(pCur);
59571   }
59572   return rc;
59573 }
59574 
59575 /*
59576 ** Create a new BTree table.  Write into *piTable the page
59577 ** number for the root page of the new table.
59578 **
59579 ** The type of type is determined by the flags parameter.  Only the
59580 ** following values of flags are currently in use.  Other values for
59581 ** flags might not work:
59582 **
59583 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
59584 **     BTREE_ZERODATA                  Used for SQL indices
59585 */
59586 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
59587   BtShared *pBt = p->pBt;
59588   MemPage *pRoot;
59589   Pgno pgnoRoot;
59590   int rc;
59591   int ptfFlags;          /* Page-type flage for the root page of new table */
59592 
59593   assert( sqlite3BtreeHoldsMutex(p) );
59594   assert( pBt->inTransaction==TRANS_WRITE );
59595   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
59596 
59597 #ifdef SQLITE_OMIT_AUTOVACUUM
59598   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
59599   if( rc ){
59600     return rc;
59601   }
59602 #else
59603   if( pBt->autoVacuum ){
59604     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
59605     MemPage *pPageMove; /* The page to move to. */
59606 
59607     /* Creating a new table may probably require moving an existing database
59608     ** to make room for the new tables root page. In case this page turns
59609     ** out to be an overflow page, delete all overflow page-map caches
59610     ** held by open cursors.
59611     */
59612     invalidateAllOverflowCache(pBt);
59613 
59614     /* Read the value of meta[3] from the database to determine where the
59615     ** root page of the new table should go. meta[3] is the largest root-page
59616     ** created so far, so the new root-page is (meta[3]+1).
59617     */
59618     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
59619     pgnoRoot++;
59620 
59621     /* The new root-page may not be allocated on a pointer-map page, or the
59622     ** PENDING_BYTE page.
59623     */
59624     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
59625         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
59626       pgnoRoot++;
59627     }
59628     assert( pgnoRoot>=3 );
59629 
59630     /* Allocate a page. The page that currently resides at pgnoRoot will
59631     ** be moved to the allocated page (unless the allocated page happens
59632     ** to reside at pgnoRoot).
59633     */
59634     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
59635     if( rc!=SQLITE_OK ){
59636       return rc;
59637     }
59638 
59639     if( pgnoMove!=pgnoRoot ){
59640       /* pgnoRoot is the page that will be used for the root-page of
59641       ** the new table (assuming an error did not occur). But we were
59642       ** allocated pgnoMove. If required (i.e. if it was not allocated
59643       ** by extending the file), the current page at position pgnoMove
59644       ** is already journaled.
59645       */
59646       u8 eType = 0;
59647       Pgno iPtrPage = 0;
59648 
59649       /* Save the positions of any open cursors. This is required in
59650       ** case they are holding a reference to an xFetch reference
59651       ** corresponding to page pgnoRoot.  */
59652       rc = saveAllCursors(pBt, 0, 0);
59653       releasePage(pPageMove);
59654       if( rc!=SQLITE_OK ){
59655         return rc;
59656       }
59657 
59658       /* Move the page currently at pgnoRoot to pgnoMove. */
59659       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
59660       if( rc!=SQLITE_OK ){
59661         return rc;
59662       }
59663       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
59664       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
59665         rc = SQLITE_CORRUPT_BKPT;
59666       }
59667       if( rc!=SQLITE_OK ){
59668         releasePage(pRoot);
59669         return rc;
59670       }
59671       assert( eType!=PTRMAP_ROOTPAGE );
59672       assert( eType!=PTRMAP_FREEPAGE );
59673       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
59674       releasePage(pRoot);
59675 
59676       /* Obtain the page at pgnoRoot */
59677       if( rc!=SQLITE_OK ){
59678         return rc;
59679       }
59680       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
59681       if( rc!=SQLITE_OK ){
59682         return rc;
59683       }
59684       rc = sqlite3PagerWrite(pRoot->pDbPage);
59685       if( rc!=SQLITE_OK ){
59686         releasePage(pRoot);
59687         return rc;
59688       }
59689     }else{
59690       pRoot = pPageMove;
59691     }
59692 
59693     /* Update the pointer-map and meta-data with the new root-page number. */
59694     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
59695     if( rc ){
59696       releasePage(pRoot);
59697       return rc;
59698     }
59699 
59700     /* When the new root page was allocated, page 1 was made writable in
59701     ** order either to increase the database filesize, or to decrement the
59702     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
59703     */
59704     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
59705     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
59706     if( NEVER(rc) ){
59707       releasePage(pRoot);
59708       return rc;
59709     }
59710 
59711   }else{
59712     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
59713     if( rc ) return rc;
59714   }
59715 #endif
59716   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
59717   if( createTabFlags & BTREE_INTKEY ){
59718     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
59719   }else{
59720     ptfFlags = PTF_ZERODATA | PTF_LEAF;
59721   }
59722   zeroPage(pRoot, ptfFlags);
59723   sqlite3PagerUnref(pRoot->pDbPage);
59724   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
59725   *piTable = (int)pgnoRoot;
59726   return SQLITE_OK;
59727 }
59728 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
59729   int rc;
59730   sqlite3BtreeEnter(p);
59731   rc = btreeCreateTable(p, piTable, flags);
59732   sqlite3BtreeLeave(p);
59733   return rc;
59734 }
59735 
59736 /*
59737 ** Erase the given database page and all its children.  Return
59738 ** the page to the freelist.
59739 */
59740 static int clearDatabasePage(
59741   BtShared *pBt,           /* The BTree that contains the table */
59742   Pgno pgno,               /* Page number to clear */
59743   int freePageFlag,        /* Deallocate page if true */
59744   int *pnChange            /* Add number of Cells freed to this counter */
59745 ){
59746   MemPage *pPage;
59747   int rc;
59748   unsigned char *pCell;
59749   int i;
59750   int hdr;
59751   u16 szCell;
59752 
59753   assert( sqlite3_mutex_held(pBt->mutex) );
59754   if( pgno>btreePagecount(pBt) ){
59755     return SQLITE_CORRUPT_BKPT;
59756   }
59757 
59758   rc = getAndInitPage(pBt, pgno, &pPage, 0);
59759   if( rc ) return rc;
59760   hdr = pPage->hdrOffset;
59761   for(i=0; i<pPage->nCell; i++){
59762     pCell = findCell(pPage, i);
59763     if( !pPage->leaf ){
59764       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
59765       if( rc ) goto cleardatabasepage_out;
59766     }
59767     rc = clearCell(pPage, pCell, &szCell);
59768     if( rc ) goto cleardatabasepage_out;
59769   }
59770   if( !pPage->leaf ){
59771     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
59772     if( rc ) goto cleardatabasepage_out;
59773   }else if( pnChange ){
59774     assert( pPage->intKey );
59775     *pnChange += pPage->nCell;
59776   }
59777   if( freePageFlag ){
59778     freePage(pPage, &rc);
59779   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
59780     zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
59781   }
59782 
59783 cleardatabasepage_out:
59784   releasePage(pPage);
59785   return rc;
59786 }
59787 
59788 /*
59789 ** Delete all information from a single table in the database.  iTable is
59790 ** the page number of the root of the table.  After this routine returns,
59791 ** the root page is empty, but still exists.
59792 **
59793 ** This routine will fail with SQLITE_LOCKED if there are any open
59794 ** read cursors on the table.  Open write cursors are moved to the
59795 ** root of the table.
59796 **
59797 ** If pnChange is not NULL, then table iTable must be an intkey table. The
59798 ** integer value pointed to by pnChange is incremented by the number of
59799 ** entries in the table.
59800 */
59801 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
59802   int rc;
59803   BtShared *pBt = p->pBt;
59804   sqlite3BtreeEnter(p);
59805   assert( p->inTrans==TRANS_WRITE );
59806 
59807   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
59808 
59809   if( SQLITE_OK==rc ){
59810     /* Invalidate all incrblob cursors open on table iTable (assuming iTable
59811     ** is the root of a table b-tree - if it is not, the following call is
59812     ** a no-op).  */
59813     invalidateIncrblobCursors(p, 0, 1);
59814     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
59815   }
59816   sqlite3BtreeLeave(p);
59817   return rc;
59818 }
59819 
59820 /*
59821 ** Delete all information from the single table that pCur is open on.
59822 **
59823 ** This routine only work for pCur on an ephemeral table.
59824 */
59825 SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
59826   return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
59827 }
59828 
59829 /*
59830 ** Erase all information in a table and add the root of the table to
59831 ** the freelist.  Except, the root of the principle table (the one on
59832 ** page 1) is never added to the freelist.
59833 **
59834 ** This routine will fail with SQLITE_LOCKED if there are any open
59835 ** cursors on the table.
59836 **
59837 ** If AUTOVACUUM is enabled and the page at iTable is not the last
59838 ** root page in the database file, then the last root page
59839 ** in the database file is moved into the slot formerly occupied by
59840 ** iTable and that last slot formerly occupied by the last root page
59841 ** is added to the freelist instead of iTable.  In this say, all
59842 ** root pages are kept at the beginning of the database file, which
59843 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
59844 ** page number that used to be the last root page in the file before
59845 ** the move.  If no page gets moved, *piMoved is set to 0.
59846 ** The last root page is recorded in meta[3] and the value of
59847 ** meta[3] is updated by this procedure.
59848 */
59849 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
59850   int rc;
59851   MemPage *pPage = 0;
59852   BtShared *pBt = p->pBt;
59853 
59854   assert( sqlite3BtreeHoldsMutex(p) );
59855   assert( p->inTrans==TRANS_WRITE );
59856 
59857   /* It is illegal to drop a table if any cursors are open on the
59858   ** database. This is because in auto-vacuum mode the backend may
59859   ** need to move another root-page to fill a gap left by the deleted
59860   ** root page. If an open cursor was using this page a problem would
59861   ** occur.
59862   **
59863   ** This error is caught long before control reaches this point.
59864   */
59865   if( NEVER(pBt->pCursor) ){
59866     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
59867     return SQLITE_LOCKED_SHAREDCACHE;
59868   }
59869 
59870   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
59871   if( rc ) return rc;
59872   rc = sqlite3BtreeClearTable(p, iTable, 0);
59873   if( rc ){
59874     releasePage(pPage);
59875     return rc;
59876   }
59877 
59878   *piMoved = 0;
59879 
59880   if( iTable>1 ){
59881 #ifdef SQLITE_OMIT_AUTOVACUUM
59882     freePage(pPage, &rc);
59883     releasePage(pPage);
59884 #else
59885     if( pBt->autoVacuum ){
59886       Pgno maxRootPgno;
59887       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
59888 
59889       if( iTable==maxRootPgno ){
59890         /* If the table being dropped is the table with the largest root-page
59891         ** number in the database, put the root page on the free list.
59892         */
59893         freePage(pPage, &rc);
59894         releasePage(pPage);
59895         if( rc!=SQLITE_OK ){
59896           return rc;
59897         }
59898       }else{
59899         /* The table being dropped does not have the largest root-page
59900         ** number in the database. So move the page that does into the
59901         ** gap left by the deleted root-page.
59902         */
59903         MemPage *pMove;
59904         releasePage(pPage);
59905         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
59906         if( rc!=SQLITE_OK ){
59907           return rc;
59908         }
59909         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
59910         releasePage(pMove);
59911         if( rc!=SQLITE_OK ){
59912           return rc;
59913         }
59914         pMove = 0;
59915         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
59916         freePage(pMove, &rc);
59917         releasePage(pMove);
59918         if( rc!=SQLITE_OK ){
59919           return rc;
59920         }
59921         *piMoved = maxRootPgno;
59922       }
59923 
59924       /* Set the new 'max-root-page' value in the database header. This
59925       ** is the old value less one, less one more if that happens to
59926       ** be a root-page number, less one again if that is the
59927       ** PENDING_BYTE_PAGE.
59928       */
59929       maxRootPgno--;
59930       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
59931              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
59932         maxRootPgno--;
59933       }
59934       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
59935 
59936       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
59937     }else{
59938       freePage(pPage, &rc);
59939       releasePage(pPage);
59940     }
59941 #endif
59942   }else{
59943     /* If sqlite3BtreeDropTable was called on page 1.
59944     ** This really never should happen except in a corrupt
59945     ** database.
59946     */
59947     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
59948     releasePage(pPage);
59949   }
59950   return rc;
59951 }
59952 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
59953   int rc;
59954   sqlite3BtreeEnter(p);
59955   rc = btreeDropTable(p, iTable, piMoved);
59956   sqlite3BtreeLeave(p);
59957   return rc;
59958 }
59959 
59960 
59961 /*
59962 ** This function may only be called if the b-tree connection already
59963 ** has a read or write transaction open on the database.
59964 **
59965 ** Read the meta-information out of a database file.  Meta[0]
59966 ** is the number of free pages currently in the database.  Meta[1]
59967 ** through meta[15] are available for use by higher layers.  Meta[0]
59968 ** is read-only, the others are read/write.
59969 **
59970 ** The schema layer numbers meta values differently.  At the schema
59971 ** layer (and the SetCookie and ReadCookie opcodes) the number of
59972 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
59973 */
59974 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
59975   BtShared *pBt = p->pBt;
59976 
59977   sqlite3BtreeEnter(p);
59978   assert( p->inTrans>TRANS_NONE );
59979   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
59980   assert( pBt->pPage1 );
59981   assert( idx>=0 && idx<=15 );
59982 
59983   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
59984 
59985   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
59986   ** database, mark the database as read-only.  */
59987 #ifdef SQLITE_OMIT_AUTOVACUUM
59988   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
59989     pBt->btsFlags |= BTS_READ_ONLY;
59990   }
59991 #endif
59992 
59993   sqlite3BtreeLeave(p);
59994 }
59995 
59996 /*
59997 ** Write meta-information back into the database.  Meta[0] is
59998 ** read-only and may not be written.
59999 */
60000 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
60001   BtShared *pBt = p->pBt;
60002   unsigned char *pP1;
60003   int rc;
60004   assert( idx>=1 && idx<=15 );
60005   sqlite3BtreeEnter(p);
60006   assert( p->inTrans==TRANS_WRITE );
60007   assert( pBt->pPage1!=0 );
60008   pP1 = pBt->pPage1->aData;
60009   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
60010   if( rc==SQLITE_OK ){
60011     put4byte(&pP1[36 + idx*4], iMeta);
60012 #ifndef SQLITE_OMIT_AUTOVACUUM
60013     if( idx==BTREE_INCR_VACUUM ){
60014       assert( pBt->autoVacuum || iMeta==0 );
60015       assert( iMeta==0 || iMeta==1 );
60016       pBt->incrVacuum = (u8)iMeta;
60017     }
60018 #endif
60019   }
60020   sqlite3BtreeLeave(p);
60021   return rc;
60022 }
60023 
60024 #ifndef SQLITE_OMIT_BTREECOUNT
60025 /*
60026 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
60027 ** number of entries in the b-tree and write the result to *pnEntry.
60028 **
60029 ** SQLITE_OK is returned if the operation is successfully executed.
60030 ** Otherwise, if an error is encountered (i.e. an IO error or database
60031 ** corruption) an SQLite error code is returned.
60032 */
60033 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
60034   i64 nEntry = 0;                      /* Value to return in *pnEntry */
60035   int rc;                              /* Return code */
60036 
60037   if( pCur->pgnoRoot==0 ){
60038     *pnEntry = 0;
60039     return SQLITE_OK;
60040   }
60041   rc = moveToRoot(pCur);
60042 
60043   /* Unless an error occurs, the following loop runs one iteration for each
60044   ** page in the B-Tree structure (not including overflow pages).
60045   */
60046   while( rc==SQLITE_OK ){
60047     int iIdx;                          /* Index of child node in parent */
60048     MemPage *pPage;                    /* Current page of the b-tree */
60049 
60050     /* If this is a leaf page or the tree is not an int-key tree, then
60051     ** this page contains countable entries. Increment the entry counter
60052     ** accordingly.
60053     */
60054     pPage = pCur->apPage[pCur->iPage];
60055     if( pPage->leaf || !pPage->intKey ){
60056       nEntry += pPage->nCell;
60057     }
60058 
60059     /* pPage is a leaf node. This loop navigates the cursor so that it
60060     ** points to the first interior cell that it points to the parent of
60061     ** the next page in the tree that has not yet been visited. The
60062     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
60063     ** of the page, or to the number of cells in the page if the next page
60064     ** to visit is the right-child of its parent.
60065     **
60066     ** If all pages in the tree have been visited, return SQLITE_OK to the
60067     ** caller.
60068     */
60069     if( pPage->leaf ){
60070       do {
60071         if( pCur->iPage==0 ){
60072           /* All pages of the b-tree have been visited. Return successfully. */
60073           *pnEntry = nEntry;
60074           return SQLITE_OK;
60075         }
60076         moveToParent(pCur);
60077       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
60078 
60079       pCur->aiIdx[pCur->iPage]++;
60080       pPage = pCur->apPage[pCur->iPage];
60081     }
60082 
60083     /* Descend to the child node of the cell that the cursor currently
60084     ** points at. This is the right-child if (iIdx==pPage->nCell).
60085     */
60086     iIdx = pCur->aiIdx[pCur->iPage];
60087     if( iIdx==pPage->nCell ){
60088       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
60089     }else{
60090       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
60091     }
60092   }
60093 
60094   /* An error has occurred. Return an error code. */
60095   return rc;
60096 }
60097 #endif
60098 
60099 /*
60100 ** Return the pager associated with a BTree.  This routine is used for
60101 ** testing and debugging only.
60102 */
60103 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
60104   return p->pBt->pPager;
60105 }
60106 
60107 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
60108 /*
60109 ** Append a message to the error message string.
60110 */
60111 static void checkAppendMsg(
60112   IntegrityCk *pCheck,
60113   const char *zFormat,
60114   ...
60115 ){
60116   va_list ap;
60117   char zBuf[200];
60118   if( !pCheck->mxErr ) return;
60119   pCheck->mxErr--;
60120   pCheck->nErr++;
60121   va_start(ap, zFormat);
60122   if( pCheck->errMsg.nChar ){
60123     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
60124   }
60125   if( pCheck->zPfx ){
60126     sqlite3_snprintf(sizeof(zBuf), zBuf, pCheck->zPfx, pCheck->v1, pCheck->v2);
60127     sqlite3StrAccumAppendAll(&pCheck->errMsg, zBuf);
60128   }
60129   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
60130   va_end(ap);
60131   if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
60132     pCheck->mallocFailed = 1;
60133   }
60134 }
60135 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
60136 
60137 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
60138 
60139 /*
60140 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
60141 ** corresponds to page iPg is already set.
60142 */
60143 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
60144   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
60145   return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
60146 }
60147 
60148 /*
60149 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
60150 */
60151 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
60152   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
60153   pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
60154 }
60155 
60156 
60157 /*
60158 ** Add 1 to the reference count for page iPage.  If this is the second
60159 ** reference to the page, add an error message to pCheck->zErrMsg.
60160 ** Return 1 if there are 2 or more references to the page and 0 if
60161 ** if this is the first reference to the page.
60162 **
60163 ** Also check that the page number is in bounds.
60164 */
60165 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
60166   if( iPage==0 ) return 1;
60167   if( iPage>pCheck->nPage ){
60168     checkAppendMsg(pCheck, "invalid page number %d", iPage);
60169     return 1;
60170   }
60171   if( getPageReferenced(pCheck, iPage) ){
60172     checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
60173     return 1;
60174   }
60175   setPageReferenced(pCheck, iPage);
60176   return 0;
60177 }
60178 
60179 #ifndef SQLITE_OMIT_AUTOVACUUM
60180 /*
60181 ** Check that the entry in the pointer-map for page iChild maps to
60182 ** page iParent, pointer type ptrType. If not, append an error message
60183 ** to pCheck.
60184 */
60185 static void checkPtrmap(
60186   IntegrityCk *pCheck,   /* Integrity check context */
60187   Pgno iChild,           /* Child page number */
60188   u8 eType,              /* Expected pointer map type */
60189   Pgno iParent           /* Expected pointer map parent page number */
60190 ){
60191   int rc;
60192   u8 ePtrmapType;
60193   Pgno iPtrmapParent;
60194 
60195   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
60196   if( rc!=SQLITE_OK ){
60197     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
60198     checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
60199     return;
60200   }
60201 
60202   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
60203     checkAppendMsg(pCheck,
60204       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
60205       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
60206   }
60207 }
60208 #endif
60209 
60210 /*
60211 ** Check the integrity of the freelist or of an overflow page list.
60212 ** Verify that the number of pages on the list is N.
60213 */
60214 static void checkList(
60215   IntegrityCk *pCheck,  /* Integrity checking context */
60216   int isFreeList,       /* True for a freelist.  False for overflow page list */
60217   int iPage,            /* Page number for first page in the list */
60218   int N                 /* Expected number of pages in the list */
60219 ){
60220   int i;
60221   int expected = N;
60222   int iFirst = iPage;
60223   while( N-- > 0 && pCheck->mxErr ){
60224     DbPage *pOvflPage;
60225     unsigned char *pOvflData;
60226     if( iPage<1 ){
60227       checkAppendMsg(pCheck,
60228          "%d of %d pages missing from overflow list starting at %d",
60229           N+1, expected, iFirst);
60230       break;
60231     }
60232     if( checkRef(pCheck, iPage) ) break;
60233     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
60234       checkAppendMsg(pCheck, "failed to get page %d", iPage);
60235       break;
60236     }
60237     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
60238     if( isFreeList ){
60239       int n = get4byte(&pOvflData[4]);
60240 #ifndef SQLITE_OMIT_AUTOVACUUM
60241       if( pCheck->pBt->autoVacuum ){
60242         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
60243       }
60244 #endif
60245       if( n>(int)pCheck->pBt->usableSize/4-2 ){
60246         checkAppendMsg(pCheck,
60247            "freelist leaf count too big on page %d", iPage);
60248         N--;
60249       }else{
60250         for(i=0; i<n; i++){
60251           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
60252 #ifndef SQLITE_OMIT_AUTOVACUUM
60253           if( pCheck->pBt->autoVacuum ){
60254             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
60255           }
60256 #endif
60257           checkRef(pCheck, iFreePage);
60258         }
60259         N -= n;
60260       }
60261     }
60262 #ifndef SQLITE_OMIT_AUTOVACUUM
60263     else{
60264       /* If this database supports auto-vacuum and iPage is not the last
60265       ** page in this overflow list, check that the pointer-map entry for
60266       ** the following page matches iPage.
60267       */
60268       if( pCheck->pBt->autoVacuum && N>0 ){
60269         i = get4byte(pOvflData);
60270         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
60271       }
60272     }
60273 #endif
60274     iPage = get4byte(pOvflData);
60275     sqlite3PagerUnref(pOvflPage);
60276   }
60277 }
60278 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
60279 
60280 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
60281 /*
60282 ** Do various sanity checks on a single page of a tree.  Return
60283 ** the tree depth.  Root pages return 0.  Parents of root pages
60284 ** return 1, and so forth.
60285 **
60286 ** These checks are done:
60287 **
60288 **      1.  Make sure that cells and freeblocks do not overlap
60289 **          but combine to completely cover the page.
60290 **  NO  2.  Make sure cell keys are in order.
60291 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
60292 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
60293 **      5.  Check the integrity of overflow pages.
60294 **      6.  Recursively call checkTreePage on all children.
60295 **      7.  Verify that the depth of all children is the same.
60296 **      8.  Make sure this page is at least 33% full or else it is
60297 **          the root of the tree.
60298 */
60299 static int checkTreePage(
60300   IntegrityCk *pCheck,  /* Context for the sanity check */
60301   int iPage,            /* Page number of the page to check */
60302   i64 *pnParentMinKey,
60303   i64 *pnParentMaxKey
60304 ){
60305   MemPage *pPage;
60306   int i, rc, depth, d2, pgno, cnt;
60307   int hdr, cellStart;
60308   int nCell;
60309   u8 *data;
60310   BtShared *pBt;
60311   int usableSize;
60312   char *hit = 0;
60313   i64 nMinKey = 0;
60314   i64 nMaxKey = 0;
60315   const char *saved_zPfx = pCheck->zPfx;
60316   int saved_v1 = pCheck->v1;
60317   int saved_v2 = pCheck->v2;
60318 
60319   /* Check that the page exists
60320   */
60321   pBt = pCheck->pBt;
60322   usableSize = pBt->usableSize;
60323   if( iPage==0 ) return 0;
60324   if( checkRef(pCheck, iPage) ) return 0;
60325   pCheck->zPfx = "Page %d: ";
60326   pCheck->v1 = iPage;
60327   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
60328     checkAppendMsg(pCheck,
60329        "unable to get the page. error code=%d", rc);
60330     depth = -1;
60331     goto end_of_check;
60332   }
60333 
60334   /* Clear MemPage.isInit to make sure the corruption detection code in
60335   ** btreeInitPage() is executed.  */
60336   pPage->isInit = 0;
60337   if( (rc = btreeInitPage(pPage))!=0 ){
60338     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
60339     checkAppendMsg(pCheck,
60340                    "btreeInitPage() returns error code %d", rc);
60341     releasePage(pPage);
60342     depth = -1;
60343     goto end_of_check;
60344   }
60345 
60346   /* Check out all the cells.
60347   */
60348   depth = 0;
60349   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
60350     u8 *pCell;
60351     u32 sz;
60352     CellInfo info;
60353 
60354     /* Check payload overflow pages
60355     */
60356     pCheck->zPfx = "On tree page %d cell %d: ";
60357     pCheck->v1 = iPage;
60358     pCheck->v2 = i;
60359     pCell = findCell(pPage,i);
60360     btreeParseCellPtr(pPage, pCell, &info);
60361     sz = info.nPayload;
60362     /* For intKey pages, check that the keys are in order.
60363     */
60364     if( pPage->intKey ){
60365       if( i==0 ){
60366         nMinKey = nMaxKey = info.nKey;
60367       }else if( info.nKey <= nMaxKey ){
60368         checkAppendMsg(pCheck,
60369            "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
60370       }
60371       nMaxKey = info.nKey;
60372     }
60373     if( (sz>info.nLocal)
60374      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
60375     ){
60376       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
60377       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
60378 #ifndef SQLITE_OMIT_AUTOVACUUM
60379       if( pBt->autoVacuum ){
60380         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
60381       }
60382 #endif
60383       checkList(pCheck, 0, pgnoOvfl, nPage);
60384     }
60385 
60386     /* Check sanity of left child page.
60387     */
60388     if( !pPage->leaf ){
60389       pgno = get4byte(pCell);
60390 #ifndef SQLITE_OMIT_AUTOVACUUM
60391       if( pBt->autoVacuum ){
60392         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
60393       }
60394 #endif
60395       d2 = checkTreePage(pCheck, pgno, &nMinKey, i==0?NULL:&nMaxKey);
60396       if( i>0 && d2!=depth ){
60397         checkAppendMsg(pCheck, "Child page depth differs");
60398       }
60399       depth = d2;
60400     }
60401   }
60402 
60403   if( !pPage->leaf ){
60404     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
60405     pCheck->zPfx = "On page %d at right child: ";
60406     pCheck->v1 = iPage;
60407 #ifndef SQLITE_OMIT_AUTOVACUUM
60408     if( pBt->autoVacuum ){
60409       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
60410     }
60411 #endif
60412     checkTreePage(pCheck, pgno, NULL, !pPage->nCell?NULL:&nMaxKey);
60413   }
60414 
60415   /* For intKey leaf pages, check that the min/max keys are in order
60416   ** with any left/parent/right pages.
60417   */
60418   pCheck->zPfx = "Page %d: ";
60419   pCheck->v1 = iPage;
60420   if( pPage->leaf && pPage->intKey ){
60421     /* if we are a left child page */
60422     if( pnParentMinKey ){
60423       /* if we are the left most child page */
60424       if( !pnParentMaxKey ){
60425         if( nMaxKey > *pnParentMinKey ){
60426           checkAppendMsg(pCheck,
60427               "Rowid %lld out of order (max larger than parent min of %lld)",
60428               nMaxKey, *pnParentMinKey);
60429         }
60430       }else{
60431         if( nMinKey <= *pnParentMinKey ){
60432           checkAppendMsg(pCheck,
60433               "Rowid %lld out of order (min less than parent min of %lld)",
60434               nMinKey, *pnParentMinKey);
60435         }
60436         if( nMaxKey > *pnParentMaxKey ){
60437           checkAppendMsg(pCheck,
60438               "Rowid %lld out of order (max larger than parent max of %lld)",
60439               nMaxKey, *pnParentMaxKey);
60440         }
60441         *pnParentMinKey = nMaxKey;
60442       }
60443     /* else if we're a right child page */
60444     } else if( pnParentMaxKey ){
60445       if( nMinKey <= *pnParentMaxKey ){
60446         checkAppendMsg(pCheck,
60447             "Rowid %lld out of order (min less than parent max of %lld)",
60448             nMinKey, *pnParentMaxKey);
60449       }
60450     }
60451   }
60452 
60453   /* Check for complete coverage of the page
60454   */
60455   data = pPage->aData;
60456   hdr = pPage->hdrOffset;
60457   hit = sqlite3PageMalloc( pBt->pageSize );
60458   pCheck->zPfx = 0;
60459   if( hit==0 ){
60460     pCheck->mallocFailed = 1;
60461   }else{
60462     int contentOffset = get2byteNotZero(&data[hdr+5]);
60463     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
60464     memset(hit+contentOffset, 0, usableSize-contentOffset);
60465     memset(hit, 1, contentOffset);
60466     nCell = get2byte(&data[hdr+3]);
60467     cellStart = hdr + 12 - 4*pPage->leaf;
60468     for(i=0; i<nCell; i++){
60469       int pc = get2byte(&data[cellStart+i*2]);
60470       u32 size = 65536;
60471       int j;
60472       if( pc<=usableSize-4 ){
60473         size = cellSizePtr(pPage, &data[pc]);
60474       }
60475       if( (int)(pc+size-1)>=usableSize ){
60476         pCheck->zPfx = 0;
60477         checkAppendMsg(pCheck,
60478             "Corruption detected in cell %d on page %d",i,iPage);
60479       }else{
60480         for(j=pc+size-1; j>=pc; j--) hit[j]++;
60481       }
60482     }
60483     i = get2byte(&data[hdr+1]);
60484     while( i>0 ){
60485       int size, j;
60486       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
60487       size = get2byte(&data[i+2]);
60488       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
60489       for(j=i+size-1; j>=i; j--) hit[j]++;
60490       j = get2byte(&data[i]);
60491       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
60492       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
60493       i = j;
60494     }
60495     for(i=cnt=0; i<usableSize; i++){
60496       if( hit[i]==0 ){
60497         cnt++;
60498       }else if( hit[i]>1 ){
60499         checkAppendMsg(pCheck,
60500           "Multiple uses for byte %d of page %d", i, iPage);
60501         break;
60502       }
60503     }
60504     if( cnt!=data[hdr+7] ){
60505       checkAppendMsg(pCheck,
60506           "Fragmentation of %d bytes reported as %d on page %d",
60507           cnt, data[hdr+7], iPage);
60508     }
60509   }
60510   sqlite3PageFree(hit);
60511   releasePage(pPage);
60512 
60513 end_of_check:
60514   pCheck->zPfx = saved_zPfx;
60515   pCheck->v1 = saved_v1;
60516   pCheck->v2 = saved_v2;
60517   return depth+1;
60518 }
60519 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
60520 
60521 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
60522 /*
60523 ** This routine does a complete check of the given BTree file.  aRoot[] is
60524 ** an array of pages numbers were each page number is the root page of
60525 ** a table.  nRoot is the number of entries in aRoot.
60526 **
60527 ** A read-only or read-write transaction must be opened before calling
60528 ** this function.
60529 **
60530 ** Write the number of error seen in *pnErr.  Except for some memory
60531 ** allocation errors,  an error message held in memory obtained from
60532 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
60533 ** returned.  If a memory allocation error occurs, NULL is returned.
60534 */
60535 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
60536   Btree *p,     /* The btree to be checked */
60537   int *aRoot,   /* An array of root pages numbers for individual trees */
60538   int nRoot,    /* Number of entries in aRoot[] */
60539   int mxErr,    /* Stop reporting errors after this many */
60540   int *pnErr    /* Write number of errors seen to this variable */
60541 ){
60542   Pgno i;
60543   int nRef;
60544   IntegrityCk sCheck;
60545   BtShared *pBt = p->pBt;
60546   char zErr[100];
60547 
60548   sqlite3BtreeEnter(p);
60549   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
60550   nRef = sqlite3PagerRefcount(pBt->pPager);
60551   sCheck.pBt = pBt;
60552   sCheck.pPager = pBt->pPager;
60553   sCheck.nPage = btreePagecount(sCheck.pBt);
60554   sCheck.mxErr = mxErr;
60555   sCheck.nErr = 0;
60556   sCheck.mallocFailed = 0;
60557   sCheck.zPfx = 0;
60558   sCheck.v1 = 0;
60559   sCheck.v2 = 0;
60560   *pnErr = 0;
60561   if( sCheck.nPage==0 ){
60562     sqlite3BtreeLeave(p);
60563     return 0;
60564   }
60565 
60566   sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
60567   if( !sCheck.aPgRef ){
60568     *pnErr = 1;
60569     sqlite3BtreeLeave(p);
60570     return 0;
60571   }
60572   i = PENDING_BYTE_PAGE(pBt);
60573   if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
60574   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
60575   sCheck.errMsg.useMalloc = 2;
60576 
60577   /* Check the integrity of the freelist
60578   */
60579   sCheck.zPfx = "Main freelist: ";
60580   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
60581             get4byte(&pBt->pPage1->aData[36]));
60582   sCheck.zPfx = 0;
60583 
60584   /* Check all the tables.
60585   */
60586   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
60587     if( aRoot[i]==0 ) continue;
60588 #ifndef SQLITE_OMIT_AUTOVACUUM
60589     if( pBt->autoVacuum && aRoot[i]>1 ){
60590       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
60591     }
60592 #endif
60593     sCheck.zPfx = "List of tree roots: ";
60594     checkTreePage(&sCheck, aRoot[i], NULL, NULL);
60595     sCheck.zPfx = 0;
60596   }
60597 
60598   /* Make sure every page in the file is referenced
60599   */
60600   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
60601 #ifdef SQLITE_OMIT_AUTOVACUUM
60602     if( getPageReferenced(&sCheck, i)==0 ){
60603       checkAppendMsg(&sCheck, "Page %d is never used", i);
60604     }
60605 #else
60606     /* If the database supports auto-vacuum, make sure no tables contain
60607     ** references to pointer-map pages.
60608     */
60609     if( getPageReferenced(&sCheck, i)==0 &&
60610        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
60611       checkAppendMsg(&sCheck, "Page %d is never used", i);
60612     }
60613     if( getPageReferenced(&sCheck, i)!=0 &&
60614        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
60615       checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
60616     }
60617 #endif
60618   }
60619 
60620   /* Make sure this analysis did not leave any unref() pages.
60621   ** This is an internal consistency check; an integrity check
60622   ** of the integrity check.
60623   */
60624   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
60625     checkAppendMsg(&sCheck,
60626       "Outstanding page count goes from %d to %d during this analysis",
60627       nRef, sqlite3PagerRefcount(pBt->pPager)
60628     );
60629   }
60630 
60631   /* Clean  up and report errors.
60632   */
60633   sqlite3BtreeLeave(p);
60634   sqlite3_free(sCheck.aPgRef);
60635   if( sCheck.mallocFailed ){
60636     sqlite3StrAccumReset(&sCheck.errMsg);
60637     *pnErr = sCheck.nErr+1;
60638     return 0;
60639   }
60640   *pnErr = sCheck.nErr;
60641   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
60642   return sqlite3StrAccumFinish(&sCheck.errMsg);
60643 }
60644 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
60645 
60646 /*
60647 ** Return the full pathname of the underlying database file.  Return
60648 ** an empty string if the database is in-memory or a TEMP database.
60649 **
60650 ** The pager filename is invariant as long as the pager is
60651 ** open so it is safe to access without the BtShared mutex.
60652 */
60653 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
60654   assert( p->pBt->pPager!=0 );
60655   return sqlite3PagerFilename(p->pBt->pPager, 1);
60656 }
60657 
60658 /*
60659 ** Return the pathname of the journal file for this database. The return
60660 ** value of this routine is the same regardless of whether the journal file
60661 ** has been created or not.
60662 **
60663 ** The pager journal filename is invariant as long as the pager is
60664 ** open so it is safe to access without the BtShared mutex.
60665 */
60666 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
60667   assert( p->pBt->pPager!=0 );
60668   return sqlite3PagerJournalname(p->pBt->pPager);
60669 }
60670 
60671 /*
60672 ** Return non-zero if a transaction is active.
60673 */
60674 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
60675   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
60676   return (p && (p->inTrans==TRANS_WRITE));
60677 }
60678 
60679 #ifndef SQLITE_OMIT_WAL
60680 /*
60681 ** Run a checkpoint on the Btree passed as the first argument.
60682 **
60683 ** Return SQLITE_LOCKED if this or any other connection has an open
60684 ** transaction on the shared-cache the argument Btree is connected to.
60685 **
60686 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
60687 */
60688 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
60689   int rc = SQLITE_OK;
60690   if( p ){
60691     BtShared *pBt = p->pBt;
60692     sqlite3BtreeEnter(p);
60693     if( pBt->inTransaction!=TRANS_NONE ){
60694       rc = SQLITE_LOCKED;
60695     }else{
60696       rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
60697     }
60698     sqlite3BtreeLeave(p);
60699   }
60700   return rc;
60701 }
60702 #endif
60703 
60704 /*
60705 ** Return non-zero if a read (or write) transaction is active.
60706 */
60707 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
60708   assert( p );
60709   assert( sqlite3_mutex_held(p->db->mutex) );
60710   return p->inTrans!=TRANS_NONE;
60711 }
60712 
60713 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
60714   assert( p );
60715   assert( sqlite3_mutex_held(p->db->mutex) );
60716   return p->nBackup!=0;
60717 }
60718 
60719 /*
60720 ** This function returns a pointer to a blob of memory associated with
60721 ** a single shared-btree. The memory is used by client code for its own
60722 ** purposes (for example, to store a high-level schema associated with
60723 ** the shared-btree). The btree layer manages reference counting issues.
60724 **
60725 ** The first time this is called on a shared-btree, nBytes bytes of memory
60726 ** are allocated, zeroed, and returned to the caller. For each subsequent
60727 ** call the nBytes parameter is ignored and a pointer to the same blob
60728 ** of memory returned.
60729 **
60730 ** If the nBytes parameter is 0 and the blob of memory has not yet been
60731 ** allocated, a null pointer is returned. If the blob has already been
60732 ** allocated, it is returned as normal.
60733 **
60734 ** Just before the shared-btree is closed, the function passed as the
60735 ** xFree argument when the memory allocation was made is invoked on the
60736 ** blob of allocated memory. The xFree function should not call sqlite3_free()
60737 ** on the memory, the btree layer does that.
60738 */
60739 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
60740   BtShared *pBt = p->pBt;
60741   sqlite3BtreeEnter(p);
60742   if( !pBt->pSchema && nBytes ){
60743     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
60744     pBt->xFreeSchema = xFree;
60745   }
60746   sqlite3BtreeLeave(p);
60747   return pBt->pSchema;
60748 }
60749 
60750 /*
60751 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
60752 ** btree as the argument handle holds an exclusive lock on the
60753 ** sqlite_master table. Otherwise SQLITE_OK.
60754 */
60755 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
60756   int rc;
60757   assert( sqlite3_mutex_held(p->db->mutex) );
60758   sqlite3BtreeEnter(p);
60759   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
60760   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
60761   sqlite3BtreeLeave(p);
60762   return rc;
60763 }
60764 
60765 
60766 #ifndef SQLITE_OMIT_SHARED_CACHE
60767 /*
60768 ** Obtain a lock on the table whose root page is iTab.  The
60769 ** lock is a write lock if isWritelock is true or a read lock
60770 ** if it is false.
60771 */
60772 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
60773   int rc = SQLITE_OK;
60774   assert( p->inTrans!=TRANS_NONE );
60775   if( p->sharable ){
60776     u8 lockType = READ_LOCK + isWriteLock;
60777     assert( READ_LOCK+1==WRITE_LOCK );
60778     assert( isWriteLock==0 || isWriteLock==1 );
60779 
60780     sqlite3BtreeEnter(p);
60781     rc = querySharedCacheTableLock(p, iTab, lockType);
60782     if( rc==SQLITE_OK ){
60783       rc = setSharedCacheTableLock(p, iTab, lockType);
60784     }
60785     sqlite3BtreeLeave(p);
60786   }
60787   return rc;
60788 }
60789 #endif
60790 
60791 #ifndef SQLITE_OMIT_INCRBLOB
60792 /*
60793 ** Argument pCsr must be a cursor opened for writing on an
60794 ** INTKEY table currently pointing at a valid table entry.
60795 ** This function modifies the data stored as part of that entry.
60796 **
60797 ** Only the data content may only be modified, it is not possible to
60798 ** change the length of the data stored. If this function is called with
60799 ** parameters that attempt to write past the end of the existing data,
60800 ** no modifications are made and SQLITE_CORRUPT is returned.
60801 */
60802 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
60803   int rc;
60804   assert( cursorHoldsMutex(pCsr) );
60805   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
60806   assert( pCsr->curFlags & BTCF_Incrblob );
60807 
60808   rc = restoreCursorPosition(pCsr);
60809   if( rc!=SQLITE_OK ){
60810     return rc;
60811   }
60812   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
60813   if( pCsr->eState!=CURSOR_VALID ){
60814     return SQLITE_ABORT;
60815   }
60816 
60817   /* Save the positions of all other cursors open on this table. This is
60818   ** required in case any of them are holding references to an xFetch
60819   ** version of the b-tree page modified by the accessPayload call below.
60820   **
60821   ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
60822   ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
60823   ** saveAllCursors can only return SQLITE_OK.
60824   */
60825   VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
60826   assert( rc==SQLITE_OK );
60827 
60828   /* Check some assumptions:
60829   **   (a) the cursor is open for writing,
60830   **   (b) there is a read/write transaction open,
60831   **   (c) the connection holds a write-lock on the table (if required),
60832   **   (d) there are no conflicting read-locks, and
60833   **   (e) the cursor points at a valid row of an intKey table.
60834   */
60835   if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
60836     return SQLITE_READONLY;
60837   }
60838   assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
60839               && pCsr->pBt->inTransaction==TRANS_WRITE );
60840   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
60841   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
60842   assert( pCsr->apPage[pCsr->iPage]->intKey );
60843 
60844   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
60845 }
60846 
60847 /*
60848 ** Mark this cursor as an incremental blob cursor.
60849 */
60850 SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
60851   pCur->curFlags |= BTCF_Incrblob;
60852 }
60853 #endif
60854 
60855 /*
60856 ** Set both the "read version" (single byte at byte offset 18) and
60857 ** "write version" (single byte at byte offset 19) fields in the database
60858 ** header to iVersion.
60859 */
60860 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
60861   BtShared *pBt = pBtree->pBt;
60862   int rc;                         /* Return code */
60863 
60864   assert( iVersion==1 || iVersion==2 );
60865 
60866   /* If setting the version fields to 1, do not automatically open the
60867   ** WAL connection, even if the version fields are currently set to 2.
60868   */
60869   pBt->btsFlags &= ~BTS_NO_WAL;
60870   if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
60871 
60872   rc = sqlite3BtreeBeginTrans(pBtree, 0);
60873   if( rc==SQLITE_OK ){
60874     u8 *aData = pBt->pPage1->aData;
60875     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
60876       rc = sqlite3BtreeBeginTrans(pBtree, 2);
60877       if( rc==SQLITE_OK ){
60878         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
60879         if( rc==SQLITE_OK ){
60880           aData[18] = (u8)iVersion;
60881           aData[19] = (u8)iVersion;
60882         }
60883       }
60884     }
60885   }
60886 
60887   pBt->btsFlags &= ~BTS_NO_WAL;
60888   return rc;
60889 }
60890 
60891 /*
60892 ** set the mask of hint flags for cursor pCsr. Currently the only valid
60893 ** values are 0 and BTREE_BULKLOAD.
60894 */
60895 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
60896   assert( mask==BTREE_BULKLOAD || mask==0 );
60897   pCsr->hints = mask;
60898 }
60899 
60900 /*
60901 ** Return true if the given Btree is read-only.
60902 */
60903 SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
60904   return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
60905 }
60906 
60907 /************** End of btree.c ***********************************************/
60908 /************** Begin file backup.c ******************************************/
60909 /*
60910 ** 2009 January 28
60911 **
60912 ** The author disclaims copyright to this source code.  In place of
60913 ** a legal notice, here is a blessing:
60914 **
60915 **    May you do good and not evil.
60916 **    May you find forgiveness for yourself and forgive others.
60917 **    May you share freely, never taking more than you give.
60918 **
60919 *************************************************************************
60920 ** This file contains the implementation of the sqlite3_backup_XXX()
60921 ** API functions and the related features.
60922 */
60923 
60924 /*
60925 ** Structure allocated for each backup operation.
60926 */
60927 struct sqlite3_backup {
60928   sqlite3* pDestDb;        /* Destination database handle */
60929   Btree *pDest;            /* Destination b-tree file */
60930   u32 iDestSchema;         /* Original schema cookie in destination */
60931   int bDestLocked;         /* True once a write-transaction is open on pDest */
60932 
60933   Pgno iNext;              /* Page number of the next source page to copy */
60934   sqlite3* pSrcDb;         /* Source database handle */
60935   Btree *pSrc;             /* Source b-tree file */
60936 
60937   int rc;                  /* Backup process error code */
60938 
60939   /* These two variables are set by every call to backup_step(). They are
60940   ** read by calls to backup_remaining() and backup_pagecount().
60941   */
60942   Pgno nRemaining;         /* Number of pages left to copy */
60943   Pgno nPagecount;         /* Total number of pages to copy */
60944 
60945   int isAttached;          /* True once backup has been registered with pager */
60946   sqlite3_backup *pNext;   /* Next backup associated with source pager */
60947 };
60948 
60949 /*
60950 ** THREAD SAFETY NOTES:
60951 **
60952 **   Once it has been created using backup_init(), a single sqlite3_backup
60953 **   structure may be accessed via two groups of thread-safe entry points:
60954 **
60955 **     * Via the sqlite3_backup_XXX() API function backup_step() and
60956 **       backup_finish(). Both these functions obtain the source database
60957 **       handle mutex and the mutex associated with the source BtShared
60958 **       structure, in that order.
60959 **
60960 **     * Via the BackupUpdate() and BackupRestart() functions, which are
60961 **       invoked by the pager layer to report various state changes in
60962 **       the page cache associated with the source database. The mutex
60963 **       associated with the source database BtShared structure will always
60964 **       be held when either of these functions are invoked.
60965 **
60966 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
60967 **   backup_pagecount() are not thread-safe functions. If they are called
60968 **   while some other thread is calling backup_step() or backup_finish(),
60969 **   the values returned may be invalid. There is no way for a call to
60970 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
60971 **   or backup_pagecount().
60972 **
60973 **   Depending on the SQLite configuration, the database handles and/or
60974 **   the Btree objects may have their own mutexes that require locking.
60975 **   Non-sharable Btrees (in-memory databases for example), do not have
60976 **   associated mutexes.
60977 */
60978 
60979 /*
60980 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
60981 ** in connection handle pDb. If such a database cannot be found, return
60982 ** a NULL pointer and write an error message to pErrorDb.
60983 **
60984 ** If the "temp" database is requested, it may need to be opened by this
60985 ** function. If an error occurs while doing so, return 0 and write an
60986 ** error message to pErrorDb.
60987 */
60988 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
60989   int i = sqlite3FindDbName(pDb, zDb);
60990 
60991   if( i==1 ){
60992     Parse *pParse;
60993     int rc = 0;
60994     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
60995     if( pParse==0 ){
60996       sqlite3ErrorWithMsg(pErrorDb, SQLITE_NOMEM, "out of memory");
60997       rc = SQLITE_NOMEM;
60998     }else{
60999       pParse->db = pDb;
61000       if( sqlite3OpenTempDatabase(pParse) ){
61001         sqlite3ErrorWithMsg(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
61002         rc = SQLITE_ERROR;
61003       }
61004       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
61005       sqlite3ParserReset(pParse);
61006       sqlite3StackFree(pErrorDb, pParse);
61007     }
61008     if( rc ){
61009       return 0;
61010     }
61011   }
61012 
61013   if( i<0 ){
61014     sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
61015     return 0;
61016   }
61017 
61018   return pDb->aDb[i].pBt;
61019 }
61020 
61021 /*
61022 ** Attempt to set the page size of the destination to match the page size
61023 ** of the source.
61024 */
61025 static int setDestPgsz(sqlite3_backup *p){
61026   int rc;
61027   rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
61028   return rc;
61029 }
61030 
61031 /*
61032 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
61033 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
61034 ** a pointer to the new sqlite3_backup object.
61035 **
61036 ** If an error occurs, NULL is returned and an error code and error message
61037 ** stored in database handle pDestDb.
61038 */
61039 SQLITE_API sqlite3_backup *sqlite3_backup_init(
61040   sqlite3* pDestDb,                     /* Database to write to */
61041   const char *zDestDb,                  /* Name of database within pDestDb */
61042   sqlite3* pSrcDb,                      /* Database connection to read from */
61043   const char *zSrcDb                    /* Name of database within pSrcDb */
61044 ){
61045   sqlite3_backup *p;                    /* Value to return */
61046 
61047   /* Lock the source database handle. The destination database
61048   ** handle is not locked in this routine, but it is locked in
61049   ** sqlite3_backup_step(). The user is required to ensure that no
61050   ** other thread accesses the destination handle for the duration
61051   ** of the backup operation.  Any attempt to use the destination
61052   ** database connection while a backup is in progress may cause
61053   ** a malfunction or a deadlock.
61054   */
61055   sqlite3_mutex_enter(pSrcDb->mutex);
61056   sqlite3_mutex_enter(pDestDb->mutex);
61057 
61058   if( pSrcDb==pDestDb ){
61059     sqlite3ErrorWithMsg(
61060         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
61061     );
61062     p = 0;
61063   }else {
61064     /* Allocate space for a new sqlite3_backup object...
61065     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
61066     ** call to sqlite3_backup_init() and is destroyed by a call to
61067     ** sqlite3_backup_finish(). */
61068     p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
61069     if( !p ){
61070       sqlite3Error(pDestDb, SQLITE_NOMEM);
61071     }
61072   }
61073 
61074   /* If the allocation succeeded, populate the new object. */
61075   if( p ){
61076     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
61077     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
61078     p->pDestDb = pDestDb;
61079     p->pSrcDb = pSrcDb;
61080     p->iNext = 1;
61081     p->isAttached = 0;
61082 
61083     if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
61084       /* One (or both) of the named databases did not exist or an OOM
61085       ** error was hit.  The error has already been written into the
61086       ** pDestDb handle.  All that is left to do here is free the
61087       ** sqlite3_backup structure.
61088       */
61089       sqlite3_free(p);
61090       p = 0;
61091     }
61092   }
61093   if( p ){
61094     p->pSrc->nBackup++;
61095   }
61096 
61097   sqlite3_mutex_leave(pDestDb->mutex);
61098   sqlite3_mutex_leave(pSrcDb->mutex);
61099   return p;
61100 }
61101 
61102 /*
61103 ** Argument rc is an SQLite error code. Return true if this error is
61104 ** considered fatal if encountered during a backup operation. All errors
61105 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
61106 */
61107 static int isFatalError(int rc){
61108   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
61109 }
61110 
61111 /*
61112 ** Parameter zSrcData points to a buffer containing the data for
61113 ** page iSrcPg from the source database. Copy this data into the
61114 ** destination database.
61115 */
61116 static int backupOnePage(
61117   sqlite3_backup *p,              /* Backup handle */
61118   Pgno iSrcPg,                    /* Source database page to backup */
61119   const u8 *zSrcData,             /* Source database page data */
61120   int bUpdate                     /* True for an update, false otherwise */
61121 ){
61122   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
61123   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
61124   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
61125   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
61126   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
61127 #ifdef SQLITE_HAS_CODEC
61128   /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
61129   ** guaranteed that the shared-mutex is held by this thread, handle
61130   ** p->pSrc may not actually be the owner.  */
61131   int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
61132   int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
61133 #endif
61134   int rc = SQLITE_OK;
61135   i64 iOff;
61136 
61137   assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
61138   assert( p->bDestLocked );
61139   assert( !isFatalError(p->rc) );
61140   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
61141   assert( zSrcData );
61142 
61143   /* Catch the case where the destination is an in-memory database and the
61144   ** page sizes of the source and destination differ.
61145   */
61146   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
61147     rc = SQLITE_READONLY;
61148   }
61149 
61150 #ifdef SQLITE_HAS_CODEC
61151   /* Backup is not possible if the page size of the destination is changing
61152   ** and a codec is in use.
61153   */
61154   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
61155     rc = SQLITE_READONLY;
61156   }
61157 
61158   /* Backup is not possible if the number of bytes of reserve space differ
61159   ** between source and destination.  If there is a difference, try to
61160   ** fix the destination to agree with the source.  If that is not possible,
61161   ** then the backup cannot proceed.
61162   */
61163   if( nSrcReserve!=nDestReserve ){
61164     u32 newPgsz = nSrcPgsz;
61165     rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
61166     if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
61167   }
61168 #endif
61169 
61170   /* This loop runs once for each destination page spanned by the source
61171   ** page. For each iteration, variable iOff is set to the byte offset
61172   ** of the destination page.
61173   */
61174   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
61175     DbPage *pDestPg = 0;
61176     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
61177     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
61178     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
61179      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
61180     ){
61181       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
61182       u8 *zDestData = sqlite3PagerGetData(pDestPg);
61183       u8 *zOut = &zDestData[iOff%nDestPgsz];
61184 
61185       /* Copy the data from the source page into the destination page.
61186       ** Then clear the Btree layer MemPage.isInit flag. Both this module
61187       ** and the pager code use this trick (clearing the first byte
61188       ** of the page 'extra' space to invalidate the Btree layers
61189       ** cached parse of the page). MemPage.isInit is marked
61190       ** "MUST BE FIRST" for this purpose.
61191       */
61192       memcpy(zOut, zIn, nCopy);
61193       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
61194       if( iOff==0 && bUpdate==0 ){
61195         sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
61196       }
61197     }
61198     sqlite3PagerUnref(pDestPg);
61199   }
61200 
61201   return rc;
61202 }
61203 
61204 /*
61205 ** If pFile is currently larger than iSize bytes, then truncate it to
61206 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
61207 ** this function is a no-op.
61208 **
61209 ** Return SQLITE_OK if everything is successful, or an SQLite error
61210 ** code if an error occurs.
61211 */
61212 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
61213   i64 iCurrent;
61214   int rc = sqlite3OsFileSize(pFile, &iCurrent);
61215   if( rc==SQLITE_OK && iCurrent>iSize ){
61216     rc = sqlite3OsTruncate(pFile, iSize);
61217   }
61218   return rc;
61219 }
61220 
61221 /*
61222 ** Register this backup object with the associated source pager for
61223 ** callbacks when pages are changed or the cache invalidated.
61224 */
61225 static void attachBackupObject(sqlite3_backup *p){
61226   sqlite3_backup **pp;
61227   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
61228   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
61229   p->pNext = *pp;
61230   *pp = p;
61231   p->isAttached = 1;
61232 }
61233 
61234 /*
61235 ** Copy nPage pages from the source b-tree to the destination.
61236 */
61237 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
61238   int rc;
61239   int destMode;       /* Destination journal mode */
61240   int pgszSrc = 0;    /* Source page size */
61241   int pgszDest = 0;   /* Destination page size */
61242 
61243   sqlite3_mutex_enter(p->pSrcDb->mutex);
61244   sqlite3BtreeEnter(p->pSrc);
61245   if( p->pDestDb ){
61246     sqlite3_mutex_enter(p->pDestDb->mutex);
61247   }
61248 
61249   rc = p->rc;
61250   if( !isFatalError(rc) ){
61251     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
61252     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
61253     int ii;                            /* Iterator variable */
61254     int nSrcPage = -1;                 /* Size of source db in pages */
61255     int bCloseTrans = 0;               /* True if src db requires unlocking */
61256 
61257     /* If the source pager is currently in a write-transaction, return
61258     ** SQLITE_BUSY immediately.
61259     */
61260     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
61261       rc = SQLITE_BUSY;
61262     }else{
61263       rc = SQLITE_OK;
61264     }
61265 
61266     /* Lock the destination database, if it is not locked already. */
61267     if( SQLITE_OK==rc && p->bDestLocked==0
61268      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
61269     ){
61270       p->bDestLocked = 1;
61271       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
61272     }
61273 
61274     /* If there is no open read-transaction on the source database, open
61275     ** one now. If a transaction is opened here, then it will be closed
61276     ** before this function exits.
61277     */
61278     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
61279       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
61280       bCloseTrans = 1;
61281     }
61282 
61283     /* Do not allow backup if the destination database is in WAL mode
61284     ** and the page sizes are different between source and destination */
61285     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
61286     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
61287     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
61288     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
61289       rc = SQLITE_READONLY;
61290     }
61291 
61292     /* Now that there is a read-lock on the source database, query the
61293     ** source pager for the number of pages in the database.
61294     */
61295     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
61296     assert( nSrcPage>=0 );
61297     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
61298       const Pgno iSrcPg = p->iNext;                 /* Source page number */
61299       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
61300         DbPage *pSrcPg;                             /* Source page object */
61301         rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
61302                                  PAGER_GET_READONLY);
61303         if( rc==SQLITE_OK ){
61304           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
61305           sqlite3PagerUnref(pSrcPg);
61306         }
61307       }
61308       p->iNext++;
61309     }
61310     if( rc==SQLITE_OK ){
61311       p->nPagecount = nSrcPage;
61312       p->nRemaining = nSrcPage+1-p->iNext;
61313       if( p->iNext>(Pgno)nSrcPage ){
61314         rc = SQLITE_DONE;
61315       }else if( !p->isAttached ){
61316         attachBackupObject(p);
61317       }
61318     }
61319 
61320     /* Update the schema version field in the destination database. This
61321     ** is to make sure that the schema-version really does change in
61322     ** the case where the source and destination databases have the
61323     ** same schema version.
61324     */
61325     if( rc==SQLITE_DONE ){
61326       if( nSrcPage==0 ){
61327         rc = sqlite3BtreeNewDb(p->pDest);
61328         nSrcPage = 1;
61329       }
61330       if( rc==SQLITE_OK || rc==SQLITE_DONE ){
61331         rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
61332       }
61333       if( rc==SQLITE_OK ){
61334         if( p->pDestDb ){
61335           sqlite3ResetAllSchemasOfConnection(p->pDestDb);
61336         }
61337         if( destMode==PAGER_JOURNALMODE_WAL ){
61338           rc = sqlite3BtreeSetVersion(p->pDest, 2);
61339         }
61340       }
61341       if( rc==SQLITE_OK ){
61342         int nDestTruncate;
61343         /* Set nDestTruncate to the final number of pages in the destination
61344         ** database. The complication here is that the destination page
61345         ** size may be different to the source page size.
61346         **
61347         ** If the source page size is smaller than the destination page size,
61348         ** round up. In this case the call to sqlite3OsTruncate() below will
61349         ** fix the size of the file. However it is important to call
61350         ** sqlite3PagerTruncateImage() here so that any pages in the
61351         ** destination file that lie beyond the nDestTruncate page mark are
61352         ** journalled by PagerCommitPhaseOne() before they are destroyed
61353         ** by the file truncation.
61354         */
61355         assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
61356         assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
61357         if( pgszSrc<pgszDest ){
61358           int ratio = pgszDest/pgszSrc;
61359           nDestTruncate = (nSrcPage+ratio-1)/ratio;
61360           if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
61361             nDestTruncate--;
61362           }
61363         }else{
61364           nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
61365         }
61366         assert( nDestTruncate>0 );
61367 
61368         if( pgszSrc<pgszDest ){
61369           /* If the source page-size is smaller than the destination page-size,
61370           ** two extra things may need to happen:
61371           **
61372           **   * The destination may need to be truncated, and
61373           **
61374           **   * Data stored on the pages immediately following the
61375           **     pending-byte page in the source database may need to be
61376           **     copied into the destination database.
61377           */
61378           const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
61379           sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
61380           Pgno iPg;
61381           int nDstPage;
61382           i64 iOff;
61383           i64 iEnd;
61384 
61385           assert( pFile );
61386           assert( nDestTruncate==0
61387               || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
61388                 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
61389              && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
61390           ));
61391 
61392           /* This block ensures that all data required to recreate the original
61393           ** database has been stored in the journal for pDestPager and the
61394           ** journal synced to disk. So at this point we may safely modify
61395           ** the database file in any way, knowing that if a power failure
61396           ** occurs, the original database will be reconstructed from the
61397           ** journal file.  */
61398           sqlite3PagerPagecount(pDestPager, &nDstPage);
61399           for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
61400             if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
61401               DbPage *pPg;
61402               rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
61403               if( rc==SQLITE_OK ){
61404                 rc = sqlite3PagerWrite(pPg);
61405                 sqlite3PagerUnref(pPg);
61406               }
61407             }
61408           }
61409           if( rc==SQLITE_OK ){
61410             rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
61411           }
61412 
61413           /* Write the extra pages and truncate the database file as required */
61414           iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
61415           for(
61416             iOff=PENDING_BYTE+pgszSrc;
61417             rc==SQLITE_OK && iOff<iEnd;
61418             iOff+=pgszSrc
61419           ){
61420             PgHdr *pSrcPg = 0;
61421             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
61422             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
61423             if( rc==SQLITE_OK ){
61424               u8 *zData = sqlite3PagerGetData(pSrcPg);
61425               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
61426             }
61427             sqlite3PagerUnref(pSrcPg);
61428           }
61429           if( rc==SQLITE_OK ){
61430             rc = backupTruncateFile(pFile, iSize);
61431           }
61432 
61433           /* Sync the database file to disk. */
61434           if( rc==SQLITE_OK ){
61435             rc = sqlite3PagerSync(pDestPager, 0);
61436           }
61437         }else{
61438           sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
61439           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
61440         }
61441 
61442         /* Finish committing the transaction to the destination database. */
61443         if( SQLITE_OK==rc
61444          && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
61445         ){
61446           rc = SQLITE_DONE;
61447         }
61448       }
61449     }
61450 
61451     /* If bCloseTrans is true, then this function opened a read transaction
61452     ** on the source database. Close the read transaction here. There is
61453     ** no need to check the return values of the btree methods here, as
61454     ** "committing" a read-only transaction cannot fail.
61455     */
61456     if( bCloseTrans ){
61457       TESTONLY( int rc2 );
61458       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
61459       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
61460       assert( rc2==SQLITE_OK );
61461     }
61462 
61463     if( rc==SQLITE_IOERR_NOMEM ){
61464       rc = SQLITE_NOMEM;
61465     }
61466     p->rc = rc;
61467   }
61468   if( p->pDestDb ){
61469     sqlite3_mutex_leave(p->pDestDb->mutex);
61470   }
61471   sqlite3BtreeLeave(p->pSrc);
61472   sqlite3_mutex_leave(p->pSrcDb->mutex);
61473   return rc;
61474 }
61475 
61476 /*
61477 ** Release all resources associated with an sqlite3_backup* handle.
61478 */
61479 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
61480   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
61481   sqlite3 *pSrcDb;                     /* Source database connection */
61482   int rc;                              /* Value to return */
61483 
61484   /* Enter the mutexes */
61485   if( p==0 ) return SQLITE_OK;
61486   pSrcDb = p->pSrcDb;
61487   sqlite3_mutex_enter(pSrcDb->mutex);
61488   sqlite3BtreeEnter(p->pSrc);
61489   if( p->pDestDb ){
61490     sqlite3_mutex_enter(p->pDestDb->mutex);
61491   }
61492 
61493   /* Detach this backup from the source pager. */
61494   if( p->pDestDb ){
61495     p->pSrc->nBackup--;
61496   }
61497   if( p->isAttached ){
61498     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
61499     while( *pp!=p ){
61500       pp = &(*pp)->pNext;
61501     }
61502     *pp = p->pNext;
61503   }
61504 
61505   /* If a transaction is still open on the Btree, roll it back. */
61506   sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
61507 
61508   /* Set the error code of the destination database handle. */
61509   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
61510   if( p->pDestDb ){
61511     sqlite3Error(p->pDestDb, rc);
61512 
61513     /* Exit the mutexes and free the backup context structure. */
61514     sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
61515   }
61516   sqlite3BtreeLeave(p->pSrc);
61517   if( p->pDestDb ){
61518     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
61519     ** call to sqlite3_backup_init() and is destroyed by a call to
61520     ** sqlite3_backup_finish(). */
61521     sqlite3_free(p);
61522   }
61523   sqlite3LeaveMutexAndCloseZombie(pSrcDb);
61524   return rc;
61525 }
61526 
61527 /*
61528 ** Return the number of pages still to be backed up as of the most recent
61529 ** call to sqlite3_backup_step().
61530 */
61531 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
61532   return p->nRemaining;
61533 }
61534 
61535 /*
61536 ** Return the total number of pages in the source database as of the most
61537 ** recent call to sqlite3_backup_step().
61538 */
61539 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
61540   return p->nPagecount;
61541 }
61542 
61543 /*
61544 ** This function is called after the contents of page iPage of the
61545 ** source database have been modified. If page iPage has already been
61546 ** copied into the destination database, then the data written to the
61547 ** destination is now invalidated. The destination copy of iPage needs
61548 ** to be updated with the new data before the backup operation is
61549 ** complete.
61550 **
61551 ** It is assumed that the mutex associated with the BtShared object
61552 ** corresponding to the source database is held when this function is
61553 ** called.
61554 */
61555 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
61556   sqlite3_backup *p;                   /* Iterator variable */
61557   for(p=pBackup; p; p=p->pNext){
61558     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
61559     if( !isFatalError(p->rc) && iPage<p->iNext ){
61560       /* The backup process p has already copied page iPage. But now it
61561       ** has been modified by a transaction on the source pager. Copy
61562       ** the new data into the backup.
61563       */
61564       int rc;
61565       assert( p->pDestDb );
61566       sqlite3_mutex_enter(p->pDestDb->mutex);
61567       rc = backupOnePage(p, iPage, aData, 1);
61568       sqlite3_mutex_leave(p->pDestDb->mutex);
61569       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
61570       if( rc!=SQLITE_OK ){
61571         p->rc = rc;
61572       }
61573     }
61574   }
61575 }
61576 
61577 /*
61578 ** Restart the backup process. This is called when the pager layer
61579 ** detects that the database has been modified by an external database
61580 ** connection. In this case there is no way of knowing which of the
61581 ** pages that have been copied into the destination database are still
61582 ** valid and which are not, so the entire process needs to be restarted.
61583 **
61584 ** It is assumed that the mutex associated with the BtShared object
61585 ** corresponding to the source database is held when this function is
61586 ** called.
61587 */
61588 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
61589   sqlite3_backup *p;                   /* Iterator variable */
61590   for(p=pBackup; p; p=p->pNext){
61591     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
61592     p->iNext = 1;
61593   }
61594 }
61595 
61596 #ifndef SQLITE_OMIT_VACUUM
61597 /*
61598 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
61599 ** must be active for both files.
61600 **
61601 ** The size of file pTo may be reduced by this operation. If anything
61602 ** goes wrong, the transaction on pTo is rolled back. If successful, the
61603 ** transaction is committed before returning.
61604 */
61605 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
61606   int rc;
61607   sqlite3_file *pFd;              /* File descriptor for database pTo */
61608   sqlite3_backup b;
61609   sqlite3BtreeEnter(pTo);
61610   sqlite3BtreeEnter(pFrom);
61611 
61612   assert( sqlite3BtreeIsInTrans(pTo) );
61613   pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
61614   if( pFd->pMethods ){
61615     i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
61616     rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
61617     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
61618     if( rc ) goto copy_finished;
61619   }
61620 
61621   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
61622   ** to 0. This is used by the implementations of sqlite3_backup_step()
61623   ** and sqlite3_backup_finish() to detect that they are being called
61624   ** from this function, not directly by the user.
61625   */
61626   memset(&b, 0, sizeof(b));
61627   b.pSrcDb = pFrom->db;
61628   b.pSrc = pFrom;
61629   b.pDest = pTo;
61630   b.iNext = 1;
61631 
61632   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
61633   ** file. By passing this as the number of pages to copy to
61634   ** sqlite3_backup_step(), we can guarantee that the copy finishes
61635   ** within a single call (unless an error occurs). The assert() statement
61636   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
61637   ** or an error code.
61638   */
61639   sqlite3_backup_step(&b, 0x7FFFFFFF);
61640   assert( b.rc!=SQLITE_OK );
61641   rc = sqlite3_backup_finish(&b);
61642   if( rc==SQLITE_OK ){
61643     pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
61644   }else{
61645     sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
61646   }
61647 
61648   assert( sqlite3BtreeIsInTrans(pTo)==0 );
61649 copy_finished:
61650   sqlite3BtreeLeave(pFrom);
61651   sqlite3BtreeLeave(pTo);
61652   return rc;
61653 }
61654 #endif /* SQLITE_OMIT_VACUUM */
61655 
61656 /************** End of backup.c **********************************************/
61657 /************** Begin file vdbemem.c *****************************************/
61658 /*
61659 ** 2004 May 26
61660 **
61661 ** The author disclaims copyright to this source code.  In place of
61662 ** a legal notice, here is a blessing:
61663 **
61664 **    May you do good and not evil.
61665 **    May you find forgiveness for yourself and forgive others.
61666 **    May you share freely, never taking more than you give.
61667 **
61668 *************************************************************************
61669 **
61670 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
61671 ** stores a single value in the VDBE.  Mem is an opaque structure visible
61672 ** only within the VDBE.  Interface routines refer to a Mem using the
61673 ** name sqlite_value
61674 */
61675 
61676 #ifdef SQLITE_DEBUG
61677 /*
61678 ** Check invariants on a Mem object.
61679 **
61680 ** This routine is intended for use inside of assert() statements, like
61681 ** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );
61682 */
61683 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
61684   /* If MEM_Dyn is set then Mem.xDel!=0.
61685   ** Mem.xDel is might not be initialized if MEM_Dyn is clear.
61686   */
61687   assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
61688 
61689   /* MEM_Dyn may only be set if Mem.szMalloc==0.  In this way we
61690   ** ensure that if Mem.szMalloc>0 then it is safe to do
61691   ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
61692   ** That saves a few cycles in inner loops. */
61693   assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
61694 
61695   /* Cannot be both MEM_Int and MEM_Real at the same time */
61696   assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
61697 
61698   /* The szMalloc field holds the correct memory allocation size */
61699   assert( p->szMalloc==0
61700        || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
61701 
61702   /* If p holds a string or blob, the Mem.z must point to exactly
61703   ** one of the following:
61704   **
61705   **   (1) Memory in Mem.zMalloc and managed by the Mem object
61706   **   (2) Memory to be freed using Mem.xDel
61707   **   (3) An ephemeral string or blob
61708   **   (4) A static string or blob
61709   */
61710   if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
61711     assert(
61712       ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
61713       ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
61714       ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
61715       ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
61716     );
61717   }
61718   return 1;
61719 }
61720 #endif
61721 
61722 
61723 /*
61724 ** If pMem is an object with a valid string representation, this routine
61725 ** ensures the internal encoding for the string representation is
61726 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
61727 **
61728 ** If pMem is not a string object, or the encoding of the string
61729 ** representation is already stored using the requested encoding, then this
61730 ** routine is a no-op.
61731 **
61732 ** SQLITE_OK is returned if the conversion is successful (or not required).
61733 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
61734 ** between formats.
61735 */
61736 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
61737 #ifndef SQLITE_OMIT_UTF16
61738   int rc;
61739 #endif
61740   assert( (pMem->flags&MEM_RowSet)==0 );
61741   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
61742            || desiredEnc==SQLITE_UTF16BE );
61743   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
61744     return SQLITE_OK;
61745   }
61746   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
61747 #ifdef SQLITE_OMIT_UTF16
61748   return SQLITE_ERROR;
61749 #else
61750 
61751   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
61752   ** then the encoding of the value may not have changed.
61753   */
61754   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
61755   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
61756   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
61757   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
61758   return rc;
61759 #endif
61760 }
61761 
61762 /*
61763 ** Make sure pMem->z points to a writable allocation of at least
61764 ** min(n,32) bytes.
61765 **
61766 ** If the bPreserve argument is true, then copy of the content of
61767 ** pMem->z into the new allocation.  pMem must be either a string or
61768 ** blob if bPreserve is true.  If bPreserve is false, any prior content
61769 ** in pMem->z is discarded.
61770 */
61771 SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
61772   assert( sqlite3VdbeCheckMemInvariants(pMem) );
61773   assert( (pMem->flags&MEM_RowSet)==0 );
61774 
61775   /* If the bPreserve flag is set to true, then the memory cell must already
61776   ** contain a valid string or blob value.  */
61777   assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
61778   testcase( bPreserve && pMem->z==0 );
61779 
61780   assert( pMem->szMalloc==0
61781        || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
61782   if( pMem->szMalloc<n ){
61783     if( n<32 ) n = 32;
61784     if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
61785       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
61786       bPreserve = 0;
61787     }else{
61788       if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
61789       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
61790     }
61791     if( pMem->zMalloc==0 ){
61792       sqlite3VdbeMemSetNull(pMem);
61793       pMem->z = 0;
61794       pMem->szMalloc = 0;
61795       return SQLITE_NOMEM;
61796     }else{
61797       pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
61798     }
61799   }
61800 
61801   if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){
61802     memcpy(pMem->zMalloc, pMem->z, pMem->n);
61803   }
61804   if( (pMem->flags&MEM_Dyn)!=0 ){
61805     assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
61806     pMem->xDel((void *)(pMem->z));
61807   }
61808 
61809   pMem->z = pMem->zMalloc;
61810   pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
61811   return SQLITE_OK;
61812 }
61813 
61814 /*
61815 ** Change the pMem->zMalloc allocation to be at least szNew bytes.
61816 ** If pMem->zMalloc already meets or exceeds the requested size, this
61817 ** routine is a no-op.
61818 **
61819 ** Any prior string or blob content in the pMem object may be discarded.
61820 ** The pMem->xDel destructor is called, if it exists.  Though MEM_Str
61821 ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
61822 ** values are preserved.
61823 **
61824 ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
61825 ** if unable to complete the resizing.
61826 */
61827 SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
61828   assert( szNew>0 );
61829   assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
61830   if( pMem->szMalloc<szNew ){
61831     return sqlite3VdbeMemGrow(pMem, szNew, 0);
61832   }
61833   assert( (pMem->flags & MEM_Dyn)==0 );
61834   pMem->z = pMem->zMalloc;
61835   pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
61836   return SQLITE_OK;
61837 }
61838 
61839 /*
61840 ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
61841 ** MEM.zMalloc, where it can be safely written.
61842 **
61843 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
61844 */
61845 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
61846   int f;
61847   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
61848   assert( (pMem->flags&MEM_RowSet)==0 );
61849   ExpandBlob(pMem);
61850   f = pMem->flags;
61851   if( (f&(MEM_Str|MEM_Blob)) && (pMem->szMalloc==0 || pMem->z!=pMem->zMalloc) ){
61852     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
61853       return SQLITE_NOMEM;
61854     }
61855     pMem->z[pMem->n] = 0;
61856     pMem->z[pMem->n+1] = 0;
61857     pMem->flags |= MEM_Term;
61858 #ifdef SQLITE_DEBUG
61859     pMem->pScopyFrom = 0;
61860 #endif
61861   }
61862 
61863   return SQLITE_OK;
61864 }
61865 
61866 /*
61867 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
61868 ** blob stored in dynamically allocated space.
61869 */
61870 #ifndef SQLITE_OMIT_INCRBLOB
61871 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
61872   if( pMem->flags & MEM_Zero ){
61873     int nByte;
61874     assert( pMem->flags&MEM_Blob );
61875     assert( (pMem->flags&MEM_RowSet)==0 );
61876     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
61877 
61878     /* Set nByte to the number of bytes required to store the expanded blob. */
61879     nByte = pMem->n + pMem->u.nZero;
61880     if( nByte<=0 ){
61881       nByte = 1;
61882     }
61883     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
61884       return SQLITE_NOMEM;
61885     }
61886 
61887     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
61888     pMem->n += pMem->u.nZero;
61889     pMem->flags &= ~(MEM_Zero|MEM_Term);
61890   }
61891   return SQLITE_OK;
61892 }
61893 #endif
61894 
61895 /*
61896 ** It is already known that pMem contains an unterminated string.
61897 ** Add the zero terminator.
61898 */
61899 static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
61900   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
61901     return SQLITE_NOMEM;
61902   }
61903   pMem->z[pMem->n] = 0;
61904   pMem->z[pMem->n+1] = 0;
61905   pMem->flags |= MEM_Term;
61906   return SQLITE_OK;
61907 }
61908 
61909 /*
61910 ** Make sure the given Mem is \u0000 terminated.
61911 */
61912 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
61913   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
61914   testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
61915   testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
61916   if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
61917     return SQLITE_OK;   /* Nothing to do */
61918   }else{
61919     return vdbeMemAddTerminator(pMem);
61920   }
61921 }
61922 
61923 /*
61924 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
61925 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
61926 ** is a no-op.
61927 **
61928 ** Existing representations MEM_Int and MEM_Real are invalidated if
61929 ** bForce is true but are retained if bForce is false.
61930 **
61931 ** A MEM_Null value will never be passed to this function. This function is
61932 ** used for converting values to text for returning to the user (i.e. via
61933 ** sqlite3_value_text()), or for ensuring that values to be used as btree
61934 ** keys are strings. In the former case a NULL pointer is returned the
61935 ** user and the latter is an internal programming error.
61936 */
61937 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
61938   int fg = pMem->flags;
61939   const int nByte = 32;
61940 
61941   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
61942   assert( !(fg&MEM_Zero) );
61943   assert( !(fg&(MEM_Str|MEM_Blob)) );
61944   assert( fg&(MEM_Int|MEM_Real) );
61945   assert( (pMem->flags&MEM_RowSet)==0 );
61946   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
61947 
61948 
61949   if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
61950     return SQLITE_NOMEM;
61951   }
61952 
61953   /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
61954   ** string representation of the value. Then, if the required encoding
61955   ** is UTF-16le or UTF-16be do a translation.
61956   **
61957   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
61958   */
61959   if( fg & MEM_Int ){
61960     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
61961   }else{
61962     assert( fg & MEM_Real );
61963     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
61964   }
61965   pMem->n = sqlite3Strlen30(pMem->z);
61966   pMem->enc = SQLITE_UTF8;
61967   pMem->flags |= MEM_Str|MEM_Term;
61968   if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
61969   sqlite3VdbeChangeEncoding(pMem, enc);
61970   return SQLITE_OK;
61971 }
61972 
61973 /*
61974 ** Memory cell pMem contains the context of an aggregate function.
61975 ** This routine calls the finalize method for that function.  The
61976 ** result of the aggregate is stored back into pMem.
61977 **
61978 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
61979 ** otherwise.
61980 */
61981 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
61982   int rc = SQLITE_OK;
61983   if( ALWAYS(pFunc && pFunc->xFinalize) ){
61984     sqlite3_context ctx;
61985     Mem t;
61986     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
61987     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
61988     memset(&ctx, 0, sizeof(ctx));
61989     memset(&t, 0, sizeof(t));
61990     t.flags = MEM_Null;
61991     t.db = pMem->db;
61992     ctx.pOut = &t;
61993     ctx.pMem = pMem;
61994     ctx.pFunc = pFunc;
61995     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
61996     assert( (pMem->flags & MEM_Dyn)==0 );
61997     if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
61998     memcpy(pMem, &t, sizeof(t));
61999     rc = ctx.isError;
62000   }
62001   return rc;
62002 }
62003 
62004 /*
62005 ** If the memory cell contains a value that must be freed by
62006 ** invoking the external callback in Mem.xDel, then this routine
62007 ** will free that value.  It also sets Mem.flags to MEM_Null.
62008 **
62009 ** This is a helper routine for sqlite3VdbeMemSetNull() and
62010 ** for sqlite3VdbeMemRelease().  Use those other routines as the
62011 ** entry point for releasing Mem resources.
62012 */
62013 static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
62014   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
62015   assert( VdbeMemDynamic(p) );
62016   if( p->flags&MEM_Agg ){
62017     sqlite3VdbeMemFinalize(p, p->u.pDef);
62018     assert( (p->flags & MEM_Agg)==0 );
62019     testcase( p->flags & MEM_Dyn );
62020   }
62021   if( p->flags&MEM_Dyn ){
62022     assert( (p->flags&MEM_RowSet)==0 );
62023     assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
62024     p->xDel((void *)p->z);
62025   }else if( p->flags&MEM_RowSet ){
62026     sqlite3RowSetClear(p->u.pRowSet);
62027   }else if( p->flags&MEM_Frame ){
62028     VdbeFrame *pFrame = p->u.pFrame;
62029     pFrame->pParent = pFrame->v->pDelFrame;
62030     pFrame->v->pDelFrame = pFrame;
62031   }
62032   p->flags = MEM_Null;
62033 }
62034 
62035 /*
62036 ** Release memory held by the Mem p, both external memory cleared
62037 ** by p->xDel and memory in p->zMalloc.
62038 **
62039 ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
62040 ** the unusual case where there really is memory in p that needs
62041 ** to be freed.
62042 */
62043 static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
62044   if( VdbeMemDynamic(p) ){
62045     vdbeMemClearExternAndSetNull(p);
62046   }
62047   if( p->szMalloc ){
62048     sqlite3DbFree(p->db, p->zMalloc);
62049     p->szMalloc = 0;
62050   }
62051   p->z = 0;
62052 }
62053 
62054 /*
62055 ** Release any memory resources held by the Mem.  Both the memory that is
62056 ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
62057 **
62058 ** Use this routine prior to clean up prior to abandoning a Mem, or to
62059 ** reset a Mem back to its minimum memory utilization.
62060 **
62061 ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
62062 ** prior to inserting new content into the Mem.
62063 */
62064 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
62065   assert( sqlite3VdbeCheckMemInvariants(p) );
62066   if( VdbeMemDynamic(p) || p->szMalloc ){
62067     vdbeMemClear(p);
62068   }
62069 }
62070 
62071 /*
62072 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
62073 ** If the double is out of range of a 64-bit signed integer then
62074 ** return the closest available 64-bit signed integer.
62075 */
62076 static i64 doubleToInt64(double r){
62077 #ifdef SQLITE_OMIT_FLOATING_POINT
62078   /* When floating-point is omitted, double and int64 are the same thing */
62079   return r;
62080 #else
62081   /*
62082   ** Many compilers we encounter do not define constants for the
62083   ** minimum and maximum 64-bit integers, or they define them
62084   ** inconsistently.  And many do not understand the "LL" notation.
62085   ** So we define our own static constants here using nothing
62086   ** larger than a 32-bit integer constant.
62087   */
62088   static const i64 maxInt = LARGEST_INT64;
62089   static const i64 minInt = SMALLEST_INT64;
62090 
62091   if( r<=(double)minInt ){
62092     return minInt;
62093   }else if( r>=(double)maxInt ){
62094     return maxInt;
62095   }else{
62096     return (i64)r;
62097   }
62098 #endif
62099 }
62100 
62101 /*
62102 ** Return some kind of integer value which is the best we can do
62103 ** at representing the value that *pMem describes as an integer.
62104 ** If pMem is an integer, then the value is exact.  If pMem is
62105 ** a floating-point then the value returned is the integer part.
62106 ** If pMem is a string or blob, then we make an attempt to convert
62107 ** it into an integer and return that.  If pMem represents an
62108 ** an SQL-NULL value, return 0.
62109 **
62110 ** If pMem represents a string value, its encoding might be changed.
62111 */
62112 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
62113   int flags;
62114   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62115   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62116   flags = pMem->flags;
62117   if( flags & MEM_Int ){
62118     return pMem->u.i;
62119   }else if( flags & MEM_Real ){
62120     return doubleToInt64(pMem->u.r);
62121   }else if( flags & (MEM_Str|MEM_Blob) ){
62122     i64 value = 0;
62123     assert( pMem->z || pMem->n==0 );
62124     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
62125     return value;
62126   }else{
62127     return 0;
62128   }
62129 }
62130 
62131 /*
62132 ** Return the best representation of pMem that we can get into a
62133 ** double.  If pMem is already a double or an integer, return its
62134 ** value.  If it is a string or blob, try to convert it to a double.
62135 ** If it is a NULL, return 0.0.
62136 */
62137 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
62138   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62139   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62140   if( pMem->flags & MEM_Real ){
62141     return pMem->u.r;
62142   }else if( pMem->flags & MEM_Int ){
62143     return (double)pMem->u.i;
62144   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
62145     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
62146     double val = (double)0;
62147     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
62148     return val;
62149   }else{
62150     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
62151     return (double)0;
62152   }
62153 }
62154 
62155 /*
62156 ** The MEM structure is already a MEM_Real.  Try to also make it a
62157 ** MEM_Int if we can.
62158 */
62159 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
62160   i64 ix;
62161   assert( pMem->flags & MEM_Real );
62162   assert( (pMem->flags & MEM_RowSet)==0 );
62163   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62164   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62165 
62166   ix = doubleToInt64(pMem->u.r);
62167 
62168   /* Only mark the value as an integer if
62169   **
62170   **    (1) the round-trip conversion real->int->real is a no-op, and
62171   **    (2) The integer is neither the largest nor the smallest
62172   **        possible integer (ticket #3922)
62173   **
62174   ** The second and third terms in the following conditional enforces
62175   ** the second condition under the assumption that addition overflow causes
62176   ** values to wrap around.
62177   */
62178   if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
62179     pMem->u.i = ix;
62180     MemSetTypeFlag(pMem, MEM_Int);
62181   }
62182 }
62183 
62184 /*
62185 ** Convert pMem to type integer.  Invalidate any prior representations.
62186 */
62187 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
62188   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62189   assert( (pMem->flags & MEM_RowSet)==0 );
62190   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62191 
62192   pMem->u.i = sqlite3VdbeIntValue(pMem);
62193   MemSetTypeFlag(pMem, MEM_Int);
62194   return SQLITE_OK;
62195 }
62196 
62197 /*
62198 ** Convert pMem so that it is of type MEM_Real.
62199 ** Invalidate any prior representations.
62200 */
62201 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
62202   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62203   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62204 
62205   pMem->u.r = sqlite3VdbeRealValue(pMem);
62206   MemSetTypeFlag(pMem, MEM_Real);
62207   return SQLITE_OK;
62208 }
62209 
62210 /*
62211 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
62212 ** Invalidate any prior representations.
62213 **
62214 ** Every effort is made to force the conversion, even if the input
62215 ** is a string that does not look completely like a number.  Convert
62216 ** as much of the string as we can and ignore the rest.
62217 */
62218 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
62219   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
62220     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
62221     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62222     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
62223       MemSetTypeFlag(pMem, MEM_Int);
62224     }else{
62225       pMem->u.r = sqlite3VdbeRealValue(pMem);
62226       MemSetTypeFlag(pMem, MEM_Real);
62227       sqlite3VdbeIntegerAffinity(pMem);
62228     }
62229   }
62230   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
62231   pMem->flags &= ~(MEM_Str|MEM_Blob);
62232   return SQLITE_OK;
62233 }
62234 
62235 /*
62236 ** Cast the datatype of the value in pMem according to the affinity
62237 ** "aff".  Casting is different from applying affinity in that a cast
62238 ** is forced.  In other words, the value is converted into the desired
62239 ** affinity even if that results in loss of data.  This routine is
62240 ** used (for example) to implement the SQL "cast()" operator.
62241 */
62242 SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
62243   if( pMem->flags & MEM_Null ) return;
62244   switch( aff ){
62245     case SQLITE_AFF_NONE: {   /* Really a cast to BLOB */
62246       if( (pMem->flags & MEM_Blob)==0 ){
62247         sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
62248         assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
62249         MemSetTypeFlag(pMem, MEM_Blob);
62250       }else{
62251         pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
62252       }
62253       break;
62254     }
62255     case SQLITE_AFF_NUMERIC: {
62256       sqlite3VdbeMemNumerify(pMem);
62257       break;
62258     }
62259     case SQLITE_AFF_INTEGER: {
62260       sqlite3VdbeMemIntegerify(pMem);
62261       break;
62262     }
62263     case SQLITE_AFF_REAL: {
62264       sqlite3VdbeMemRealify(pMem);
62265       break;
62266     }
62267     default: {
62268       assert( aff==SQLITE_AFF_TEXT );
62269       assert( MEM_Str==(MEM_Blob>>3) );
62270       pMem->flags |= (pMem->flags&MEM_Blob)>>3;
62271       sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
62272       assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
62273       pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
62274       break;
62275     }
62276   }
62277 }
62278 
62279 /*
62280 ** Initialize bulk memory to be a consistent Mem object.
62281 **
62282 ** The minimum amount of initialization feasible is performed.
62283 */
62284 SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
62285   assert( (flags & ~MEM_TypeMask)==0 );
62286   pMem->flags = flags;
62287   pMem->db = db;
62288   pMem->szMalloc = 0;
62289 }
62290 
62291 
62292 /*
62293 ** Delete any previous value and set the value stored in *pMem to NULL.
62294 **
62295 ** This routine calls the Mem.xDel destructor to dispose of values that
62296 ** require the destructor.  But it preserves the Mem.zMalloc memory allocation.
62297 ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
62298 ** routine to invoke the destructor and deallocates Mem.zMalloc.
62299 **
62300 ** Use this routine to reset the Mem prior to insert a new value.
62301 **
62302 ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
62303 */
62304 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
62305   if( VdbeMemDynamic(pMem) ){
62306     vdbeMemClearExternAndSetNull(pMem);
62307   }else{
62308     pMem->flags = MEM_Null;
62309   }
62310 }
62311 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
62312   sqlite3VdbeMemSetNull((Mem*)p);
62313 }
62314 
62315 /*
62316 ** Delete any previous value and set the value to be a BLOB of length
62317 ** n containing all zeros.
62318 */
62319 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
62320   sqlite3VdbeMemRelease(pMem);
62321   pMem->flags = MEM_Blob|MEM_Zero;
62322   pMem->n = 0;
62323   if( n<0 ) n = 0;
62324   pMem->u.nZero = n;
62325   pMem->enc = SQLITE_UTF8;
62326   pMem->z = 0;
62327 }
62328 
62329 /*
62330 ** The pMem is known to contain content that needs to be destroyed prior
62331 ** to a value change.  So invoke the destructor, then set the value to
62332 ** a 64-bit integer.
62333 */
62334 static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
62335   sqlite3VdbeMemSetNull(pMem);
62336   pMem->u.i = val;
62337   pMem->flags = MEM_Int;
62338 }
62339 
62340 /*
62341 ** Delete any previous value and set the value stored in *pMem to val,
62342 ** manifest type INTEGER.
62343 */
62344 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
62345   if( VdbeMemDynamic(pMem) ){
62346     vdbeReleaseAndSetInt64(pMem, val);
62347   }else{
62348     pMem->u.i = val;
62349     pMem->flags = MEM_Int;
62350   }
62351 }
62352 
62353 #ifndef SQLITE_OMIT_FLOATING_POINT
62354 /*
62355 ** Delete any previous value and set the value stored in *pMem to val,
62356 ** manifest type REAL.
62357 */
62358 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
62359   sqlite3VdbeMemSetNull(pMem);
62360   if( !sqlite3IsNaN(val) ){
62361     pMem->u.r = val;
62362     pMem->flags = MEM_Real;
62363   }
62364 }
62365 #endif
62366 
62367 /*
62368 ** Delete any previous value and set the value of pMem to be an
62369 ** empty boolean index.
62370 */
62371 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
62372   sqlite3 *db = pMem->db;
62373   assert( db!=0 );
62374   assert( (pMem->flags & MEM_RowSet)==0 );
62375   sqlite3VdbeMemRelease(pMem);
62376   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
62377   if( db->mallocFailed ){
62378     pMem->flags = MEM_Null;
62379     pMem->szMalloc = 0;
62380   }else{
62381     assert( pMem->zMalloc );
62382     pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
62383     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
62384     assert( pMem->u.pRowSet!=0 );
62385     pMem->flags = MEM_RowSet;
62386   }
62387 }
62388 
62389 /*
62390 ** Return true if the Mem object contains a TEXT or BLOB that is
62391 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
62392 */
62393 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
62394   assert( p->db!=0 );
62395   if( p->flags & (MEM_Str|MEM_Blob) ){
62396     int n = p->n;
62397     if( p->flags & MEM_Zero ){
62398       n += p->u.nZero;
62399     }
62400     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
62401   }
62402   return 0;
62403 }
62404 
62405 #ifdef SQLITE_DEBUG
62406 /*
62407 ** This routine prepares a memory cell for modification by breaking
62408 ** its link to a shallow copy and by marking any current shallow
62409 ** copies of this cell as invalid.
62410 **
62411 ** This is used for testing and debugging only - to make sure shallow
62412 ** copies are not misused.
62413 */
62414 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
62415   int i;
62416   Mem *pX;
62417   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
62418     if( pX->pScopyFrom==pMem ){
62419       pX->flags |= MEM_Undefined;
62420       pX->pScopyFrom = 0;
62421     }
62422   }
62423   pMem->pScopyFrom = 0;
62424 }
62425 #endif /* SQLITE_DEBUG */
62426 
62427 /*
62428 ** Size of struct Mem not including the Mem.zMalloc member.
62429 */
62430 #define MEMCELLSIZE offsetof(Mem,zMalloc)
62431 
62432 /*
62433 ** Make an shallow copy of pFrom into pTo.  Prior contents of
62434 ** pTo are freed.  The pFrom->z field is not duplicated.  If
62435 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
62436 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
62437 */
62438 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
62439   assert( (pFrom->flags & MEM_RowSet)==0 );
62440   assert( pTo->db==pFrom->db );
62441   if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
62442   memcpy(pTo, pFrom, MEMCELLSIZE);
62443   if( (pFrom->flags&MEM_Static)==0 ){
62444     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
62445     assert( srcType==MEM_Ephem || srcType==MEM_Static );
62446     pTo->flags |= srcType;
62447   }
62448 }
62449 
62450 /*
62451 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
62452 ** freed before the copy is made.
62453 */
62454 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
62455   int rc = SQLITE_OK;
62456 
62457   assert( pTo->db==pFrom->db );
62458   assert( (pFrom->flags & MEM_RowSet)==0 );
62459   if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
62460   memcpy(pTo, pFrom, MEMCELLSIZE);
62461   pTo->flags &= ~MEM_Dyn;
62462   if( pTo->flags&(MEM_Str|MEM_Blob) ){
62463     if( 0==(pFrom->flags&MEM_Static) ){
62464       pTo->flags |= MEM_Ephem;
62465       rc = sqlite3VdbeMemMakeWriteable(pTo);
62466     }
62467   }
62468 
62469   return rc;
62470 }
62471 
62472 /*
62473 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
62474 ** freed. If pFrom contains ephemeral data, a copy is made.
62475 **
62476 ** pFrom contains an SQL NULL when this routine returns.
62477 */
62478 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
62479   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
62480   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
62481   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
62482 
62483   sqlite3VdbeMemRelease(pTo);
62484   memcpy(pTo, pFrom, sizeof(Mem));
62485   pFrom->flags = MEM_Null;
62486   pFrom->szMalloc = 0;
62487 }
62488 
62489 /*
62490 ** Change the value of a Mem to be a string or a BLOB.
62491 **
62492 ** The memory management strategy depends on the value of the xDel
62493 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
62494 ** string is copied into a (possibly existing) buffer managed by the
62495 ** Mem structure. Otherwise, any existing buffer is freed and the
62496 ** pointer copied.
62497 **
62498 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
62499 ** size limit) then no memory allocation occurs.  If the string can be
62500 ** stored without allocating memory, then it is.  If a memory allocation
62501 ** is required to store the string, then value of pMem is unchanged.  In
62502 ** either case, SQLITE_TOOBIG is returned.
62503 */
62504 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
62505   Mem *pMem,          /* Memory cell to set to string value */
62506   const char *z,      /* String pointer */
62507   int n,              /* Bytes in string, or negative */
62508   u8 enc,             /* Encoding of z.  0 for BLOBs */
62509   void (*xDel)(void*) /* Destructor function */
62510 ){
62511   int nByte = n;      /* New value for pMem->n */
62512   int iLimit;         /* Maximum allowed string or blob size */
62513   u16 flags = 0;      /* New value for pMem->flags */
62514 
62515   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
62516   assert( (pMem->flags & MEM_RowSet)==0 );
62517 
62518   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
62519   if( !z ){
62520     sqlite3VdbeMemSetNull(pMem);
62521     return SQLITE_OK;
62522   }
62523 
62524   if( pMem->db ){
62525     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
62526   }else{
62527     iLimit = SQLITE_MAX_LENGTH;
62528   }
62529   flags = (enc==0?MEM_Blob:MEM_Str);
62530   if( nByte<0 ){
62531     assert( enc!=0 );
62532     if( enc==SQLITE_UTF8 ){
62533       nByte = sqlite3Strlen30(z);
62534       if( nByte>iLimit ) nByte = iLimit+1;
62535     }else{
62536       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
62537     }
62538     flags |= MEM_Term;
62539   }
62540 
62541   /* The following block sets the new values of Mem.z and Mem.xDel. It
62542   ** also sets a flag in local variable "flags" to indicate the memory
62543   ** management (one of MEM_Dyn or MEM_Static).
62544   */
62545   if( xDel==SQLITE_TRANSIENT ){
62546     int nAlloc = nByte;
62547     if( flags&MEM_Term ){
62548       nAlloc += (enc==SQLITE_UTF8?1:2);
62549     }
62550     if( nByte>iLimit ){
62551       return SQLITE_TOOBIG;
62552     }
62553     testcase( nAlloc==0 );
62554     testcase( nAlloc==31 );
62555     testcase( nAlloc==32 );
62556     if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
62557       return SQLITE_NOMEM;
62558     }
62559     memcpy(pMem->z, z, nAlloc);
62560   }else if( xDel==SQLITE_DYNAMIC ){
62561     sqlite3VdbeMemRelease(pMem);
62562     pMem->zMalloc = pMem->z = (char *)z;
62563     pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
62564   }else{
62565     sqlite3VdbeMemRelease(pMem);
62566     pMem->z = (char *)z;
62567     pMem->xDel = xDel;
62568     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
62569   }
62570 
62571   pMem->n = nByte;
62572   pMem->flags = flags;
62573   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
62574 
62575 #ifndef SQLITE_OMIT_UTF16
62576   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
62577     return SQLITE_NOMEM;
62578   }
62579 #endif
62580 
62581   if( nByte>iLimit ){
62582     return SQLITE_TOOBIG;
62583   }
62584 
62585   return SQLITE_OK;
62586 }
62587 
62588 /*
62589 ** Move data out of a btree key or data field and into a Mem structure.
62590 ** The data or key is taken from the entry that pCur is currently pointing
62591 ** to.  offset and amt determine what portion of the data or key to retrieve.
62592 ** key is true to get the key or false to get data.  The result is written
62593 ** into the pMem element.
62594 **
62595 ** The pMem object must have been initialized.  This routine will use
62596 ** pMem->zMalloc to hold the content from the btree, if possible.  New
62597 ** pMem->zMalloc space will be allocated if necessary.  The calling routine
62598 ** is responsible for making sure that the pMem object is eventually
62599 ** destroyed.
62600 **
62601 ** If this routine fails for any reason (malloc returns NULL or unable
62602 ** to read from the disk) then the pMem is left in an inconsistent state.
62603 */
62604 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
62605   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
62606   u32 offset,       /* Offset from the start of data to return bytes from. */
62607   u32 amt,          /* Number of bytes to return. */
62608   int key,          /* If true, retrieve from the btree key, not data. */
62609   Mem *pMem         /* OUT: Return data in this Mem structure. */
62610 ){
62611   char *zData;        /* Data from the btree layer */
62612   u32 available = 0;  /* Number of bytes available on the local btree page */
62613   int rc = SQLITE_OK; /* Return code */
62614 
62615   assert( sqlite3BtreeCursorIsValid(pCur) );
62616   assert( !VdbeMemDynamic(pMem) );
62617 
62618   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
62619   ** that both the BtShared and database handle mutexes are held. */
62620   assert( (pMem->flags & MEM_RowSet)==0 );
62621   if( key ){
62622     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
62623   }else{
62624     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
62625   }
62626   assert( zData!=0 );
62627 
62628   if( offset+amt<=available ){
62629     pMem->z = &zData[offset];
62630     pMem->flags = MEM_Blob|MEM_Ephem;
62631     pMem->n = (int)amt;
62632   }else{
62633     pMem->flags = MEM_Null;
62634     if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
62635       if( key ){
62636         rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
62637       }else{
62638         rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
62639       }
62640       if( rc==SQLITE_OK ){
62641         pMem->z[amt] = 0;
62642         pMem->z[amt+1] = 0;
62643         pMem->flags = MEM_Blob|MEM_Term;
62644         pMem->n = (int)amt;
62645       }else{
62646         sqlite3VdbeMemRelease(pMem);
62647       }
62648     }
62649   }
62650 
62651   return rc;
62652 }
62653 
62654 /*
62655 ** The pVal argument is known to be a value other than NULL.
62656 ** Convert it into a string with encoding enc and return a pointer
62657 ** to a zero-terminated version of that string.
62658 */
62659 static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
62660   assert( pVal!=0 );
62661   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
62662   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
62663   assert( (pVal->flags & MEM_RowSet)==0 );
62664   assert( (pVal->flags & (MEM_Null))==0 );
62665   if( pVal->flags & (MEM_Blob|MEM_Str) ){
62666     pVal->flags |= MEM_Str;
62667     if( pVal->flags & MEM_Zero ){
62668       sqlite3VdbeMemExpandBlob(pVal);
62669     }
62670     if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
62671       sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
62672     }
62673     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
62674       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
62675       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
62676         return 0;
62677       }
62678     }
62679     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
62680   }else{
62681     sqlite3VdbeMemStringify(pVal, enc, 0);
62682     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
62683   }
62684   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
62685               || pVal->db->mallocFailed );
62686   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
62687     return pVal->z;
62688   }else{
62689     return 0;
62690   }
62691 }
62692 
62693 /* This function is only available internally, it is not part of the
62694 ** external API. It works in a similar way to sqlite3_value_text(),
62695 ** except the data returned is in the encoding specified by the second
62696 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
62697 ** SQLITE_UTF8.
62698 **
62699 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
62700 ** If that is the case, then the result must be aligned on an even byte
62701 ** boundary.
62702 */
62703 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
62704   if( !pVal ) return 0;
62705   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
62706   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
62707   assert( (pVal->flags & MEM_RowSet)==0 );
62708   if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
62709     return pVal->z;
62710   }
62711   if( pVal->flags&MEM_Null ){
62712     return 0;
62713   }
62714   return valueToText(pVal, enc);
62715 }
62716 
62717 /*
62718 ** Create a new sqlite3_value object.
62719 */
62720 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
62721   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
62722   if( p ){
62723     p->flags = MEM_Null;
62724     p->db = db;
62725   }
62726   return p;
62727 }
62728 
62729 /*
62730 ** Context object passed by sqlite3Stat4ProbeSetValue() through to
62731 ** valueNew(). See comments above valueNew() for details.
62732 */
62733 struct ValueNewStat4Ctx {
62734   Parse *pParse;
62735   Index *pIdx;
62736   UnpackedRecord **ppRec;
62737   int iVal;
62738 };
62739 
62740 /*
62741 ** Allocate and return a pointer to a new sqlite3_value object. If
62742 ** the second argument to this function is NULL, the object is allocated
62743 ** by calling sqlite3ValueNew().
62744 **
62745 ** Otherwise, if the second argument is non-zero, then this function is
62746 ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
62747 ** already been allocated, allocate the UnpackedRecord structure that
62748 ** that function will return to its caller here. Then return a pointer
62749 ** an sqlite3_value within the UnpackedRecord.a[] array.
62750 */
62751 static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
62752 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
62753   if( p ){
62754     UnpackedRecord *pRec = p->ppRec[0];
62755 
62756     if( pRec==0 ){
62757       Index *pIdx = p->pIdx;      /* Index being probed */
62758       int nByte;                  /* Bytes of space to allocate */
62759       int i;                      /* Counter variable */
62760       int nCol = pIdx->nColumn;   /* Number of index columns including rowid */
62761 
62762       nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
62763       pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
62764       if( pRec ){
62765         pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
62766         if( pRec->pKeyInfo ){
62767           assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
62768           assert( pRec->pKeyInfo->enc==ENC(db) );
62769           pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
62770           for(i=0; i<nCol; i++){
62771             pRec->aMem[i].flags = MEM_Null;
62772             pRec->aMem[i].db = db;
62773           }
62774         }else{
62775           sqlite3DbFree(db, pRec);
62776           pRec = 0;
62777         }
62778       }
62779       if( pRec==0 ) return 0;
62780       p->ppRec[0] = pRec;
62781     }
62782 
62783     pRec->nField = p->iVal+1;
62784     return &pRec->aMem[p->iVal];
62785   }
62786 #else
62787   UNUSED_PARAMETER(p);
62788 #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
62789   return sqlite3ValueNew(db);
62790 }
62791 
62792 /*
62793 ** Extract a value from the supplied expression in the manner described
62794 ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
62795 ** using valueNew().
62796 **
62797 ** If pCtx is NULL and an error occurs after the sqlite3_value object
62798 ** has been allocated, it is freed before returning. Or, if pCtx is not
62799 ** NULL, it is assumed that the caller will free any allocated object
62800 ** in all cases.
62801 */
62802 static int valueFromExpr(
62803   sqlite3 *db,                    /* The database connection */
62804   Expr *pExpr,                    /* The expression to evaluate */
62805   u8 enc,                         /* Encoding to use */
62806   u8 affinity,                    /* Affinity to use */
62807   sqlite3_value **ppVal,          /* Write the new value here */
62808   struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
62809 ){
62810   int op;
62811   char *zVal = 0;
62812   sqlite3_value *pVal = 0;
62813   int negInt = 1;
62814   const char *zNeg = "";
62815   int rc = SQLITE_OK;
62816 
62817   if( !pExpr ){
62818     *ppVal = 0;
62819     return SQLITE_OK;
62820   }
62821   while( (op = pExpr->op)==TK_UPLUS ) pExpr = pExpr->pLeft;
62822   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
62823 
62824   if( op==TK_CAST ){
62825     u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
62826     rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
62827     testcase( rc!=SQLITE_OK );
62828     if( *ppVal ){
62829       sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
62830       sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
62831     }
62832     return rc;
62833   }
62834 
62835   /* Handle negative integers in a single step.  This is needed in the
62836   ** case when the value is -9223372036854775808.
62837   */
62838   if( op==TK_UMINUS
62839    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
62840     pExpr = pExpr->pLeft;
62841     op = pExpr->op;
62842     negInt = -1;
62843     zNeg = "-";
62844   }
62845 
62846   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
62847     pVal = valueNew(db, pCtx);
62848     if( pVal==0 ) goto no_mem;
62849     if( ExprHasProperty(pExpr, EP_IntValue) ){
62850       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
62851     }else{
62852       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
62853       if( zVal==0 ) goto no_mem;
62854       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
62855     }
62856     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
62857       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
62858     }else{
62859       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
62860     }
62861     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
62862     if( enc!=SQLITE_UTF8 ){
62863       rc = sqlite3VdbeChangeEncoding(pVal, enc);
62864     }
62865   }else if( op==TK_UMINUS ) {
62866     /* This branch happens for multiple negative signs.  Ex: -(-5) */
62867     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
62868      && pVal!=0
62869     ){
62870       sqlite3VdbeMemNumerify(pVal);
62871       if( pVal->flags & MEM_Real ){
62872         pVal->u.r = -pVal->u.r;
62873       }else if( pVal->u.i==SMALLEST_INT64 ){
62874         pVal->u.r = -(double)SMALLEST_INT64;
62875         MemSetTypeFlag(pVal, MEM_Real);
62876       }else{
62877         pVal->u.i = -pVal->u.i;
62878       }
62879       sqlite3ValueApplyAffinity(pVal, affinity, enc);
62880     }
62881   }else if( op==TK_NULL ){
62882     pVal = valueNew(db, pCtx);
62883     if( pVal==0 ) goto no_mem;
62884   }
62885 #ifndef SQLITE_OMIT_BLOB_LITERAL
62886   else if( op==TK_BLOB ){
62887     int nVal;
62888     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
62889     assert( pExpr->u.zToken[1]=='\'' );
62890     pVal = valueNew(db, pCtx);
62891     if( !pVal ) goto no_mem;
62892     zVal = &pExpr->u.zToken[2];
62893     nVal = sqlite3Strlen30(zVal)-1;
62894     assert( zVal[nVal]=='\'' );
62895     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
62896                          0, SQLITE_DYNAMIC);
62897   }
62898 #endif
62899 
62900   *ppVal = pVal;
62901   return rc;
62902 
62903 no_mem:
62904   db->mallocFailed = 1;
62905   sqlite3DbFree(db, zVal);
62906   assert( *ppVal==0 );
62907 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
62908   if( pCtx==0 ) sqlite3ValueFree(pVal);
62909 #else
62910   assert( pCtx==0 ); sqlite3ValueFree(pVal);
62911 #endif
62912   return SQLITE_NOMEM;
62913 }
62914 
62915 /*
62916 ** Create a new sqlite3_value object, containing the value of pExpr.
62917 **
62918 ** This only works for very simple expressions that consist of one constant
62919 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
62920 ** be converted directly into a value, then the value is allocated and
62921 ** a pointer written to *ppVal. The caller is responsible for deallocating
62922 ** the value by passing it to sqlite3ValueFree() later on. If the expression
62923 ** cannot be converted to a value, then *ppVal is set to NULL.
62924 */
62925 SQLITE_PRIVATE int sqlite3ValueFromExpr(
62926   sqlite3 *db,              /* The database connection */
62927   Expr *pExpr,              /* The expression to evaluate */
62928   u8 enc,                   /* Encoding to use */
62929   u8 affinity,              /* Affinity to use */
62930   sqlite3_value **ppVal     /* Write the new value here */
62931 ){
62932   return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
62933 }
62934 
62935 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
62936 /*
62937 ** The implementation of the sqlite_record() function. This function accepts
62938 ** a single argument of any type. The return value is a formatted database
62939 ** record (a blob) containing the argument value.
62940 **
62941 ** This is used to convert the value stored in the 'sample' column of the
62942 ** sqlite_stat3 table to the record format SQLite uses internally.
62943 */
62944 static void recordFunc(
62945   sqlite3_context *context,
62946   int argc,
62947   sqlite3_value **argv
62948 ){
62949   const int file_format = 1;
62950   int iSerial;                    /* Serial type */
62951   int nSerial;                    /* Bytes of space for iSerial as varint */
62952   int nVal;                       /* Bytes of space required for argv[0] */
62953   int nRet;
62954   sqlite3 *db;
62955   u8 *aRet;
62956 
62957   UNUSED_PARAMETER( argc );
62958   iSerial = sqlite3VdbeSerialType(argv[0], file_format);
62959   nSerial = sqlite3VarintLen(iSerial);
62960   nVal = sqlite3VdbeSerialTypeLen(iSerial);
62961   db = sqlite3_context_db_handle(context);
62962 
62963   nRet = 1 + nSerial + nVal;
62964   aRet = sqlite3DbMallocRaw(db, nRet);
62965   if( aRet==0 ){
62966     sqlite3_result_error_nomem(context);
62967   }else{
62968     aRet[0] = nSerial+1;
62969     putVarint32(&aRet[1], iSerial);
62970     sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
62971     sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
62972     sqlite3DbFree(db, aRet);
62973   }
62974 }
62975 
62976 /*
62977 ** Register built-in functions used to help read ANALYZE data.
62978 */
62979 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
62980   static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
62981     FUNCTION(sqlite_record,   1, 0, 0, recordFunc),
62982   };
62983   int i;
62984   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
62985   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
62986   for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
62987     sqlite3FuncDefInsert(pHash, &aFunc[i]);
62988   }
62989 }
62990 
62991 /*
62992 ** Attempt to extract a value from pExpr and use it to construct *ppVal.
62993 **
62994 ** If pAlloc is not NULL, then an UnpackedRecord object is created for
62995 ** pAlloc if one does not exist and the new value is added to the
62996 ** UnpackedRecord object.
62997 **
62998 ** A value is extracted in the following cases:
62999 **
63000 **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
63001 **
63002 **  * The expression is a bound variable, and this is a reprepare, or
63003 **
63004 **  * The expression is a literal value.
63005 **
63006 ** On success, *ppVal is made to point to the extracted value.  The caller
63007 ** is responsible for ensuring that the value is eventually freed.
63008 */
63009 static int stat4ValueFromExpr(
63010   Parse *pParse,                  /* Parse context */
63011   Expr *pExpr,                    /* The expression to extract a value from */
63012   u8 affinity,                    /* Affinity to use */
63013   struct ValueNewStat4Ctx *pAlloc,/* How to allocate space.  Or NULL */
63014   sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
63015 ){
63016   int rc = SQLITE_OK;
63017   sqlite3_value *pVal = 0;
63018   sqlite3 *db = pParse->db;
63019 
63020   /* Skip over any TK_COLLATE nodes */
63021   pExpr = sqlite3ExprSkipCollate(pExpr);
63022 
63023   if( !pExpr ){
63024     pVal = valueNew(db, pAlloc);
63025     if( pVal ){
63026       sqlite3VdbeMemSetNull((Mem*)pVal);
63027     }
63028   }else if( pExpr->op==TK_VARIABLE
63029         || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
63030   ){
63031     Vdbe *v;
63032     int iBindVar = pExpr->iColumn;
63033     sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
63034     if( (v = pParse->pReprepare)!=0 ){
63035       pVal = valueNew(db, pAlloc);
63036       if( pVal ){
63037         rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
63038         if( rc==SQLITE_OK ){
63039           sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
63040         }
63041         pVal->db = pParse->db;
63042       }
63043     }
63044   }else{
63045     rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
63046   }
63047 
63048   assert( pVal==0 || pVal->db==db );
63049   *ppVal = pVal;
63050   return rc;
63051 }
63052 
63053 /*
63054 ** This function is used to allocate and populate UnpackedRecord
63055 ** structures intended to be compared against sample index keys stored
63056 ** in the sqlite_stat4 table.
63057 **
63058 ** A single call to this function attempts to populates field iVal (leftmost
63059 ** is 0 etc.) of the unpacked record with a value extracted from expression
63060 ** pExpr. Extraction of values is possible if:
63061 **
63062 **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
63063 **
63064 **  * The expression is a bound variable, and this is a reprepare, or
63065 **
63066 **  * The sqlite3ValueFromExpr() function is able to extract a value
63067 **    from the expression (i.e. the expression is a literal value).
63068 **
63069 ** If a value can be extracted, the affinity passed as the 5th argument
63070 ** is applied to it before it is copied into the UnpackedRecord. Output
63071 ** parameter *pbOk is set to true if a value is extracted, or false
63072 ** otherwise.
63073 **
63074 ** When this function is called, *ppRec must either point to an object
63075 ** allocated by an earlier call to this function, or must be NULL. If it
63076 ** is NULL and a value can be successfully extracted, a new UnpackedRecord
63077 ** is allocated (and *ppRec set to point to it) before returning.
63078 **
63079 ** Unless an error is encountered, SQLITE_OK is returned. It is not an
63080 ** error if a value cannot be extracted from pExpr. If an error does
63081 ** occur, an SQLite error code is returned.
63082 */
63083 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
63084   Parse *pParse,                  /* Parse context */
63085   Index *pIdx,                    /* Index being probed */
63086   UnpackedRecord **ppRec,         /* IN/OUT: Probe record */
63087   Expr *pExpr,                    /* The expression to extract a value from */
63088   u8 affinity,                    /* Affinity to use */
63089   int iVal,                       /* Array element to populate */
63090   int *pbOk                       /* OUT: True if value was extracted */
63091 ){
63092   int rc;
63093   sqlite3_value *pVal = 0;
63094   struct ValueNewStat4Ctx alloc;
63095 
63096   alloc.pParse = pParse;
63097   alloc.pIdx = pIdx;
63098   alloc.ppRec = ppRec;
63099   alloc.iVal = iVal;
63100 
63101   rc = stat4ValueFromExpr(pParse, pExpr, affinity, &alloc, &pVal);
63102   assert( pVal==0 || pVal->db==pParse->db );
63103   *pbOk = (pVal!=0);
63104   return rc;
63105 }
63106 
63107 /*
63108 ** Attempt to extract a value from expression pExpr using the methods
63109 ** as described for sqlite3Stat4ProbeSetValue() above.
63110 **
63111 ** If successful, set *ppVal to point to a new value object and return
63112 ** SQLITE_OK. If no value can be extracted, but no other error occurs
63113 ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
63114 ** does occur, return an SQLite error code. The final value of *ppVal
63115 ** is undefined in this case.
63116 */
63117 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
63118   Parse *pParse,                  /* Parse context */
63119   Expr *pExpr,                    /* The expression to extract a value from */
63120   u8 affinity,                    /* Affinity to use */
63121   sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
63122 ){
63123   return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
63124 }
63125 
63126 /*
63127 ** Extract the iCol-th column from the nRec-byte record in pRec.  Write
63128 ** the column value into *ppVal.  If *ppVal is initially NULL then a new
63129 ** sqlite3_value object is allocated.
63130 **
63131 ** If *ppVal is initially NULL then the caller is responsible for
63132 ** ensuring that the value written into *ppVal is eventually freed.
63133 */
63134 SQLITE_PRIVATE int sqlite3Stat4Column(
63135   sqlite3 *db,                    /* Database handle */
63136   const void *pRec,               /* Pointer to buffer containing record */
63137   int nRec,                       /* Size of buffer pRec in bytes */
63138   int iCol,                       /* Column to extract */
63139   sqlite3_value **ppVal           /* OUT: Extracted value */
63140 ){
63141   u32 t;                          /* a column type code */
63142   int nHdr;                       /* Size of the header in the record */
63143   int iHdr;                       /* Next unread header byte */
63144   int iField;                     /* Next unread data byte */
63145   int szField;                    /* Size of the current data field */
63146   int i;                          /* Column index */
63147   u8 *a = (u8*)pRec;              /* Typecast byte array */
63148   Mem *pMem = *ppVal;             /* Write result into this Mem object */
63149 
63150   assert( iCol>0 );
63151   iHdr = getVarint32(a, nHdr);
63152   if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
63153   iField = nHdr;
63154   for(i=0; i<=iCol; i++){
63155     iHdr += getVarint32(&a[iHdr], t);
63156     testcase( iHdr==nHdr );
63157     testcase( iHdr==nHdr+1 );
63158     if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
63159     szField = sqlite3VdbeSerialTypeLen(t);
63160     iField += szField;
63161   }
63162   testcase( iField==nRec );
63163   testcase( iField==nRec+1 );
63164   if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
63165   if( pMem==0 ){
63166     pMem = *ppVal = sqlite3ValueNew(db);
63167     if( pMem==0 ) return SQLITE_NOMEM;
63168   }
63169   sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
63170   pMem->enc = ENC(db);
63171   return SQLITE_OK;
63172 }
63173 
63174 /*
63175 ** Unless it is NULL, the argument must be an UnpackedRecord object returned
63176 ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
63177 ** the object.
63178 */
63179 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
63180   if( pRec ){
63181     int i;
63182     int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
63183     Mem *aMem = pRec->aMem;
63184     sqlite3 *db = aMem[0].db;
63185     for(i=0; i<nCol; i++){
63186       if( aMem[i].szMalloc ) sqlite3DbFree(db, aMem[i].zMalloc);
63187     }
63188     sqlite3KeyInfoUnref(pRec->pKeyInfo);
63189     sqlite3DbFree(db, pRec);
63190   }
63191 }
63192 #endif /* ifdef SQLITE_ENABLE_STAT4 */
63193 
63194 /*
63195 ** Change the string value of an sqlite3_value object
63196 */
63197 SQLITE_PRIVATE void sqlite3ValueSetStr(
63198   sqlite3_value *v,     /* Value to be set */
63199   int n,                /* Length of string z */
63200   const void *z,        /* Text of the new string */
63201   u8 enc,               /* Encoding to use */
63202   void (*xDel)(void*)   /* Destructor for the string */
63203 ){
63204   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
63205 }
63206 
63207 /*
63208 ** Free an sqlite3_value object
63209 */
63210 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
63211   if( !v ) return;
63212   sqlite3VdbeMemRelease((Mem *)v);
63213   sqlite3DbFree(((Mem*)v)->db, v);
63214 }
63215 
63216 /*
63217 ** Return the number of bytes in the sqlite3_value object assuming
63218 ** that it uses the encoding "enc"
63219 */
63220 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
63221   Mem *p = (Mem*)pVal;
63222   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
63223     if( p->flags & MEM_Zero ){
63224       return p->n + p->u.nZero;
63225     }else{
63226       return p->n;
63227     }
63228   }
63229   return 0;
63230 }
63231 
63232 /************** End of vdbemem.c *********************************************/
63233 /************** Begin file vdbeaux.c *****************************************/
63234 /*
63235 ** 2003 September 6
63236 **
63237 ** The author disclaims copyright to this source code.  In place of
63238 ** a legal notice, here is a blessing:
63239 **
63240 **    May you do good and not evil.
63241 **    May you find forgiveness for yourself and forgive others.
63242 **    May you share freely, never taking more than you give.
63243 **
63244 *************************************************************************
63245 ** This file contains code used for creating, destroying, and populating
63246 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
63247 */
63248 
63249 /*
63250 ** Create a new virtual database engine.
63251 */
63252 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
63253   sqlite3 *db = pParse->db;
63254   Vdbe *p;
63255   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
63256   if( p==0 ) return 0;
63257   p->db = db;
63258   if( db->pVdbe ){
63259     db->pVdbe->pPrev = p;
63260   }
63261   p->pNext = db->pVdbe;
63262   p->pPrev = 0;
63263   db->pVdbe = p;
63264   p->magic = VDBE_MAGIC_INIT;
63265   p->pParse = pParse;
63266   assert( pParse->aLabel==0 );
63267   assert( pParse->nLabel==0 );
63268   assert( pParse->nOpAlloc==0 );
63269   return p;
63270 }
63271 
63272 /*
63273 ** Remember the SQL string for a prepared statement.
63274 */
63275 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
63276   assert( isPrepareV2==1 || isPrepareV2==0 );
63277   if( p==0 ) return;
63278 #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
63279   if( !isPrepareV2 ) return;
63280 #endif
63281   assert( p->zSql==0 );
63282   p->zSql = sqlite3DbStrNDup(p->db, z, n);
63283   p->isPrepareV2 = (u8)isPrepareV2;
63284 }
63285 
63286 /*
63287 ** Return the SQL associated with a prepared statement
63288 */
63289 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
63290   Vdbe *p = (Vdbe *)pStmt;
63291   return (p && p->isPrepareV2) ? p->zSql : 0;
63292 }
63293 
63294 /*
63295 ** Swap all content between two VDBE structures.
63296 */
63297 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
63298   Vdbe tmp, *pTmp;
63299   char *zTmp;
63300   tmp = *pA;
63301   *pA = *pB;
63302   *pB = tmp;
63303   pTmp = pA->pNext;
63304   pA->pNext = pB->pNext;
63305   pB->pNext = pTmp;
63306   pTmp = pA->pPrev;
63307   pA->pPrev = pB->pPrev;
63308   pB->pPrev = pTmp;
63309   zTmp = pA->zSql;
63310   pA->zSql = pB->zSql;
63311   pB->zSql = zTmp;
63312   pB->isPrepareV2 = pA->isPrepareV2;
63313 }
63314 
63315 /*
63316 ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
63317 ** than its current size. nOp is guaranteed to be less than or equal
63318 ** to 1024/sizeof(Op).
63319 **
63320 ** If an out-of-memory error occurs while resizing the array, return
63321 ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
63322 ** unchanged (this is so that any opcodes already allocated can be
63323 ** correctly deallocated along with the rest of the Vdbe).
63324 */
63325 static int growOpArray(Vdbe *v, int nOp){
63326   VdbeOp *pNew;
63327   Parse *p = v->pParse;
63328 
63329   /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
63330   ** more frequent reallocs and hence provide more opportunities for
63331   ** simulated OOM faults.  SQLITE_TEST_REALLOC_STRESS is generally used
63332   ** during testing only.  With SQLITE_TEST_REALLOC_STRESS grow the op array
63333   ** by the minimum* amount required until the size reaches 512.  Normal
63334   ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
63335   ** size of the op array or add 1KB of space, whichever is smaller. */
63336 #ifdef SQLITE_TEST_REALLOC_STRESS
63337   int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
63338 #else
63339   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
63340   UNUSED_PARAMETER(nOp);
63341 #endif
63342 
63343   assert( nOp<=(1024/sizeof(Op)) );
63344   assert( nNew>=(p->nOpAlloc+nOp) );
63345   pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
63346   if( pNew ){
63347     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
63348     v->aOp = pNew;
63349   }
63350   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
63351 }
63352 
63353 #ifdef SQLITE_DEBUG
63354 /* This routine is just a convenient place to set a breakpoint that will
63355 ** fire after each opcode is inserted and displayed using
63356 ** "PRAGMA vdbe_addoptrace=on".
63357 */
63358 static void test_addop_breakpoint(void){
63359   static int n = 0;
63360   n++;
63361 }
63362 #endif
63363 
63364 /*
63365 ** Add a new instruction to the list of instructions current in the
63366 ** VDBE.  Return the address of the new instruction.
63367 **
63368 ** Parameters:
63369 **
63370 **    p               Pointer to the VDBE
63371 **
63372 **    op              The opcode for this instruction
63373 **
63374 **    p1, p2, p3      Operands
63375 **
63376 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
63377 ** the sqlite3VdbeChangeP4() function to change the value of the P4
63378 ** operand.
63379 */
63380 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
63381   int i;
63382   VdbeOp *pOp;
63383 
63384   i = p->nOp;
63385   assert( p->magic==VDBE_MAGIC_INIT );
63386   assert( op>0 && op<0xff );
63387   if( p->pParse->nOpAlloc<=i ){
63388     if( growOpArray(p, 1) ){
63389       return 1;
63390     }
63391   }
63392   p->nOp++;
63393   pOp = &p->aOp[i];
63394   pOp->opcode = (u8)op;
63395   pOp->p5 = 0;
63396   pOp->p1 = p1;
63397   pOp->p2 = p2;
63398   pOp->p3 = p3;
63399   pOp->p4.p = 0;
63400   pOp->p4type = P4_NOTUSED;
63401 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
63402   pOp->zComment = 0;
63403 #endif
63404 #ifdef SQLITE_DEBUG
63405   if( p->db->flags & SQLITE_VdbeAddopTrace ){
63406     int jj, kk;
63407     Parse *pParse = p->pParse;
63408     for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
63409       struct yColCache *x = pParse->aColCache + jj;
63410       if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
63411       printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
63412       kk++;
63413     }
63414     if( kk ) printf("\n");
63415     sqlite3VdbePrintOp(0, i, &p->aOp[i]);
63416     test_addop_breakpoint();
63417   }
63418 #endif
63419 #ifdef VDBE_PROFILE
63420   pOp->cycles = 0;
63421   pOp->cnt = 0;
63422 #endif
63423 #ifdef SQLITE_VDBE_COVERAGE
63424   pOp->iSrcLine = 0;
63425 #endif
63426   return i;
63427 }
63428 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
63429   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
63430 }
63431 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
63432   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
63433 }
63434 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
63435   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
63436 }
63437 
63438 
63439 /*
63440 ** Add an opcode that includes the p4 value as a pointer.
63441 */
63442 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
63443   Vdbe *p,            /* Add the opcode to this VM */
63444   int op,             /* The new opcode */
63445   int p1,             /* The P1 operand */
63446   int p2,             /* The P2 operand */
63447   int p3,             /* The P3 operand */
63448   const char *zP4,    /* The P4 operand */
63449   int p4type          /* P4 operand type */
63450 ){
63451   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
63452   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
63453   return addr;
63454 }
63455 
63456 /*
63457 ** Add an OP_ParseSchema opcode.  This routine is broken out from
63458 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
63459 ** as having been used.
63460 **
63461 ** The zWhere string must have been obtained from sqlite3_malloc().
63462 ** This routine will take ownership of the allocated memory.
63463 */
63464 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
63465   int j;
63466   int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
63467   sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
63468   for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
63469 }
63470 
63471 /*
63472 ** Add an opcode that includes the p4 value as an integer.
63473 */
63474 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
63475   Vdbe *p,            /* Add the opcode to this VM */
63476   int op,             /* The new opcode */
63477   int p1,             /* The P1 operand */
63478   int p2,             /* The P2 operand */
63479   int p3,             /* The P3 operand */
63480   int p4              /* The P4 operand as an integer */
63481 ){
63482   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
63483   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
63484   return addr;
63485 }
63486 
63487 /*
63488 ** Create a new symbolic label for an instruction that has yet to be
63489 ** coded.  The symbolic label is really just a negative number.  The
63490 ** label can be used as the P2 value of an operation.  Later, when
63491 ** the label is resolved to a specific address, the VDBE will scan
63492 ** through its operation list and change all values of P2 which match
63493 ** the label into the resolved address.
63494 **
63495 ** The VDBE knows that a P2 value is a label because labels are
63496 ** always negative and P2 values are suppose to be non-negative.
63497 ** Hence, a negative P2 value is a label that has yet to be resolved.
63498 **
63499 ** Zero is returned if a malloc() fails.
63500 */
63501 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
63502   Parse *p = v->pParse;
63503   int i = p->nLabel++;
63504   assert( v->magic==VDBE_MAGIC_INIT );
63505   if( (i & (i-1))==0 ){
63506     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
63507                                        (i*2+1)*sizeof(p->aLabel[0]));
63508   }
63509   if( p->aLabel ){
63510     p->aLabel[i] = -1;
63511   }
63512   return -1-i;
63513 }
63514 
63515 /*
63516 ** Resolve label "x" to be the address of the next instruction to
63517 ** be inserted.  The parameter "x" must have been obtained from
63518 ** a prior call to sqlite3VdbeMakeLabel().
63519 */
63520 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
63521   Parse *p = v->pParse;
63522   int j = -1-x;
63523   assert( v->magic==VDBE_MAGIC_INIT );
63524   assert( j<p->nLabel );
63525   if( ALWAYS(j>=0) && p->aLabel ){
63526     p->aLabel[j] = v->nOp;
63527   }
63528   p->iFixedOp = v->nOp - 1;
63529 }
63530 
63531 /*
63532 ** Mark the VDBE as one that can only be run one time.
63533 */
63534 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
63535   p->runOnlyOnce = 1;
63536 }
63537 
63538 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
63539 
63540 /*
63541 ** The following type and function are used to iterate through all opcodes
63542 ** in a Vdbe main program and each of the sub-programs (triggers) it may
63543 ** invoke directly or indirectly. It should be used as follows:
63544 **
63545 **   Op *pOp;
63546 **   VdbeOpIter sIter;
63547 **
63548 **   memset(&sIter, 0, sizeof(sIter));
63549 **   sIter.v = v;                            // v is of type Vdbe*
63550 **   while( (pOp = opIterNext(&sIter)) ){
63551 **     // Do something with pOp
63552 **   }
63553 **   sqlite3DbFree(v->db, sIter.apSub);
63554 **
63555 */
63556 typedef struct VdbeOpIter VdbeOpIter;
63557 struct VdbeOpIter {
63558   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
63559   SubProgram **apSub;        /* Array of subprograms */
63560   int nSub;                  /* Number of entries in apSub */
63561   int iAddr;                 /* Address of next instruction to return */
63562   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
63563 };
63564 static Op *opIterNext(VdbeOpIter *p){
63565   Vdbe *v = p->v;
63566   Op *pRet = 0;
63567   Op *aOp;
63568   int nOp;
63569 
63570   if( p->iSub<=p->nSub ){
63571 
63572     if( p->iSub==0 ){
63573       aOp = v->aOp;
63574       nOp = v->nOp;
63575     }else{
63576       aOp = p->apSub[p->iSub-1]->aOp;
63577       nOp = p->apSub[p->iSub-1]->nOp;
63578     }
63579     assert( p->iAddr<nOp );
63580 
63581     pRet = &aOp[p->iAddr];
63582     p->iAddr++;
63583     if( p->iAddr==nOp ){
63584       p->iSub++;
63585       p->iAddr = 0;
63586     }
63587 
63588     if( pRet->p4type==P4_SUBPROGRAM ){
63589       int nByte = (p->nSub+1)*sizeof(SubProgram*);
63590       int j;
63591       for(j=0; j<p->nSub; j++){
63592         if( p->apSub[j]==pRet->p4.pProgram ) break;
63593       }
63594       if( j==p->nSub ){
63595         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
63596         if( !p->apSub ){
63597           pRet = 0;
63598         }else{
63599           p->apSub[p->nSub++] = pRet->p4.pProgram;
63600         }
63601       }
63602     }
63603   }
63604 
63605   return pRet;
63606 }
63607 
63608 /*
63609 ** Check if the program stored in the VM associated with pParse may
63610 ** throw an ABORT exception (causing the statement, but not entire transaction
63611 ** to be rolled back). This condition is true if the main program or any
63612 ** sub-programs contains any of the following:
63613 **
63614 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
63615 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
63616 **   *  OP_Destroy
63617 **   *  OP_VUpdate
63618 **   *  OP_VRename
63619 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
63620 **
63621 ** Then check that the value of Parse.mayAbort is true if an
63622 ** ABORT may be thrown, or false otherwise. Return true if it does
63623 ** match, or false otherwise. This function is intended to be used as
63624 ** part of an assert statement in the compiler. Similar to:
63625 **
63626 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
63627 */
63628 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
63629   int hasAbort = 0;
63630   Op *pOp;
63631   VdbeOpIter sIter;
63632   memset(&sIter, 0, sizeof(sIter));
63633   sIter.v = v;
63634 
63635   while( (pOp = opIterNext(&sIter))!=0 ){
63636     int opcode = pOp->opcode;
63637     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
63638 #ifndef SQLITE_OMIT_FOREIGN_KEY
63639      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
63640 #endif
63641      || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
63642       && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
63643     ){
63644       hasAbort = 1;
63645       break;
63646     }
63647   }
63648   sqlite3DbFree(v->db, sIter.apSub);
63649 
63650   /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
63651   ** If malloc failed, then the while() loop above may not have iterated
63652   ** through all opcodes and hasAbort may be set incorrectly. Return
63653   ** true for this case to prevent the assert() in the callers frame
63654   ** from failing.  */
63655   return ( v->db->mallocFailed || hasAbort==mayAbort );
63656 }
63657 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
63658 
63659 /*
63660 ** Loop through the program looking for P2 values that are negative
63661 ** on jump instructions.  Each such value is a label.  Resolve the
63662 ** label by setting the P2 value to its correct non-zero value.
63663 **
63664 ** This routine is called once after all opcodes have been inserted.
63665 **
63666 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
63667 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
63668 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
63669 **
63670 ** The Op.opflags field is set on all opcodes.
63671 */
63672 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
63673   int i;
63674   int nMaxArgs = *pMaxFuncArgs;
63675   Op *pOp;
63676   Parse *pParse = p->pParse;
63677   int *aLabel = pParse->aLabel;
63678   p->readOnly = 1;
63679   p->bIsReader = 0;
63680   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
63681     u8 opcode = pOp->opcode;
63682 
63683     /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
63684     ** cases from this switch! */
63685     switch( opcode ){
63686       case OP_Function:
63687       case OP_AggStep: {
63688         if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
63689         break;
63690       }
63691       case OP_Transaction: {
63692         if( pOp->p2!=0 ) p->readOnly = 0;
63693         /* fall thru */
63694       }
63695       case OP_AutoCommit:
63696       case OP_Savepoint: {
63697         p->bIsReader = 1;
63698         break;
63699       }
63700 #ifndef SQLITE_OMIT_WAL
63701       case OP_Checkpoint:
63702 #endif
63703       case OP_Vacuum:
63704       case OP_JournalMode: {
63705         p->readOnly = 0;
63706         p->bIsReader = 1;
63707         break;
63708       }
63709 #ifndef SQLITE_OMIT_VIRTUALTABLE
63710       case OP_VUpdate: {
63711         if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
63712         break;
63713       }
63714       case OP_VFilter: {
63715         int n;
63716         assert( p->nOp - i >= 3 );
63717         assert( pOp[-1].opcode==OP_Integer );
63718         n = pOp[-1].p1;
63719         if( n>nMaxArgs ) nMaxArgs = n;
63720         break;
63721       }
63722 #endif
63723       case OP_Next:
63724       case OP_NextIfOpen:
63725       case OP_SorterNext: {
63726         pOp->p4.xAdvance = sqlite3BtreeNext;
63727         pOp->p4type = P4_ADVANCE;
63728         break;
63729       }
63730       case OP_Prev:
63731       case OP_PrevIfOpen: {
63732         pOp->p4.xAdvance = sqlite3BtreePrevious;
63733         pOp->p4type = P4_ADVANCE;
63734         break;
63735       }
63736     }
63737 
63738     pOp->opflags = sqlite3OpcodeProperty[opcode];
63739     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
63740       assert( -1-pOp->p2<pParse->nLabel );
63741       pOp->p2 = aLabel[-1-pOp->p2];
63742     }
63743   }
63744   sqlite3DbFree(p->db, pParse->aLabel);
63745   pParse->aLabel = 0;
63746   pParse->nLabel = 0;
63747   *pMaxFuncArgs = nMaxArgs;
63748   assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
63749 }
63750 
63751 /*
63752 ** Return the address of the next instruction to be inserted.
63753 */
63754 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
63755   assert( p->magic==VDBE_MAGIC_INIT );
63756   return p->nOp;
63757 }
63758 
63759 /*
63760 ** This function returns a pointer to the array of opcodes associated with
63761 ** the Vdbe passed as the first argument. It is the callers responsibility
63762 ** to arrange for the returned array to be eventually freed using the
63763 ** vdbeFreeOpArray() function.
63764 **
63765 ** Before returning, *pnOp is set to the number of entries in the returned
63766 ** array. Also, *pnMaxArg is set to the larger of its current value and
63767 ** the number of entries in the Vdbe.apArg[] array required to execute the
63768 ** returned program.
63769 */
63770 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
63771   VdbeOp *aOp = p->aOp;
63772   assert( aOp && !p->db->mallocFailed );
63773 
63774   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
63775   assert( DbMaskAllZero(p->btreeMask) );
63776 
63777   resolveP2Values(p, pnMaxArg);
63778   *pnOp = p->nOp;
63779   p->aOp = 0;
63780   return aOp;
63781 }
63782 
63783 /*
63784 ** Add a whole list of operations to the operation stack.  Return the
63785 ** address of the first operation added.
63786 */
63787 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp, int iLineno){
63788   int addr;
63789   assert( p->magic==VDBE_MAGIC_INIT );
63790   if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
63791     return 0;
63792   }
63793   addr = p->nOp;
63794   if( ALWAYS(nOp>0) ){
63795     int i;
63796     VdbeOpList const *pIn = aOp;
63797     for(i=0; i<nOp; i++, pIn++){
63798       int p2 = pIn->p2;
63799       VdbeOp *pOut = &p->aOp[i+addr];
63800       pOut->opcode = pIn->opcode;
63801       pOut->p1 = pIn->p1;
63802       if( p2<0 ){
63803         assert( sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP );
63804         pOut->p2 = addr + ADDR(p2);
63805       }else{
63806         pOut->p2 = p2;
63807       }
63808       pOut->p3 = pIn->p3;
63809       pOut->p4type = P4_NOTUSED;
63810       pOut->p4.p = 0;
63811       pOut->p5 = 0;
63812 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
63813       pOut->zComment = 0;
63814 #endif
63815 #ifdef SQLITE_VDBE_COVERAGE
63816       pOut->iSrcLine = iLineno+i;
63817 #else
63818       (void)iLineno;
63819 #endif
63820 #ifdef SQLITE_DEBUG
63821       if( p->db->flags & SQLITE_VdbeAddopTrace ){
63822         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
63823       }
63824 #endif
63825     }
63826     p->nOp += nOp;
63827   }
63828   return addr;
63829 }
63830 
63831 /*
63832 ** Change the value of the P1 operand for a specific instruction.
63833 ** This routine is useful when a large program is loaded from a
63834 ** static array using sqlite3VdbeAddOpList but we want to make a
63835 ** few minor changes to the program.
63836 */
63837 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
63838   assert( p!=0 );
63839   if( ((u32)p->nOp)>addr ){
63840     p->aOp[addr].p1 = val;
63841   }
63842 }
63843 
63844 /*
63845 ** Change the value of the P2 operand for a specific instruction.
63846 ** This routine is useful for setting a jump destination.
63847 */
63848 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
63849   assert( p!=0 );
63850   if( ((u32)p->nOp)>addr ){
63851     p->aOp[addr].p2 = val;
63852   }
63853 }
63854 
63855 /*
63856 ** Change the value of the P3 operand for a specific instruction.
63857 */
63858 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
63859   assert( p!=0 );
63860   if( ((u32)p->nOp)>addr ){
63861     p->aOp[addr].p3 = val;
63862   }
63863 }
63864 
63865 /*
63866 ** Change the value of the P5 operand for the most recently
63867 ** added operation.
63868 */
63869 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
63870   assert( p!=0 );
63871   if( p->aOp ){
63872     assert( p->nOp>0 );
63873     p->aOp[p->nOp-1].p5 = val;
63874   }
63875 }
63876 
63877 /*
63878 ** Change the P2 operand of instruction addr so that it points to
63879 ** the address of the next instruction to be coded.
63880 */
63881 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
63882   sqlite3VdbeChangeP2(p, addr, p->nOp);
63883   p->pParse->iFixedOp = p->nOp - 1;
63884 }
63885 
63886 
63887 /*
63888 ** If the input FuncDef structure is ephemeral, then free it.  If
63889 ** the FuncDef is not ephermal, then do nothing.
63890 */
63891 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
63892   if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
63893     sqlite3DbFree(db, pDef);
63894   }
63895 }
63896 
63897 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
63898 
63899 /*
63900 ** Delete a P4 value if necessary.
63901 */
63902 static void freeP4(sqlite3 *db, int p4type, void *p4){
63903   if( p4 ){
63904     assert( db );
63905     switch( p4type ){
63906       case P4_REAL:
63907       case P4_INT64:
63908       case P4_DYNAMIC:
63909       case P4_INTARRAY: {
63910         sqlite3DbFree(db, p4);
63911         break;
63912       }
63913       case P4_KEYINFO: {
63914         if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
63915         break;
63916       }
63917       case P4_MPRINTF: {
63918         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
63919         break;
63920       }
63921       case P4_FUNCDEF: {
63922         freeEphemeralFunction(db, (FuncDef*)p4);
63923         break;
63924       }
63925       case P4_MEM: {
63926         if( db->pnBytesFreed==0 ){
63927           sqlite3ValueFree((sqlite3_value*)p4);
63928         }else{
63929           Mem *p = (Mem*)p4;
63930           if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
63931           sqlite3DbFree(db, p);
63932         }
63933         break;
63934       }
63935       case P4_VTAB : {
63936         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
63937         break;
63938       }
63939     }
63940   }
63941 }
63942 
63943 /*
63944 ** Free the space allocated for aOp and any p4 values allocated for the
63945 ** opcodes contained within. If aOp is not NULL it is assumed to contain
63946 ** nOp entries.
63947 */
63948 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
63949   if( aOp ){
63950     Op *pOp;
63951     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
63952       freeP4(db, pOp->p4type, pOp->p4.p);
63953 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
63954       sqlite3DbFree(db, pOp->zComment);
63955 #endif
63956     }
63957   }
63958   sqlite3DbFree(db, aOp);
63959 }
63960 
63961 /*
63962 ** Link the SubProgram object passed as the second argument into the linked
63963 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
63964 ** objects when the VM is no longer required.
63965 */
63966 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
63967   p->pNext = pVdbe->pProgram;
63968   pVdbe->pProgram = p;
63969 }
63970 
63971 /*
63972 ** Change the opcode at addr into OP_Noop
63973 */
63974 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
63975   if( addr<p->nOp ){
63976     VdbeOp *pOp = &p->aOp[addr];
63977     sqlite3 *db = p->db;
63978     freeP4(db, pOp->p4type, pOp->p4.p);
63979     memset(pOp, 0, sizeof(pOp[0]));
63980     pOp->opcode = OP_Noop;
63981     if( addr==p->nOp-1 ) p->nOp--;
63982   }
63983 }
63984 
63985 /*
63986 ** If the last opcode is "op" and it is not a jump destination,
63987 ** then remove it.  Return true if and only if an opcode was removed.
63988 */
63989 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
63990   if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
63991     sqlite3VdbeChangeToNoop(p, p->nOp-1);
63992     return 1;
63993   }else{
63994     return 0;
63995   }
63996 }
63997 
63998 /*
63999 ** Change the value of the P4 operand for a specific instruction.
64000 ** This routine is useful when a large program is loaded from a
64001 ** static array using sqlite3VdbeAddOpList but we want to make a
64002 ** few minor changes to the program.
64003 **
64004 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
64005 ** the string is made into memory obtained from sqlite3_malloc().
64006 ** A value of n==0 means copy bytes of zP4 up to and including the
64007 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
64008 **
64009 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
64010 ** to a string or structure that is guaranteed to exist for the lifetime of
64011 ** the Vdbe. In these cases we can just copy the pointer.
64012 **
64013 ** If addr<0 then change P4 on the most recently inserted instruction.
64014 */
64015 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
64016   Op *pOp;
64017   sqlite3 *db;
64018   assert( p!=0 );
64019   db = p->db;
64020   assert( p->magic==VDBE_MAGIC_INIT );
64021   if( p->aOp==0 || db->mallocFailed ){
64022     if( n!=P4_VTAB ){
64023       freeP4(db, n, (void*)*(char**)&zP4);
64024     }
64025     return;
64026   }
64027   assert( p->nOp>0 );
64028   assert( addr<p->nOp );
64029   if( addr<0 ){
64030     addr = p->nOp - 1;
64031   }
64032   pOp = &p->aOp[addr];
64033   assert( pOp->p4type==P4_NOTUSED
64034        || pOp->p4type==P4_INT32
64035        || pOp->p4type==P4_KEYINFO );
64036   freeP4(db, pOp->p4type, pOp->p4.p);
64037   pOp->p4.p = 0;
64038   if( n==P4_INT32 ){
64039     /* Note: this cast is safe, because the origin data point was an int
64040     ** that was cast to a (const char *). */
64041     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
64042     pOp->p4type = P4_INT32;
64043   }else if( zP4==0 ){
64044     pOp->p4.p = 0;
64045     pOp->p4type = P4_NOTUSED;
64046   }else if( n==P4_KEYINFO ){
64047     pOp->p4.p = (void*)zP4;
64048     pOp->p4type = P4_KEYINFO;
64049   }else if( n==P4_VTAB ){
64050     pOp->p4.p = (void*)zP4;
64051     pOp->p4type = P4_VTAB;
64052     sqlite3VtabLock((VTable *)zP4);
64053     assert( ((VTable *)zP4)->db==p->db );
64054   }else if( n<0 ){
64055     pOp->p4.p = (void*)zP4;
64056     pOp->p4type = (signed char)n;
64057   }else{
64058     if( n==0 ) n = sqlite3Strlen30(zP4);
64059     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
64060     pOp->p4type = P4_DYNAMIC;
64061   }
64062 }
64063 
64064 /*
64065 ** Set the P4 on the most recently added opcode to the KeyInfo for the
64066 ** index given.
64067 */
64068 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
64069   Vdbe *v = pParse->pVdbe;
64070   assert( v!=0 );
64071   assert( pIdx!=0 );
64072   sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
64073                       P4_KEYINFO);
64074 }
64075 
64076 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
64077 /*
64078 ** Change the comment on the most recently coded instruction.  Or
64079 ** insert a No-op and add the comment to that new instruction.  This
64080 ** makes the code easier to read during debugging.  None of this happens
64081 ** in a production build.
64082 */
64083 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
64084   assert( p->nOp>0 || p->aOp==0 );
64085   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
64086   if( p->nOp ){
64087     assert( p->aOp );
64088     sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
64089     p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
64090   }
64091 }
64092 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
64093   va_list ap;
64094   if( p ){
64095     va_start(ap, zFormat);
64096     vdbeVComment(p, zFormat, ap);
64097     va_end(ap);
64098   }
64099 }
64100 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
64101   va_list ap;
64102   if( p ){
64103     sqlite3VdbeAddOp0(p, OP_Noop);
64104     va_start(ap, zFormat);
64105     vdbeVComment(p, zFormat, ap);
64106     va_end(ap);
64107   }
64108 }
64109 #endif  /* NDEBUG */
64110 
64111 #ifdef SQLITE_VDBE_COVERAGE
64112 /*
64113 ** Set the value if the iSrcLine field for the previously coded instruction.
64114 */
64115 SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
64116   sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
64117 }
64118 #endif /* SQLITE_VDBE_COVERAGE */
64119 
64120 /*
64121 ** Return the opcode for a given address.  If the address is -1, then
64122 ** return the most recently inserted opcode.
64123 **
64124 ** If a memory allocation error has occurred prior to the calling of this
64125 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
64126 ** is readable but not writable, though it is cast to a writable value.
64127 ** The return of a dummy opcode allows the call to continue functioning
64128 ** after an OOM fault without having to check to see if the return from
64129 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
64130 ** dummy will never be written to.  This is verified by code inspection and
64131 ** by running with Valgrind.
64132 */
64133 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
64134   /* C89 specifies that the constant "dummy" will be initialized to all
64135   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
64136   static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
64137   assert( p->magic==VDBE_MAGIC_INIT );
64138   if( addr<0 ){
64139     addr = p->nOp - 1;
64140   }
64141   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
64142   if( p->db->mallocFailed ){
64143     return (VdbeOp*)&dummy;
64144   }else{
64145     return &p->aOp[addr];
64146   }
64147 }
64148 
64149 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
64150 /*
64151 ** Return an integer value for one of the parameters to the opcode pOp
64152 ** determined by character c.
64153 */
64154 static int translateP(char c, const Op *pOp){
64155   if( c=='1' ) return pOp->p1;
64156   if( c=='2' ) return pOp->p2;
64157   if( c=='3' ) return pOp->p3;
64158   if( c=='4' ) return pOp->p4.i;
64159   return pOp->p5;
64160 }
64161 
64162 /*
64163 ** Compute a string for the "comment" field of a VDBE opcode listing.
64164 **
64165 ** The Synopsis: field in comments in the vdbe.c source file gets converted
64166 ** to an extra string that is appended to the sqlite3OpcodeName().  In the
64167 ** absence of other comments, this synopsis becomes the comment on the opcode.
64168 ** Some translation occurs:
64169 **
64170 **       "PX"      ->  "r[X]"
64171 **       "PX@PY"   ->  "r[X..X+Y-1]"  or "r[x]" if y is 0 or 1
64172 **       "PX@PY+1" ->  "r[X..X+Y]"    or "r[x]" if y is 0
64173 **       "PY..PY"  ->  "r[X..Y]"      or "r[x]" if y<=x
64174 */
64175 static int displayComment(
64176   const Op *pOp,     /* The opcode to be commented */
64177   const char *zP4,   /* Previously obtained value for P4 */
64178   char *zTemp,       /* Write result here */
64179   int nTemp          /* Space available in zTemp[] */
64180 ){
64181   const char *zOpName;
64182   const char *zSynopsis;
64183   int nOpName;
64184   int ii, jj;
64185   zOpName = sqlite3OpcodeName(pOp->opcode);
64186   nOpName = sqlite3Strlen30(zOpName);
64187   if( zOpName[nOpName+1] ){
64188     int seenCom = 0;
64189     char c;
64190     zSynopsis = zOpName += nOpName + 1;
64191     for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
64192       if( c=='P' ){
64193         c = zSynopsis[++ii];
64194         if( c=='4' ){
64195           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
64196         }else if( c=='X' ){
64197           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
64198           seenCom = 1;
64199         }else{
64200           int v1 = translateP(c, pOp);
64201           int v2;
64202           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
64203           if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
64204             ii += 3;
64205             jj += sqlite3Strlen30(zTemp+jj);
64206             v2 = translateP(zSynopsis[ii], pOp);
64207             if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
64208               ii += 2;
64209               v2++;
64210             }
64211             if( v2>1 ){
64212               sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
64213             }
64214           }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
64215             ii += 4;
64216           }
64217         }
64218         jj += sqlite3Strlen30(zTemp+jj);
64219       }else{
64220         zTemp[jj++] = c;
64221       }
64222     }
64223     if( !seenCom && jj<nTemp-5 && pOp->zComment ){
64224       sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
64225       jj += sqlite3Strlen30(zTemp+jj);
64226     }
64227     if( jj<nTemp ) zTemp[jj] = 0;
64228   }else if( pOp->zComment ){
64229     sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
64230     jj = sqlite3Strlen30(zTemp);
64231   }else{
64232     zTemp[0] = 0;
64233     jj = 0;
64234   }
64235   return jj;
64236 }
64237 #endif /* SQLITE_DEBUG */
64238 
64239 
64240 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
64241      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
64242 /*
64243 ** Compute a string that describes the P4 parameter for an opcode.
64244 ** Use zTemp for any required temporary buffer space.
64245 */
64246 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
64247   char *zP4 = zTemp;
64248   assert( nTemp>=20 );
64249   switch( pOp->p4type ){
64250     case P4_KEYINFO: {
64251       int i, j;
64252       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
64253       assert( pKeyInfo->aSortOrder!=0 );
64254       sqlite3_snprintf(nTemp, zTemp, "k(%d", pKeyInfo->nField);
64255       i = sqlite3Strlen30(zTemp);
64256       for(j=0; j<pKeyInfo->nField; j++){
64257         CollSeq *pColl = pKeyInfo->aColl[j];
64258         const char *zColl = pColl ? pColl->zName : "nil";
64259         int n = sqlite3Strlen30(zColl);
64260         if( n==6 && memcmp(zColl,"BINARY",6)==0 ){
64261           zColl = "B";
64262           n = 1;
64263         }
64264         if( i+n>nTemp-6 ){
64265           memcpy(&zTemp[i],",...",4);
64266           break;
64267         }
64268         zTemp[i++] = ',';
64269         if( pKeyInfo->aSortOrder[j] ){
64270           zTemp[i++] = '-';
64271         }
64272         memcpy(&zTemp[i], zColl, n+1);
64273         i += n;
64274       }
64275       zTemp[i++] = ')';
64276       zTemp[i] = 0;
64277       assert( i<nTemp );
64278       break;
64279     }
64280     case P4_COLLSEQ: {
64281       CollSeq *pColl = pOp->p4.pColl;
64282       sqlite3_snprintf(nTemp, zTemp, "(%.20s)", pColl->zName);
64283       break;
64284     }
64285     case P4_FUNCDEF: {
64286       FuncDef *pDef = pOp->p4.pFunc;
64287       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
64288       break;
64289     }
64290     case P4_INT64: {
64291       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
64292       break;
64293     }
64294     case P4_INT32: {
64295       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
64296       break;
64297     }
64298     case P4_REAL: {
64299       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
64300       break;
64301     }
64302     case P4_MEM: {
64303       Mem *pMem = pOp->p4.pMem;
64304       if( pMem->flags & MEM_Str ){
64305         zP4 = pMem->z;
64306       }else if( pMem->flags & MEM_Int ){
64307         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
64308       }else if( pMem->flags & MEM_Real ){
64309         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->u.r);
64310       }else if( pMem->flags & MEM_Null ){
64311         sqlite3_snprintf(nTemp, zTemp, "NULL");
64312       }else{
64313         assert( pMem->flags & MEM_Blob );
64314         zP4 = "(blob)";
64315       }
64316       break;
64317     }
64318 #ifndef SQLITE_OMIT_VIRTUALTABLE
64319     case P4_VTAB: {
64320       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
64321       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
64322       break;
64323     }
64324 #endif
64325     case P4_INTARRAY: {
64326       sqlite3_snprintf(nTemp, zTemp, "intarray");
64327       break;
64328     }
64329     case P4_SUBPROGRAM: {
64330       sqlite3_snprintf(nTemp, zTemp, "program");
64331       break;
64332     }
64333     case P4_ADVANCE: {
64334       zTemp[0] = 0;
64335       break;
64336     }
64337     default: {
64338       zP4 = pOp->p4.z;
64339       if( zP4==0 ){
64340         zP4 = zTemp;
64341         zTemp[0] = 0;
64342       }
64343     }
64344   }
64345   assert( zP4!=0 );
64346   return zP4;
64347 }
64348 #endif
64349 
64350 /*
64351 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
64352 **
64353 ** The prepared statements need to know in advance the complete set of
64354 ** attached databases that will be use.  A mask of these databases
64355 ** is maintained in p->btreeMask.  The p->lockMask value is the subset of
64356 ** p->btreeMask of databases that will require a lock.
64357 */
64358 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
64359   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
64360   assert( i<(int)sizeof(p->btreeMask)*8 );
64361   DbMaskSet(p->btreeMask, i);
64362   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
64363     DbMaskSet(p->lockMask, i);
64364   }
64365 }
64366 
64367 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
64368 /*
64369 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
64370 ** this routine obtains the mutex associated with each BtShared structure
64371 ** that may be accessed by the VM passed as an argument. In doing so it also
64372 ** sets the BtShared.db member of each of the BtShared structures, ensuring
64373 ** that the correct busy-handler callback is invoked if required.
64374 **
64375 ** If SQLite is not threadsafe but does support shared-cache mode, then
64376 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
64377 ** of all of BtShared structures accessible via the database handle
64378 ** associated with the VM.
64379 **
64380 ** If SQLite is not threadsafe and does not support shared-cache mode, this
64381 ** function is a no-op.
64382 **
64383 ** The p->btreeMask field is a bitmask of all btrees that the prepared
64384 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
64385 ** corresponding to btrees that use shared cache.  Then the runtime of
64386 ** this routine is N*N.  But as N is rarely more than 1, this should not
64387 ** be a problem.
64388 */
64389 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
64390   int i;
64391   sqlite3 *db;
64392   Db *aDb;
64393   int nDb;
64394   if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
64395   db = p->db;
64396   aDb = db->aDb;
64397   nDb = db->nDb;
64398   for(i=0; i<nDb; i++){
64399     if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
64400       sqlite3BtreeEnter(aDb[i].pBt);
64401     }
64402   }
64403 }
64404 #endif
64405 
64406 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
64407 /*
64408 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
64409 */
64410 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
64411   int i;
64412   sqlite3 *db;
64413   Db *aDb;
64414   int nDb;
64415   if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
64416   db = p->db;
64417   aDb = db->aDb;
64418   nDb = db->nDb;
64419   for(i=0; i<nDb; i++){
64420     if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
64421       sqlite3BtreeLeave(aDb[i].pBt);
64422     }
64423   }
64424 }
64425 #endif
64426 
64427 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
64428 /*
64429 ** Print a single opcode.  This routine is used for debugging only.
64430 */
64431 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
64432   char *zP4;
64433   char zPtr[50];
64434   char zCom[100];
64435   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
64436   if( pOut==0 ) pOut = stdout;
64437   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
64438 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
64439   displayComment(pOp, zP4, zCom, sizeof(zCom));
64440 #else
64441   zCom[0] = 0;
64442 #endif
64443   /* NB:  The sqlite3OpcodeName() function is implemented by code created
64444   ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
64445   ** information from the vdbe.c source text */
64446   fprintf(pOut, zFormat1, pc,
64447       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
64448       zCom
64449   );
64450   fflush(pOut);
64451 }
64452 #endif
64453 
64454 /*
64455 ** Release an array of N Mem elements
64456 */
64457 static void releaseMemArray(Mem *p, int N){
64458   if( p && N ){
64459     Mem *pEnd = &p[N];
64460     sqlite3 *db = p->db;
64461     u8 malloc_failed = db->mallocFailed;
64462     if( db->pnBytesFreed ){
64463       do{
64464         if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
64465       }while( (++p)<pEnd );
64466       return;
64467     }
64468     do{
64469       assert( (&p[1])==pEnd || p[0].db==p[1].db );
64470       assert( sqlite3VdbeCheckMemInvariants(p) );
64471 
64472       /* This block is really an inlined version of sqlite3VdbeMemRelease()
64473       ** that takes advantage of the fact that the memory cell value is
64474       ** being set to NULL after releasing any dynamic resources.
64475       **
64476       ** The justification for duplicating code is that according to
64477       ** callgrind, this causes a certain test case to hit the CPU 4.7
64478       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
64479       ** sqlite3MemRelease() were called from here. With -O2, this jumps
64480       ** to 6.6 percent. The test case is inserting 1000 rows into a table
64481       ** with no indexes using a single prepared INSERT statement, bind()
64482       ** and reset(). Inserts are grouped into a transaction.
64483       */
64484       testcase( p->flags & MEM_Agg );
64485       testcase( p->flags & MEM_Dyn );
64486       testcase( p->flags & MEM_Frame );
64487       testcase( p->flags & MEM_RowSet );
64488       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
64489         sqlite3VdbeMemRelease(p);
64490       }else if( p->szMalloc ){
64491         sqlite3DbFree(db, p->zMalloc);
64492         p->szMalloc = 0;
64493       }
64494 
64495       p->flags = MEM_Undefined;
64496     }while( (++p)<pEnd );
64497     db->mallocFailed = malloc_failed;
64498   }
64499 }
64500 
64501 /*
64502 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
64503 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
64504 */
64505 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
64506   int i;
64507   Mem *aMem = VdbeFrameMem(p);
64508   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
64509   for(i=0; i<p->nChildCsr; i++){
64510     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
64511   }
64512   releaseMemArray(aMem, p->nChildMem);
64513   sqlite3DbFree(p->v->db, p);
64514 }
64515 
64516 #ifndef SQLITE_OMIT_EXPLAIN
64517 /*
64518 ** Give a listing of the program in the virtual machine.
64519 **
64520 ** The interface is the same as sqlite3VdbeExec().  But instead of
64521 ** running the code, it invokes the callback once for each instruction.
64522 ** This feature is used to implement "EXPLAIN".
64523 **
64524 ** When p->explain==1, each instruction is listed.  When
64525 ** p->explain==2, only OP_Explain instructions are listed and these
64526 ** are shown in a different format.  p->explain==2 is used to implement
64527 ** EXPLAIN QUERY PLAN.
64528 **
64529 ** When p->explain==1, first the main program is listed, then each of
64530 ** the trigger subprograms are listed one by one.
64531 */
64532 SQLITE_PRIVATE int sqlite3VdbeList(
64533   Vdbe *p                   /* The VDBE */
64534 ){
64535   int nRow;                            /* Stop when row count reaches this */
64536   int nSub = 0;                        /* Number of sub-vdbes seen so far */
64537   SubProgram **apSub = 0;              /* Array of sub-vdbes */
64538   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
64539   sqlite3 *db = p->db;                 /* The database connection */
64540   int i;                               /* Loop counter */
64541   int rc = SQLITE_OK;                  /* Return code */
64542   Mem *pMem = &p->aMem[1];             /* First Mem of result set */
64543 
64544   assert( p->explain );
64545   assert( p->magic==VDBE_MAGIC_RUN );
64546   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
64547 
64548   /* Even though this opcode does not use dynamic strings for
64549   ** the result, result columns may become dynamic if the user calls
64550   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
64551   */
64552   releaseMemArray(pMem, 8);
64553   p->pResultSet = 0;
64554 
64555   if( p->rc==SQLITE_NOMEM ){
64556     /* This happens if a malloc() inside a call to sqlite3_column_text() or
64557     ** sqlite3_column_text16() failed.  */
64558     db->mallocFailed = 1;
64559     return SQLITE_ERROR;
64560   }
64561 
64562   /* When the number of output rows reaches nRow, that means the
64563   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
64564   ** nRow is the sum of the number of rows in the main program, plus
64565   ** the sum of the number of rows in all trigger subprograms encountered
64566   ** so far.  The nRow value will increase as new trigger subprograms are
64567   ** encountered, but p->pc will eventually catch up to nRow.
64568   */
64569   nRow = p->nOp;
64570   if( p->explain==1 ){
64571     /* The first 8 memory cells are used for the result set.  So we will
64572     ** commandeer the 9th cell to use as storage for an array of pointers
64573     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
64574     ** cells.  */
64575     assert( p->nMem>9 );
64576     pSub = &p->aMem[9];
64577     if( pSub->flags&MEM_Blob ){
64578       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
64579       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
64580       nSub = pSub->n/sizeof(Vdbe*);
64581       apSub = (SubProgram **)pSub->z;
64582     }
64583     for(i=0; i<nSub; i++){
64584       nRow += apSub[i]->nOp;
64585     }
64586   }
64587 
64588   do{
64589     i = p->pc++;
64590   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
64591   if( i>=nRow ){
64592     p->rc = SQLITE_OK;
64593     rc = SQLITE_DONE;
64594   }else if( db->u1.isInterrupted ){
64595     p->rc = SQLITE_INTERRUPT;
64596     rc = SQLITE_ERROR;
64597     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
64598   }else{
64599     char *zP4;
64600     Op *pOp;
64601     if( i<p->nOp ){
64602       /* The output line number is small enough that we are still in the
64603       ** main program. */
64604       pOp = &p->aOp[i];
64605     }else{
64606       /* We are currently listing subprograms.  Figure out which one and
64607       ** pick up the appropriate opcode. */
64608       int j;
64609       i -= p->nOp;
64610       for(j=0; i>=apSub[j]->nOp; j++){
64611         i -= apSub[j]->nOp;
64612       }
64613       pOp = &apSub[j]->aOp[i];
64614     }
64615     if( p->explain==1 ){
64616       pMem->flags = MEM_Int;
64617       pMem->u.i = i;                                /* Program counter */
64618       pMem++;
64619 
64620       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
64621       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
64622       assert( pMem->z!=0 );
64623       pMem->n = sqlite3Strlen30(pMem->z);
64624       pMem->enc = SQLITE_UTF8;
64625       pMem++;
64626 
64627       /* When an OP_Program opcode is encounter (the only opcode that has
64628       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
64629       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
64630       ** has not already been seen.
64631       */
64632       if( pOp->p4type==P4_SUBPROGRAM ){
64633         int nByte = (nSub+1)*sizeof(SubProgram*);
64634         int j;
64635         for(j=0; j<nSub; j++){
64636           if( apSub[j]==pOp->p4.pProgram ) break;
64637         }
64638         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
64639           apSub = (SubProgram **)pSub->z;
64640           apSub[nSub++] = pOp->p4.pProgram;
64641           pSub->flags |= MEM_Blob;
64642           pSub->n = nSub*sizeof(SubProgram*);
64643         }
64644       }
64645     }
64646 
64647     pMem->flags = MEM_Int;
64648     pMem->u.i = pOp->p1;                          /* P1 */
64649     pMem++;
64650 
64651     pMem->flags = MEM_Int;
64652     pMem->u.i = pOp->p2;                          /* P2 */
64653     pMem++;
64654 
64655     pMem->flags = MEM_Int;
64656     pMem->u.i = pOp->p3;                          /* P3 */
64657     pMem++;
64658 
64659     if( sqlite3VdbeMemClearAndResize(pMem, 32) ){ /* P4 */
64660       assert( p->db->mallocFailed );
64661       return SQLITE_ERROR;
64662     }
64663     pMem->flags = MEM_Str|MEM_Term;
64664     zP4 = displayP4(pOp, pMem->z, 32);
64665     if( zP4!=pMem->z ){
64666       sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
64667     }else{
64668       assert( pMem->z!=0 );
64669       pMem->n = sqlite3Strlen30(pMem->z);
64670       pMem->enc = SQLITE_UTF8;
64671     }
64672     pMem++;
64673 
64674     if( p->explain==1 ){
64675       if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
64676         assert( p->db->mallocFailed );
64677         return SQLITE_ERROR;
64678       }
64679       pMem->flags = MEM_Str|MEM_Term;
64680       pMem->n = 2;
64681       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
64682       pMem->enc = SQLITE_UTF8;
64683       pMem++;
64684 
64685 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
64686       if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
64687         assert( p->db->mallocFailed );
64688         return SQLITE_ERROR;
64689       }
64690       pMem->flags = MEM_Str|MEM_Term;
64691       pMem->n = displayComment(pOp, zP4, pMem->z, 500);
64692       pMem->enc = SQLITE_UTF8;
64693 #else
64694       pMem->flags = MEM_Null;                       /* Comment */
64695 #endif
64696     }
64697 
64698     p->nResColumn = 8 - 4*(p->explain-1);
64699     p->pResultSet = &p->aMem[1];
64700     p->rc = SQLITE_OK;
64701     rc = SQLITE_ROW;
64702   }
64703   return rc;
64704 }
64705 #endif /* SQLITE_OMIT_EXPLAIN */
64706 
64707 #ifdef SQLITE_DEBUG
64708 /*
64709 ** Print the SQL that was used to generate a VDBE program.
64710 */
64711 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
64712   const char *z = 0;
64713   if( p->zSql ){
64714     z = p->zSql;
64715   }else if( p->nOp>=1 ){
64716     const VdbeOp *pOp = &p->aOp[0];
64717     if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
64718       z = pOp->p4.z;
64719       while( sqlite3Isspace(*z) ) z++;
64720     }
64721   }
64722   if( z ) printf("SQL: [%s]\n", z);
64723 }
64724 #endif
64725 
64726 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
64727 /*
64728 ** Print an IOTRACE message showing SQL content.
64729 */
64730 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
64731   int nOp = p->nOp;
64732   VdbeOp *pOp;
64733   if( sqlite3IoTrace==0 ) return;
64734   if( nOp<1 ) return;
64735   pOp = &p->aOp[0];
64736   if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
64737     int i, j;
64738     char z[1000];
64739     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
64740     for(i=0; sqlite3Isspace(z[i]); i++){}
64741     for(j=0; z[i]; i++){
64742       if( sqlite3Isspace(z[i]) ){
64743         if( z[i-1]!=' ' ){
64744           z[j++] = ' ';
64745         }
64746       }else{
64747         z[j++] = z[i];
64748       }
64749     }
64750     z[j] = 0;
64751     sqlite3IoTrace("SQL %s\n", z);
64752   }
64753 }
64754 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
64755 
64756 /*
64757 ** Allocate space from a fixed size buffer and return a pointer to
64758 ** that space.  If insufficient space is available, return NULL.
64759 **
64760 ** The pBuf parameter is the initial value of a pointer which will
64761 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
64762 ** NULL, it means that memory space has already been allocated and that
64763 ** this routine should not allocate any new memory.  When pBuf is not
64764 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
64765 ** is NULL.
64766 **
64767 ** nByte is the number of bytes of space needed.
64768 **
64769 ** *ppFrom points to available space and pEnd points to the end of the
64770 ** available space.  When space is allocated, *ppFrom is advanced past
64771 ** the end of the allocated space.
64772 **
64773 ** *pnByte is a counter of the number of bytes of space that have failed
64774 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
64775 ** request, then increment *pnByte by the amount of the request.
64776 */
64777 static void *allocSpace(
64778   void *pBuf,          /* Where return pointer will be stored */
64779   int nByte,           /* Number of bytes to allocate */
64780   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
64781   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
64782   int *pnByte          /* If allocation cannot be made, increment *pnByte */
64783 ){
64784   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
64785   if( pBuf ) return pBuf;
64786   nByte = ROUND8(nByte);
64787   if( &(*ppFrom)[nByte] <= pEnd ){
64788     pBuf = (void*)*ppFrom;
64789     *ppFrom += nByte;
64790   }else{
64791     *pnByte += nByte;
64792   }
64793   return pBuf;
64794 }
64795 
64796 /*
64797 ** Rewind the VDBE back to the beginning in preparation for
64798 ** running it.
64799 */
64800 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
64801 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
64802   int i;
64803 #endif
64804   assert( p!=0 );
64805   assert( p->magic==VDBE_MAGIC_INIT );
64806 
64807   /* There should be at least one opcode.
64808   */
64809   assert( p->nOp>0 );
64810 
64811   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
64812   p->magic = VDBE_MAGIC_RUN;
64813 
64814 #ifdef SQLITE_DEBUG
64815   for(i=1; i<p->nMem; i++){
64816     assert( p->aMem[i].db==p->db );
64817   }
64818 #endif
64819   p->pc = -1;
64820   p->rc = SQLITE_OK;
64821   p->errorAction = OE_Abort;
64822   p->magic = VDBE_MAGIC_RUN;
64823   p->nChange = 0;
64824   p->cacheCtr = 1;
64825   p->minWriteFileFormat = 255;
64826   p->iStatement = 0;
64827   p->nFkConstraint = 0;
64828 #ifdef VDBE_PROFILE
64829   for(i=0; i<p->nOp; i++){
64830     p->aOp[i].cnt = 0;
64831     p->aOp[i].cycles = 0;
64832   }
64833 #endif
64834 }
64835 
64836 /*
64837 ** Prepare a virtual machine for execution for the first time after
64838 ** creating the virtual machine.  This involves things such
64839 ** as allocating registers and initializing the program counter.
64840 ** After the VDBE has be prepped, it can be executed by one or more
64841 ** calls to sqlite3VdbeExec().
64842 **
64843 ** This function may be called exactly once on each virtual machine.
64844 ** After this routine is called the VM has been "packaged" and is ready
64845 ** to run.  After this routine is called, further calls to
64846 ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
64847 ** the Vdbe from the Parse object that helped generate it so that the
64848 ** the Vdbe becomes an independent entity and the Parse object can be
64849 ** destroyed.
64850 **
64851 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
64852 ** to its initial state after it has been run.
64853 */
64854 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
64855   Vdbe *p,                       /* The VDBE */
64856   Parse *pParse                  /* Parsing context */
64857 ){
64858   sqlite3 *db;                   /* The database connection */
64859   int nVar;                      /* Number of parameters */
64860   int nMem;                      /* Number of VM memory registers */
64861   int nCursor;                   /* Number of cursors required */
64862   int nArg;                      /* Number of arguments in subprograms */
64863   int nOnce;                     /* Number of OP_Once instructions */
64864   int n;                         /* Loop counter */
64865   u8 *zCsr;                      /* Memory available for allocation */
64866   u8 *zEnd;                      /* First byte past allocated memory */
64867   int nByte;                     /* How much extra memory is needed */
64868 
64869   assert( p!=0 );
64870   assert( p->nOp>0 );
64871   assert( pParse!=0 );
64872   assert( p->magic==VDBE_MAGIC_INIT );
64873   assert( pParse==p->pParse );
64874   db = p->db;
64875   assert( db->mallocFailed==0 );
64876   nVar = pParse->nVar;
64877   nMem = pParse->nMem;
64878   nCursor = pParse->nTab;
64879   nArg = pParse->nMaxArg;
64880   nOnce = pParse->nOnce;
64881   if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
64882 
64883   /* For each cursor required, also allocate a memory cell. Memory
64884   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
64885   ** the vdbe program. Instead they are used to allocate space for
64886   ** VdbeCursor/BtCursor structures. The blob of memory associated with
64887   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
64888   ** stores the blob of memory associated with cursor 1, etc.
64889   **
64890   ** See also: allocateCursor().
64891   */
64892   nMem += nCursor;
64893 
64894   /* Allocate space for memory registers, SQL variables, VDBE cursors and
64895   ** an array to marshal SQL function arguments in.
64896   */
64897   zCsr = (u8*)&p->aOp[p->nOp];            /* Memory avaliable for allocation */
64898   zEnd = (u8*)&p->aOp[pParse->nOpAlloc];  /* First byte past end of zCsr[] */
64899 
64900   resolveP2Values(p, &nArg);
64901   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
64902   if( pParse->explain && nMem<10 ){
64903     nMem = 10;
64904   }
64905   memset(zCsr, 0, zEnd-zCsr);
64906   zCsr += (zCsr - (u8*)0)&7;
64907   assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
64908   p->expired = 0;
64909 
64910   /* Memory for registers, parameters, cursor, etc, is allocated in two
64911   ** passes.  On the first pass, we try to reuse unused space at the
64912   ** end of the opcode array.  If we are unable to satisfy all memory
64913   ** requirements by reusing the opcode array tail, then the second
64914   ** pass will fill in the rest using a fresh allocation.
64915   **
64916   ** This two-pass approach that reuses as much memory as possible from
64917   ** the leftover space at the end of the opcode array can significantly
64918   ** reduce the amount of memory held by a prepared statement.
64919   */
64920   do {
64921     nByte = 0;
64922     p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
64923     p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
64924     p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
64925     p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
64926     p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
64927                           &zCsr, zEnd, &nByte);
64928     p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
64929     if( nByte ){
64930       p->pFree = sqlite3DbMallocZero(db, nByte);
64931     }
64932     zCsr = p->pFree;
64933     zEnd = &zCsr[nByte];
64934   }while( nByte && !db->mallocFailed );
64935 
64936   p->nCursor = nCursor;
64937   p->nOnceFlag = nOnce;
64938   if( p->aVar ){
64939     p->nVar = (ynVar)nVar;
64940     for(n=0; n<nVar; n++){
64941       p->aVar[n].flags = MEM_Null;
64942       p->aVar[n].db = db;
64943     }
64944   }
64945   if( p->azVar ){
64946     p->nzVar = pParse->nzVar;
64947     memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
64948     memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
64949   }
64950   if( p->aMem ){
64951     p->aMem--;                      /* aMem[] goes from 1..nMem */
64952     p->nMem = nMem;                 /*       not from 0..nMem-1 */
64953     for(n=1; n<=nMem; n++){
64954       p->aMem[n].flags = MEM_Undefined;
64955       p->aMem[n].db = db;
64956     }
64957   }
64958   p->explain = pParse->explain;
64959   sqlite3VdbeRewind(p);
64960 }
64961 
64962 /*
64963 ** Close a VDBE cursor and release all the resources that cursor
64964 ** happens to hold.
64965 */
64966 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
64967   if( pCx==0 ){
64968     return;
64969   }
64970   sqlite3VdbeSorterClose(p->db, pCx);
64971   if( pCx->pBt ){
64972     sqlite3BtreeClose(pCx->pBt);
64973     /* The pCx->pCursor will be close automatically, if it exists, by
64974     ** the call above. */
64975   }else if( pCx->pCursor ){
64976     sqlite3BtreeCloseCursor(pCx->pCursor);
64977   }
64978 #ifndef SQLITE_OMIT_VIRTUALTABLE
64979   else if( pCx->pVtabCursor ){
64980     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
64981     const sqlite3_module *pModule = pVtabCursor->pVtab->pModule;
64982     p->inVtabMethod = 1;
64983     pModule->xClose(pVtabCursor);
64984     p->inVtabMethod = 0;
64985   }
64986 #endif
64987 }
64988 
64989 /*
64990 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
64991 ** is used, for example, when a trigger sub-program is halted to restore
64992 ** control to the main program.
64993 */
64994 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
64995   Vdbe *v = pFrame->v;
64996   v->aOnceFlag = pFrame->aOnceFlag;
64997   v->nOnceFlag = pFrame->nOnceFlag;
64998   v->aOp = pFrame->aOp;
64999   v->nOp = pFrame->nOp;
65000   v->aMem = pFrame->aMem;
65001   v->nMem = pFrame->nMem;
65002   v->apCsr = pFrame->apCsr;
65003   v->nCursor = pFrame->nCursor;
65004   v->db->lastRowid = pFrame->lastRowid;
65005   v->nChange = pFrame->nChange;
65006   return pFrame->pc;
65007 }
65008 
65009 /*
65010 ** Close all cursors.
65011 **
65012 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
65013 ** cell array. This is necessary as the memory cell array may contain
65014 ** pointers to VdbeFrame objects, which may in turn contain pointers to
65015 ** open cursors.
65016 */
65017 static void closeAllCursors(Vdbe *p){
65018   if( p->pFrame ){
65019     VdbeFrame *pFrame;
65020     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
65021     sqlite3VdbeFrameRestore(pFrame);
65022     p->pFrame = 0;
65023     p->nFrame = 0;
65024   }
65025   assert( p->nFrame==0 );
65026 
65027   if( p->apCsr ){
65028     int i;
65029     for(i=0; i<p->nCursor; i++){
65030       VdbeCursor *pC = p->apCsr[i];
65031       if( pC ){
65032         sqlite3VdbeFreeCursor(p, pC);
65033         p->apCsr[i] = 0;
65034       }
65035     }
65036   }
65037   if( p->aMem ){
65038     releaseMemArray(&p->aMem[1], p->nMem);
65039   }
65040   while( p->pDelFrame ){
65041     VdbeFrame *pDel = p->pDelFrame;
65042     p->pDelFrame = pDel->pParent;
65043     sqlite3VdbeFrameDelete(pDel);
65044   }
65045 
65046   /* Delete any auxdata allocations made by the VM */
65047   if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p, -1, 0);
65048   assert( p->pAuxData==0 );
65049 }
65050 
65051 /*
65052 ** Clean up the VM after a single run.
65053 */
65054 static void Cleanup(Vdbe *p){
65055   sqlite3 *db = p->db;
65056 
65057 #ifdef SQLITE_DEBUG
65058   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
65059   ** Vdbe.aMem[] arrays have already been cleaned up.  */
65060   int i;
65061   if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
65062   if( p->aMem ){
65063     for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
65064   }
65065 #endif
65066 
65067   sqlite3DbFree(db, p->zErrMsg);
65068   p->zErrMsg = 0;
65069   p->pResultSet = 0;
65070 }
65071 
65072 /*
65073 ** Set the number of result columns that will be returned by this SQL
65074 ** statement. This is now set at compile time, rather than during
65075 ** execution of the vdbe program so that sqlite3_column_count() can
65076 ** be called on an SQL statement before sqlite3_step().
65077 */
65078 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
65079   Mem *pColName;
65080   int n;
65081   sqlite3 *db = p->db;
65082 
65083   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
65084   sqlite3DbFree(db, p->aColName);
65085   n = nResColumn*COLNAME_N;
65086   p->nResColumn = (u16)nResColumn;
65087   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
65088   if( p->aColName==0 ) return;
65089   while( n-- > 0 ){
65090     pColName->flags = MEM_Null;
65091     pColName->db = p->db;
65092     pColName++;
65093   }
65094 }
65095 
65096 /*
65097 ** Set the name of the idx'th column to be returned by the SQL statement.
65098 ** zName must be a pointer to a nul terminated string.
65099 **
65100 ** This call must be made after a call to sqlite3VdbeSetNumCols().
65101 **
65102 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
65103 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
65104 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
65105 */
65106 SQLITE_PRIVATE int sqlite3VdbeSetColName(
65107   Vdbe *p,                         /* Vdbe being configured */
65108   int idx,                         /* Index of column zName applies to */
65109   int var,                         /* One of the COLNAME_* constants */
65110   const char *zName,               /* Pointer to buffer containing name */
65111   void (*xDel)(void*)              /* Memory management strategy for zName */
65112 ){
65113   int rc;
65114   Mem *pColName;
65115   assert( idx<p->nResColumn );
65116   assert( var<COLNAME_N );
65117   if( p->db->mallocFailed ){
65118     assert( !zName || xDel!=SQLITE_DYNAMIC );
65119     return SQLITE_NOMEM;
65120   }
65121   assert( p->aColName!=0 );
65122   pColName = &(p->aColName[idx+var*p->nResColumn]);
65123   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
65124   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
65125   return rc;
65126 }
65127 
65128 /*
65129 ** A read or write transaction may or may not be active on database handle
65130 ** db. If a transaction is active, commit it. If there is a
65131 ** write-transaction spanning more than one database file, this routine
65132 ** takes care of the master journal trickery.
65133 */
65134 static int vdbeCommit(sqlite3 *db, Vdbe *p){
65135   int i;
65136   int nTrans = 0;  /* Number of databases with an active write-transaction */
65137   int rc = SQLITE_OK;
65138   int needXcommit = 0;
65139 
65140 #ifdef SQLITE_OMIT_VIRTUALTABLE
65141   /* With this option, sqlite3VtabSync() is defined to be simply
65142   ** SQLITE_OK so p is not used.
65143   */
65144   UNUSED_PARAMETER(p);
65145 #endif
65146 
65147   /* Before doing anything else, call the xSync() callback for any
65148   ** virtual module tables written in this transaction. This has to
65149   ** be done before determining whether a master journal file is
65150   ** required, as an xSync() callback may add an attached database
65151   ** to the transaction.
65152   */
65153   rc = sqlite3VtabSync(db, p);
65154 
65155   /* This loop determines (a) if the commit hook should be invoked and
65156   ** (b) how many database files have open write transactions, not
65157   ** including the temp database. (b) is important because if more than
65158   ** one database file has an open write transaction, a master journal
65159   ** file is required for an atomic commit.
65160   */
65161   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
65162     Btree *pBt = db->aDb[i].pBt;
65163     if( sqlite3BtreeIsInTrans(pBt) ){
65164       needXcommit = 1;
65165       if( i!=1 ) nTrans++;
65166       sqlite3BtreeEnter(pBt);
65167       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
65168       sqlite3BtreeLeave(pBt);
65169     }
65170   }
65171   if( rc!=SQLITE_OK ){
65172     return rc;
65173   }
65174 
65175   /* If there are any write-transactions at all, invoke the commit hook */
65176   if( needXcommit && db->xCommitCallback ){
65177     rc = db->xCommitCallback(db->pCommitArg);
65178     if( rc ){
65179       return SQLITE_CONSTRAINT_COMMITHOOK;
65180     }
65181   }
65182 
65183   /* The simple case - no more than one database file (not counting the
65184   ** TEMP database) has a transaction active.   There is no need for the
65185   ** master-journal.
65186   **
65187   ** If the return value of sqlite3BtreeGetFilename() is a zero length
65188   ** string, it means the main database is :memory: or a temp file.  In
65189   ** that case we do not support atomic multi-file commits, so use the
65190   ** simple case then too.
65191   */
65192   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
65193    || nTrans<=1
65194   ){
65195     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
65196       Btree *pBt = db->aDb[i].pBt;
65197       if( pBt ){
65198         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
65199       }
65200     }
65201 
65202     /* Do the commit only if all databases successfully complete phase 1.
65203     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
65204     ** IO error while deleting or truncating a journal file. It is unlikely,
65205     ** but could happen. In this case abandon processing and return the error.
65206     */
65207     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
65208       Btree *pBt = db->aDb[i].pBt;
65209       if( pBt ){
65210         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
65211       }
65212     }
65213     if( rc==SQLITE_OK ){
65214       sqlite3VtabCommit(db);
65215     }
65216   }
65217 
65218   /* The complex case - There is a multi-file write-transaction active.
65219   ** This requires a master journal file to ensure the transaction is
65220   ** committed atomically.
65221   */
65222 #ifndef SQLITE_OMIT_DISKIO
65223   else{
65224     sqlite3_vfs *pVfs = db->pVfs;
65225     int needSync = 0;
65226     char *zMaster = 0;   /* File-name for the master journal */
65227     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
65228     sqlite3_file *pMaster = 0;
65229     i64 offset = 0;
65230     int res;
65231     int retryCount = 0;
65232     int nMainFile;
65233 
65234     /* Select a master journal file name */
65235     nMainFile = sqlite3Strlen30(zMainFile);
65236     zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
65237     if( zMaster==0 ) return SQLITE_NOMEM;
65238     do {
65239       u32 iRandom;
65240       if( retryCount ){
65241         if( retryCount>100 ){
65242           sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
65243           sqlite3OsDelete(pVfs, zMaster, 0);
65244           break;
65245         }else if( retryCount==1 ){
65246           sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
65247         }
65248       }
65249       retryCount++;
65250       sqlite3_randomness(sizeof(iRandom), &iRandom);
65251       sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
65252                                (iRandom>>8)&0xffffff, iRandom&0xff);
65253       /* The antipenultimate character of the master journal name must
65254       ** be "9" to avoid name collisions when using 8+3 filenames. */
65255       assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
65256       sqlite3FileSuffix3(zMainFile, zMaster);
65257       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
65258     }while( rc==SQLITE_OK && res );
65259     if( rc==SQLITE_OK ){
65260       /* Open the master journal. */
65261       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
65262           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
65263           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
65264       );
65265     }
65266     if( rc!=SQLITE_OK ){
65267       sqlite3DbFree(db, zMaster);
65268       return rc;
65269     }
65270 
65271     /* Write the name of each database file in the transaction into the new
65272     ** master journal file. If an error occurs at this point close
65273     ** and delete the master journal file. All the individual journal files
65274     ** still have 'null' as the master journal pointer, so they will roll
65275     ** back independently if a failure occurs.
65276     */
65277     for(i=0; i<db->nDb; i++){
65278       Btree *pBt = db->aDb[i].pBt;
65279       if( sqlite3BtreeIsInTrans(pBt) ){
65280         char const *zFile = sqlite3BtreeGetJournalname(pBt);
65281         if( zFile==0 ){
65282           continue;  /* Ignore TEMP and :memory: databases */
65283         }
65284         assert( zFile[0]!=0 );
65285         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
65286           needSync = 1;
65287         }
65288         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
65289         offset += sqlite3Strlen30(zFile)+1;
65290         if( rc!=SQLITE_OK ){
65291           sqlite3OsCloseFree(pMaster);
65292           sqlite3OsDelete(pVfs, zMaster, 0);
65293           sqlite3DbFree(db, zMaster);
65294           return rc;
65295         }
65296       }
65297     }
65298 
65299     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
65300     ** flag is set this is not required.
65301     */
65302     if( needSync
65303      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
65304      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
65305     ){
65306       sqlite3OsCloseFree(pMaster);
65307       sqlite3OsDelete(pVfs, zMaster, 0);
65308       sqlite3DbFree(db, zMaster);
65309       return rc;
65310     }
65311 
65312     /* Sync all the db files involved in the transaction. The same call
65313     ** sets the master journal pointer in each individual journal. If
65314     ** an error occurs here, do not delete the master journal file.
65315     **
65316     ** If the error occurs during the first call to
65317     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
65318     ** master journal file will be orphaned. But we cannot delete it,
65319     ** in case the master journal file name was written into the journal
65320     ** file before the failure occurred.
65321     */
65322     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
65323       Btree *pBt = db->aDb[i].pBt;
65324       if( pBt ){
65325         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
65326       }
65327     }
65328     sqlite3OsCloseFree(pMaster);
65329     assert( rc!=SQLITE_BUSY );
65330     if( rc!=SQLITE_OK ){
65331       sqlite3DbFree(db, zMaster);
65332       return rc;
65333     }
65334 
65335     /* Delete the master journal file. This commits the transaction. After
65336     ** doing this the directory is synced again before any individual
65337     ** transaction files are deleted.
65338     */
65339     rc = sqlite3OsDelete(pVfs, zMaster, 1);
65340     sqlite3DbFree(db, zMaster);
65341     zMaster = 0;
65342     if( rc ){
65343       return rc;
65344     }
65345 
65346     /* All files and directories have already been synced, so the following
65347     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
65348     ** deleting or truncating journals. If something goes wrong while
65349     ** this is happening we don't really care. The integrity of the
65350     ** transaction is already guaranteed, but some stray 'cold' journals
65351     ** may be lying around. Returning an error code won't help matters.
65352     */
65353     disable_simulated_io_errors();
65354     sqlite3BeginBenignMalloc();
65355     for(i=0; i<db->nDb; i++){
65356       Btree *pBt = db->aDb[i].pBt;
65357       if( pBt ){
65358         sqlite3BtreeCommitPhaseTwo(pBt, 1);
65359       }
65360     }
65361     sqlite3EndBenignMalloc();
65362     enable_simulated_io_errors();
65363 
65364     sqlite3VtabCommit(db);
65365   }
65366 #endif
65367 
65368   return rc;
65369 }
65370 
65371 /*
65372 ** This routine checks that the sqlite3.nVdbeActive count variable
65373 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
65374 ** currently active. An assertion fails if the two counts do not match.
65375 ** This is an internal self-check only - it is not an essential processing
65376 ** step.
65377 **
65378 ** This is a no-op if NDEBUG is defined.
65379 */
65380 #ifndef NDEBUG
65381 static void checkActiveVdbeCnt(sqlite3 *db){
65382   Vdbe *p;
65383   int cnt = 0;
65384   int nWrite = 0;
65385   int nRead = 0;
65386   p = db->pVdbe;
65387   while( p ){
65388     if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
65389       cnt++;
65390       if( p->readOnly==0 ) nWrite++;
65391       if( p->bIsReader ) nRead++;
65392     }
65393     p = p->pNext;
65394   }
65395   assert( cnt==db->nVdbeActive );
65396   assert( nWrite==db->nVdbeWrite );
65397   assert( nRead==db->nVdbeRead );
65398 }
65399 #else
65400 #define checkActiveVdbeCnt(x)
65401 #endif
65402 
65403 /*
65404 ** If the Vdbe passed as the first argument opened a statement-transaction,
65405 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
65406 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
65407 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
65408 ** statement transaction is committed.
65409 **
65410 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
65411 ** Otherwise SQLITE_OK.
65412 */
65413 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
65414   sqlite3 *const db = p->db;
65415   int rc = SQLITE_OK;
65416 
65417   /* If p->iStatement is greater than zero, then this Vdbe opened a
65418   ** statement transaction that should be closed here. The only exception
65419   ** is that an IO error may have occurred, causing an emergency rollback.
65420   ** In this case (db->nStatement==0), and there is nothing to do.
65421   */
65422   if( db->nStatement && p->iStatement ){
65423     int i;
65424     const int iSavepoint = p->iStatement-1;
65425 
65426     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
65427     assert( db->nStatement>0 );
65428     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
65429 
65430     for(i=0; i<db->nDb; i++){
65431       int rc2 = SQLITE_OK;
65432       Btree *pBt = db->aDb[i].pBt;
65433       if( pBt ){
65434         if( eOp==SAVEPOINT_ROLLBACK ){
65435           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
65436         }
65437         if( rc2==SQLITE_OK ){
65438           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
65439         }
65440         if( rc==SQLITE_OK ){
65441           rc = rc2;
65442         }
65443       }
65444     }
65445     db->nStatement--;
65446     p->iStatement = 0;
65447 
65448     if( rc==SQLITE_OK ){
65449       if( eOp==SAVEPOINT_ROLLBACK ){
65450         rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
65451       }
65452       if( rc==SQLITE_OK ){
65453         rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
65454       }
65455     }
65456 
65457     /* If the statement transaction is being rolled back, also restore the
65458     ** database handles deferred constraint counter to the value it had when
65459     ** the statement transaction was opened.  */
65460     if( eOp==SAVEPOINT_ROLLBACK ){
65461       db->nDeferredCons = p->nStmtDefCons;
65462       db->nDeferredImmCons = p->nStmtDefImmCons;
65463     }
65464   }
65465   return rc;
65466 }
65467 
65468 /*
65469 ** This function is called when a transaction opened by the database
65470 ** handle associated with the VM passed as an argument is about to be
65471 ** committed. If there are outstanding deferred foreign key constraint
65472 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
65473 **
65474 ** If there are outstanding FK violations and this function returns
65475 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
65476 ** and write an error message to it. Then return SQLITE_ERROR.
65477 */
65478 #ifndef SQLITE_OMIT_FOREIGN_KEY
65479 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
65480   sqlite3 *db = p->db;
65481   if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
65482    || (!deferred && p->nFkConstraint>0)
65483   ){
65484     p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
65485     p->errorAction = OE_Abort;
65486     sqlite3SetString(&p->zErrMsg, db, "FOREIGN KEY constraint failed");
65487     return SQLITE_ERROR;
65488   }
65489   return SQLITE_OK;
65490 }
65491 #endif
65492 
65493 /*
65494 ** This routine is called the when a VDBE tries to halt.  If the VDBE
65495 ** has made changes and is in autocommit mode, then commit those
65496 ** changes.  If a rollback is needed, then do the rollback.
65497 **
65498 ** This routine is the only way to move the state of a VM from
65499 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
65500 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
65501 **
65502 ** Return an error code.  If the commit could not complete because of
65503 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
65504 ** means the close did not happen and needs to be repeated.
65505 */
65506 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
65507   int rc;                         /* Used to store transient return codes */
65508   sqlite3 *db = p->db;
65509 
65510   /* This function contains the logic that determines if a statement or
65511   ** transaction will be committed or rolled back as a result of the
65512   ** execution of this virtual machine.
65513   **
65514   ** If any of the following errors occur:
65515   **
65516   **     SQLITE_NOMEM
65517   **     SQLITE_IOERR
65518   **     SQLITE_FULL
65519   **     SQLITE_INTERRUPT
65520   **
65521   ** Then the internal cache might have been left in an inconsistent
65522   ** state.  We need to rollback the statement transaction, if there is
65523   ** one, or the complete transaction if there is no statement transaction.
65524   */
65525 
65526   if( p->db->mallocFailed ){
65527     p->rc = SQLITE_NOMEM;
65528   }
65529   if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
65530   closeAllCursors(p);
65531   if( p->magic!=VDBE_MAGIC_RUN ){
65532     return SQLITE_OK;
65533   }
65534   checkActiveVdbeCnt(db);
65535 
65536   /* No commit or rollback needed if the program never started or if the
65537   ** SQL statement does not read or write a database file.  */
65538   if( p->pc>=0 && p->bIsReader ){
65539     int mrc;   /* Primary error code from p->rc */
65540     int eStatementOp = 0;
65541     int isSpecialError;            /* Set to true if a 'special' error */
65542 
65543     /* Lock all btrees used by the statement */
65544     sqlite3VdbeEnter(p);
65545 
65546     /* Check for one of the special errors */
65547     mrc = p->rc & 0xff;
65548     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
65549                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
65550     if( isSpecialError ){
65551       /* If the query was read-only and the error code is SQLITE_INTERRUPT,
65552       ** no rollback is necessary. Otherwise, at least a savepoint
65553       ** transaction must be rolled back to restore the database to a
65554       ** consistent state.
65555       **
65556       ** Even if the statement is read-only, it is important to perform
65557       ** a statement or transaction rollback operation. If the error
65558       ** occurred while writing to the journal, sub-journal or database
65559       ** file as part of an effort to free up cache space (see function
65560       ** pagerStress() in pager.c), the rollback is required to restore
65561       ** the pager to a consistent state.
65562       */
65563       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
65564         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
65565           eStatementOp = SAVEPOINT_ROLLBACK;
65566         }else{
65567           /* We are forced to roll back the active transaction. Before doing
65568           ** so, abort any other statements this handle currently has active.
65569           */
65570           sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
65571           sqlite3CloseSavepoints(db);
65572           db->autoCommit = 1;
65573         }
65574       }
65575     }
65576 
65577     /* Check for immediate foreign key violations. */
65578     if( p->rc==SQLITE_OK ){
65579       sqlite3VdbeCheckFk(p, 0);
65580     }
65581 
65582     /* If the auto-commit flag is set and this is the only active writer
65583     ** VM, then we do either a commit or rollback of the current transaction.
65584     **
65585     ** Note: This block also runs if one of the special errors handled
65586     ** above has occurred.
65587     */
65588     if( !sqlite3VtabInSync(db)
65589      && db->autoCommit
65590      && db->nVdbeWrite==(p->readOnly==0)
65591     ){
65592       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
65593         rc = sqlite3VdbeCheckFk(p, 1);
65594         if( rc!=SQLITE_OK ){
65595           if( NEVER(p->readOnly) ){
65596             sqlite3VdbeLeave(p);
65597             return SQLITE_ERROR;
65598           }
65599           rc = SQLITE_CONSTRAINT_FOREIGNKEY;
65600         }else{
65601           /* The auto-commit flag is true, the vdbe program was successful
65602           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
65603           ** key constraints to hold up the transaction. This means a commit
65604           ** is required. */
65605           rc = vdbeCommit(db, p);
65606         }
65607         if( rc==SQLITE_BUSY && p->readOnly ){
65608           sqlite3VdbeLeave(p);
65609           return SQLITE_BUSY;
65610         }else if( rc!=SQLITE_OK ){
65611           p->rc = rc;
65612           sqlite3RollbackAll(db, SQLITE_OK);
65613         }else{
65614           db->nDeferredCons = 0;
65615           db->nDeferredImmCons = 0;
65616           db->flags &= ~SQLITE_DeferFKs;
65617           sqlite3CommitInternalChanges(db);
65618         }
65619       }else{
65620         sqlite3RollbackAll(db, SQLITE_OK);
65621       }
65622       db->nStatement = 0;
65623     }else if( eStatementOp==0 ){
65624       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
65625         eStatementOp = SAVEPOINT_RELEASE;
65626       }else if( p->errorAction==OE_Abort ){
65627         eStatementOp = SAVEPOINT_ROLLBACK;
65628       }else{
65629         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
65630         sqlite3CloseSavepoints(db);
65631         db->autoCommit = 1;
65632       }
65633     }
65634 
65635     /* If eStatementOp is non-zero, then a statement transaction needs to
65636     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
65637     ** do so. If this operation returns an error, and the current statement
65638     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
65639     ** current statement error code.
65640     */
65641     if( eStatementOp ){
65642       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
65643       if( rc ){
65644         if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
65645           p->rc = rc;
65646           sqlite3DbFree(db, p->zErrMsg);
65647           p->zErrMsg = 0;
65648         }
65649         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
65650         sqlite3CloseSavepoints(db);
65651         db->autoCommit = 1;
65652       }
65653     }
65654 
65655     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
65656     ** has been rolled back, update the database connection change-counter.
65657     */
65658     if( p->changeCntOn ){
65659       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
65660         sqlite3VdbeSetChanges(db, p->nChange);
65661       }else{
65662         sqlite3VdbeSetChanges(db, 0);
65663       }
65664       p->nChange = 0;
65665     }
65666 
65667     /* Release the locks */
65668     sqlite3VdbeLeave(p);
65669   }
65670 
65671   /* We have successfully halted and closed the VM.  Record this fact. */
65672   if( p->pc>=0 ){
65673     db->nVdbeActive--;
65674     if( !p->readOnly ) db->nVdbeWrite--;
65675     if( p->bIsReader ) db->nVdbeRead--;
65676     assert( db->nVdbeActive>=db->nVdbeRead );
65677     assert( db->nVdbeRead>=db->nVdbeWrite );
65678     assert( db->nVdbeWrite>=0 );
65679   }
65680   p->magic = VDBE_MAGIC_HALT;
65681   checkActiveVdbeCnt(db);
65682   if( p->db->mallocFailed ){
65683     p->rc = SQLITE_NOMEM;
65684   }
65685 
65686   /* If the auto-commit flag is set to true, then any locks that were held
65687   ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
65688   ** to invoke any required unlock-notify callbacks.
65689   */
65690   if( db->autoCommit ){
65691     sqlite3ConnectionUnlocked(db);
65692   }
65693 
65694   assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
65695   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
65696 }
65697 
65698 
65699 /*
65700 ** Each VDBE holds the result of the most recent sqlite3_step() call
65701 ** in p->rc.  This routine sets that result back to SQLITE_OK.
65702 */
65703 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
65704   p->rc = SQLITE_OK;
65705 }
65706 
65707 /*
65708 ** Copy the error code and error message belonging to the VDBE passed
65709 ** as the first argument to its database handle (so that they will be
65710 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
65711 **
65712 ** This function does not clear the VDBE error code or message, just
65713 ** copies them to the database handle.
65714 */
65715 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
65716   sqlite3 *db = p->db;
65717   int rc = p->rc;
65718   if( p->zErrMsg ){
65719     u8 mallocFailed = db->mallocFailed;
65720     sqlite3BeginBenignMalloc();
65721     if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
65722     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
65723     sqlite3EndBenignMalloc();
65724     db->mallocFailed = mallocFailed;
65725     db->errCode = rc;
65726   }else{
65727     sqlite3Error(db, rc);
65728   }
65729   return rc;
65730 }
65731 
65732 #ifdef SQLITE_ENABLE_SQLLOG
65733 /*
65734 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
65735 ** invoke it.
65736 */
65737 static void vdbeInvokeSqllog(Vdbe *v){
65738   if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
65739     char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
65740     assert( v->db->init.busy==0 );
65741     if( zExpanded ){
65742       sqlite3GlobalConfig.xSqllog(
65743           sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
65744       );
65745       sqlite3DbFree(v->db, zExpanded);
65746     }
65747   }
65748 }
65749 #else
65750 # define vdbeInvokeSqllog(x)
65751 #endif
65752 
65753 /*
65754 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
65755 ** Write any error messages into *pzErrMsg.  Return the result code.
65756 **
65757 ** After this routine is run, the VDBE should be ready to be executed
65758 ** again.
65759 **
65760 ** To look at it another way, this routine resets the state of the
65761 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
65762 ** VDBE_MAGIC_INIT.
65763 */
65764 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
65765   sqlite3 *db;
65766   db = p->db;
65767 
65768   /* If the VM did not run to completion or if it encountered an
65769   ** error, then it might not have been halted properly.  So halt
65770   ** it now.
65771   */
65772   sqlite3VdbeHalt(p);
65773 
65774   /* If the VDBE has be run even partially, then transfer the error code
65775   ** and error message from the VDBE into the main database structure.  But
65776   ** if the VDBE has just been set to run but has not actually executed any
65777   ** instructions yet, leave the main database error information unchanged.
65778   */
65779   if( p->pc>=0 ){
65780     vdbeInvokeSqllog(p);
65781     sqlite3VdbeTransferError(p);
65782     sqlite3DbFree(db, p->zErrMsg);
65783     p->zErrMsg = 0;
65784     if( p->runOnlyOnce ) p->expired = 1;
65785   }else if( p->rc && p->expired ){
65786     /* The expired flag was set on the VDBE before the first call
65787     ** to sqlite3_step(). For consistency (since sqlite3_step() was
65788     ** called), set the database error in this case as well.
65789     */
65790     sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
65791     sqlite3DbFree(db, p->zErrMsg);
65792     p->zErrMsg = 0;
65793   }
65794 
65795   /* Reclaim all memory used by the VDBE
65796   */
65797   Cleanup(p);
65798 
65799   /* Save profiling information from this VDBE run.
65800   */
65801 #ifdef VDBE_PROFILE
65802   {
65803     FILE *out = fopen("vdbe_profile.out", "a");
65804     if( out ){
65805       int i;
65806       fprintf(out, "---- ");
65807       for(i=0; i<p->nOp; i++){
65808         fprintf(out, "%02x", p->aOp[i].opcode);
65809       }
65810       fprintf(out, "\n");
65811       if( p->zSql ){
65812         char c, pc = 0;
65813         fprintf(out, "-- ");
65814         for(i=0; (c = p->zSql[i])!=0; i++){
65815           if( pc=='\n' ) fprintf(out, "-- ");
65816           putc(c, out);
65817           pc = c;
65818         }
65819         if( pc!='\n' ) fprintf(out, "\n");
65820       }
65821       for(i=0; i<p->nOp; i++){
65822         char zHdr[100];
65823         sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
65824            p->aOp[i].cnt,
65825            p->aOp[i].cycles,
65826            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
65827         );
65828         fprintf(out, "%s", zHdr);
65829         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
65830       }
65831       fclose(out);
65832     }
65833   }
65834 #endif
65835   p->iCurrentTime = 0;
65836   p->magic = VDBE_MAGIC_INIT;
65837   return p->rc & db->errMask;
65838 }
65839 
65840 /*
65841 ** Clean up and delete a VDBE after execution.  Return an integer which is
65842 ** the result code.  Write any error message text into *pzErrMsg.
65843 */
65844 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
65845   int rc = SQLITE_OK;
65846   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
65847     rc = sqlite3VdbeReset(p);
65848     assert( (rc & p->db->errMask)==rc );
65849   }
65850   sqlite3VdbeDelete(p);
65851   return rc;
65852 }
65853 
65854 /*
65855 ** If parameter iOp is less than zero, then invoke the destructor for
65856 ** all auxiliary data pointers currently cached by the VM passed as
65857 ** the first argument.
65858 **
65859 ** Or, if iOp is greater than or equal to zero, then the destructor is
65860 ** only invoked for those auxiliary data pointers created by the user
65861 ** function invoked by the OP_Function opcode at instruction iOp of
65862 ** VM pVdbe, and only then if:
65863 **
65864 **    * the associated function parameter is the 32nd or later (counting
65865 **      from left to right), or
65866 **
65867 **    * the corresponding bit in argument mask is clear (where the first
65868 **      function parameter corresponds to bit 0 etc.).
65869 */
65870 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
65871   AuxData **pp = &pVdbe->pAuxData;
65872   while( *pp ){
65873     AuxData *pAux = *pp;
65874     if( (iOp<0)
65875      || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
65876     ){
65877       testcase( pAux->iArg==31 );
65878       if( pAux->xDelete ){
65879         pAux->xDelete(pAux->pAux);
65880       }
65881       *pp = pAux->pNext;
65882       sqlite3DbFree(pVdbe->db, pAux);
65883     }else{
65884       pp= &pAux->pNext;
65885     }
65886   }
65887 }
65888 
65889 /*
65890 ** Free all memory associated with the Vdbe passed as the second argument,
65891 ** except for object itself, which is preserved.
65892 **
65893 ** The difference between this function and sqlite3VdbeDelete() is that
65894 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
65895 ** the database connection and frees the object itself.
65896 */
65897 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
65898   SubProgram *pSub, *pNext;
65899   int i;
65900   assert( p->db==0 || p->db==db );
65901   releaseMemArray(p->aVar, p->nVar);
65902   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
65903   for(pSub=p->pProgram; pSub; pSub=pNext){
65904     pNext = pSub->pNext;
65905     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
65906     sqlite3DbFree(db, pSub);
65907   }
65908   for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
65909   vdbeFreeOpArray(db, p->aOp, p->nOp);
65910   sqlite3DbFree(db, p->aColName);
65911   sqlite3DbFree(db, p->zSql);
65912   sqlite3DbFree(db, p->pFree);
65913 }
65914 
65915 /*
65916 ** Delete an entire VDBE.
65917 */
65918 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
65919   sqlite3 *db;
65920 
65921   if( NEVER(p==0) ) return;
65922   db = p->db;
65923   assert( sqlite3_mutex_held(db->mutex) );
65924   sqlite3VdbeClearObject(db, p);
65925   if( p->pPrev ){
65926     p->pPrev->pNext = p->pNext;
65927   }else{
65928     assert( db->pVdbe==p );
65929     db->pVdbe = p->pNext;
65930   }
65931   if( p->pNext ){
65932     p->pNext->pPrev = p->pPrev;
65933   }
65934   p->magic = VDBE_MAGIC_DEAD;
65935   p->db = 0;
65936   sqlite3DbFree(db, p);
65937 }
65938 
65939 /*
65940 ** The cursor "p" has a pending seek operation that has not yet been
65941 ** carried out.  Seek the cursor now.  If an error occurs, return
65942 ** the appropriate error code.
65943 */
65944 static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
65945   int res, rc;
65946 #ifdef SQLITE_TEST
65947   extern int sqlite3_search_count;
65948 #endif
65949   assert( p->deferredMoveto );
65950   assert( p->isTable );
65951   rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
65952   if( rc ) return rc;
65953   if( res!=0 ) return SQLITE_CORRUPT_BKPT;
65954 #ifdef SQLITE_TEST
65955   sqlite3_search_count++;
65956 #endif
65957   p->deferredMoveto = 0;
65958   p->cacheStatus = CACHE_STALE;
65959   return SQLITE_OK;
65960 }
65961 
65962 /*
65963 ** Something has moved cursor "p" out of place.  Maybe the row it was
65964 ** pointed to was deleted out from under it.  Or maybe the btree was
65965 ** rebalanced.  Whatever the cause, try to restore "p" to the place it
65966 ** is supposed to be pointing.  If the row was deleted out from under the
65967 ** cursor, set the cursor to point to a NULL row.
65968 */
65969 static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
65970   int isDifferentRow, rc;
65971   assert( p->pCursor!=0 );
65972   assert( sqlite3BtreeCursorHasMoved(p->pCursor) );
65973   rc = sqlite3BtreeCursorRestore(p->pCursor, &isDifferentRow);
65974   p->cacheStatus = CACHE_STALE;
65975   if( isDifferentRow ) p->nullRow = 1;
65976   return rc;
65977 }
65978 
65979 /*
65980 ** Check to ensure that the cursor is valid.  Restore the cursor
65981 ** if need be.  Return any I/O error from the restore operation.
65982 */
65983 SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
65984   if( sqlite3BtreeCursorHasMoved(p->pCursor) ){
65985     return handleMovedCursor(p);
65986   }
65987   return SQLITE_OK;
65988 }
65989 
65990 /*
65991 ** Make sure the cursor p is ready to read or write the row to which it
65992 ** was last positioned.  Return an error code if an OOM fault or I/O error
65993 ** prevents us from positioning the cursor to its correct position.
65994 **
65995 ** If a MoveTo operation is pending on the given cursor, then do that
65996 ** MoveTo now.  If no move is pending, check to see if the row has been
65997 ** deleted out from under the cursor and if it has, mark the row as
65998 ** a NULL row.
65999 **
66000 ** If the cursor is already pointing to the correct row and that row has
66001 ** not been deleted out from under the cursor, then this routine is a no-op.
66002 */
66003 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
66004   if( p->deferredMoveto ){
66005     return handleDeferredMoveto(p);
66006   }
66007   if( p->pCursor && sqlite3BtreeCursorHasMoved(p->pCursor) ){
66008     return handleMovedCursor(p);
66009   }
66010   return SQLITE_OK;
66011 }
66012 
66013 /*
66014 ** The following functions:
66015 **
66016 ** sqlite3VdbeSerialType()
66017 ** sqlite3VdbeSerialTypeLen()
66018 ** sqlite3VdbeSerialLen()
66019 ** sqlite3VdbeSerialPut()
66020 ** sqlite3VdbeSerialGet()
66021 **
66022 ** encapsulate the code that serializes values for storage in SQLite
66023 ** data and index records. Each serialized value consists of a
66024 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
66025 ** integer, stored as a varint.
66026 **
66027 ** In an SQLite index record, the serial type is stored directly before
66028 ** the blob of data that it corresponds to. In a table record, all serial
66029 ** types are stored at the start of the record, and the blobs of data at
66030 ** the end. Hence these functions allow the caller to handle the
66031 ** serial-type and data blob separately.
66032 **
66033 ** The following table describes the various storage classes for data:
66034 **
66035 **   serial type        bytes of data      type
66036 **   --------------     ---------------    ---------------
66037 **      0                     0            NULL
66038 **      1                     1            signed integer
66039 **      2                     2            signed integer
66040 **      3                     3            signed integer
66041 **      4                     4            signed integer
66042 **      5                     6            signed integer
66043 **      6                     8            signed integer
66044 **      7                     8            IEEE float
66045 **      8                     0            Integer constant 0
66046 **      9                     0            Integer constant 1
66047 **     10,11                               reserved for expansion
66048 **    N>=12 and even       (N-12)/2        BLOB
66049 **    N>=13 and odd        (N-13)/2        text
66050 **
66051 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
66052 ** of SQLite will not understand those serial types.
66053 */
66054 
66055 /*
66056 ** Return the serial-type for the value stored in pMem.
66057 */
66058 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
66059   int flags = pMem->flags;
66060   u32 n;
66061 
66062   if( flags&MEM_Null ){
66063     return 0;
66064   }
66065   if( flags&MEM_Int ){
66066     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
66067 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
66068     i64 i = pMem->u.i;
66069     u64 u;
66070     if( i<0 ){
66071       if( i<(-MAX_6BYTE) ) return 6;
66072       /* Previous test prevents:  u = -(-9223372036854775808) */
66073       u = -i;
66074     }else{
66075       u = i;
66076     }
66077     if( u<=127 ){
66078       return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
66079     }
66080     if( u<=32767 ) return 2;
66081     if( u<=8388607 ) return 3;
66082     if( u<=2147483647 ) return 4;
66083     if( u<=MAX_6BYTE ) return 5;
66084     return 6;
66085   }
66086   if( flags&MEM_Real ){
66087     return 7;
66088   }
66089   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
66090   assert( pMem->n>=0 );
66091   n = (u32)pMem->n;
66092   if( flags & MEM_Zero ){
66093     n += pMem->u.nZero;
66094   }
66095   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
66096 }
66097 
66098 /*
66099 ** Return the length of the data corresponding to the supplied serial-type.
66100 */
66101 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
66102   if( serial_type>=12 ){
66103     return (serial_type-12)/2;
66104   }else{
66105     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
66106     return aSize[serial_type];
66107   }
66108 }
66109 
66110 /*
66111 ** If we are on an architecture with mixed-endian floating
66112 ** points (ex: ARM7) then swap the lower 4 bytes with the
66113 ** upper 4 bytes.  Return the result.
66114 **
66115 ** For most architectures, this is a no-op.
66116 **
66117 ** (later):  It is reported to me that the mixed-endian problem
66118 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
66119 ** that early versions of GCC stored the two words of a 64-bit
66120 ** float in the wrong order.  And that error has been propagated
66121 ** ever since.  The blame is not necessarily with GCC, though.
66122 ** GCC might have just copying the problem from a prior compiler.
66123 ** I am also told that newer versions of GCC that follow a different
66124 ** ABI get the byte order right.
66125 **
66126 ** Developers using SQLite on an ARM7 should compile and run their
66127 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
66128 ** enabled, some asserts below will ensure that the byte order of
66129 ** floating point values is correct.
66130 **
66131 ** (2007-08-30)  Frank van Vugt has studied this problem closely
66132 ** and has send his findings to the SQLite developers.  Frank
66133 ** writes that some Linux kernels offer floating point hardware
66134 ** emulation that uses only 32-bit mantissas instead of a full
66135 ** 48-bits as required by the IEEE standard.  (This is the
66136 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
66137 ** byte swapping becomes very complicated.  To avoid problems,
66138 ** the necessary byte swapping is carried out using a 64-bit integer
66139 ** rather than a 64-bit float.  Frank assures us that the code here
66140 ** works for him.  We, the developers, have no way to independently
66141 ** verify this, but Frank seems to know what he is talking about
66142 ** so we trust him.
66143 */
66144 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
66145 static u64 floatSwap(u64 in){
66146   union {
66147     u64 r;
66148     u32 i[2];
66149   } u;
66150   u32 t;
66151 
66152   u.r = in;
66153   t = u.i[0];
66154   u.i[0] = u.i[1];
66155   u.i[1] = t;
66156   return u.r;
66157 }
66158 # define swapMixedEndianFloat(X)  X = floatSwap(X)
66159 #else
66160 # define swapMixedEndianFloat(X)
66161 #endif
66162 
66163 /*
66164 ** Write the serialized data blob for the value stored in pMem into
66165 ** buf. It is assumed that the caller has allocated sufficient space.
66166 ** Return the number of bytes written.
66167 **
66168 ** nBuf is the amount of space left in buf[].  The caller is responsible
66169 ** for allocating enough space to buf[] to hold the entire field, exclusive
66170 ** of the pMem->u.nZero bytes for a MEM_Zero value.
66171 **
66172 ** Return the number of bytes actually written into buf[].  The number
66173 ** of bytes in the zero-filled tail is included in the return value only
66174 ** if those bytes were zeroed in buf[].
66175 */
66176 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
66177   u32 len;
66178 
66179   /* Integer and Real */
66180   if( serial_type<=7 && serial_type>0 ){
66181     u64 v;
66182     u32 i;
66183     if( serial_type==7 ){
66184       assert( sizeof(v)==sizeof(pMem->u.r) );
66185       memcpy(&v, &pMem->u.r, sizeof(v));
66186       swapMixedEndianFloat(v);
66187     }else{
66188       v = pMem->u.i;
66189     }
66190     len = i = sqlite3VdbeSerialTypeLen(serial_type);
66191     assert( i>0 );
66192     do{
66193       buf[--i] = (u8)(v&0xFF);
66194       v >>= 8;
66195     }while( i );
66196     return len;
66197   }
66198 
66199   /* String or blob */
66200   if( serial_type>=12 ){
66201     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
66202              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
66203     len = pMem->n;
66204     memcpy(buf, pMem->z, len);
66205     return len;
66206   }
66207 
66208   /* NULL or constants 0 or 1 */
66209   return 0;
66210 }
66211 
66212 /* Input "x" is a sequence of unsigned characters that represent a
66213 ** big-endian integer.  Return the equivalent native integer
66214 */
66215 #define ONE_BYTE_INT(x)    ((i8)(x)[0])
66216 #define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
66217 #define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
66218 #define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
66219 #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
66220 
66221 /*
66222 ** Deserialize the data blob pointed to by buf as serial type serial_type
66223 ** and store the result in pMem.  Return the number of bytes read.
66224 **
66225 ** This function is implemented as two separate routines for performance.
66226 ** The few cases that require local variables are broken out into a separate
66227 ** routine so that in most cases the overhead of moving the stack pointer
66228 ** is avoided.
66229 */
66230 static u32 SQLITE_NOINLINE serialGet(
66231   const unsigned char *buf,     /* Buffer to deserialize from */
66232   u32 serial_type,              /* Serial type to deserialize */
66233   Mem *pMem                     /* Memory cell to write value into */
66234 ){
66235   u64 x = FOUR_BYTE_UINT(buf);
66236   u32 y = FOUR_BYTE_UINT(buf+4);
66237   x = (x<<32) + y;
66238   if( serial_type==6 ){
66239     pMem->u.i = *(i64*)&x;
66240     pMem->flags = MEM_Int;
66241     testcase( pMem->u.i<0 );
66242   }else{
66243 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
66244     /* Verify that integers and floating point values use the same
66245     ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
66246     ** defined that 64-bit floating point values really are mixed
66247     ** endian.
66248     */
66249     static const u64 t1 = ((u64)0x3ff00000)<<32;
66250     static const double r1 = 1.0;
66251     u64 t2 = t1;
66252     swapMixedEndianFloat(t2);
66253     assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
66254 #endif
66255     assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
66256     swapMixedEndianFloat(x);
66257     memcpy(&pMem->u.r, &x, sizeof(x));
66258     pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
66259   }
66260   return 8;
66261 }
66262 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
66263   const unsigned char *buf,     /* Buffer to deserialize from */
66264   u32 serial_type,              /* Serial type to deserialize */
66265   Mem *pMem                     /* Memory cell to write value into */
66266 ){
66267   switch( serial_type ){
66268     case 10:   /* Reserved for future use */
66269     case 11:   /* Reserved for future use */
66270     case 0: {  /* NULL */
66271       pMem->flags = MEM_Null;
66272       break;
66273     }
66274     case 1: { /* 1-byte signed integer */
66275       pMem->u.i = ONE_BYTE_INT(buf);
66276       pMem->flags = MEM_Int;
66277       testcase( pMem->u.i<0 );
66278       return 1;
66279     }
66280     case 2: { /* 2-byte signed integer */
66281       pMem->u.i = TWO_BYTE_INT(buf);
66282       pMem->flags = MEM_Int;
66283       testcase( pMem->u.i<0 );
66284       return 2;
66285     }
66286     case 3: { /* 3-byte signed integer */
66287       pMem->u.i = THREE_BYTE_INT(buf);
66288       pMem->flags = MEM_Int;
66289       testcase( pMem->u.i<0 );
66290       return 3;
66291     }
66292     case 4: { /* 4-byte signed integer */
66293       pMem->u.i = FOUR_BYTE_INT(buf);
66294       pMem->flags = MEM_Int;
66295       testcase( pMem->u.i<0 );
66296       return 4;
66297     }
66298     case 5: { /* 6-byte signed integer */
66299       pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
66300       pMem->flags = MEM_Int;
66301       testcase( pMem->u.i<0 );
66302       return 6;
66303     }
66304     case 6:   /* 8-byte signed integer */
66305     case 7: { /* IEEE floating point */
66306       /* These use local variables, so do them in a separate routine
66307       ** to avoid having to move the frame pointer in the common case */
66308       return serialGet(buf,serial_type,pMem);
66309     }
66310     case 8:    /* Integer 0 */
66311     case 9: {  /* Integer 1 */
66312       pMem->u.i = serial_type-8;
66313       pMem->flags = MEM_Int;
66314       return 0;
66315     }
66316     default: {
66317       static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
66318       pMem->z = (char *)buf;
66319       pMem->n = (serial_type-12)/2;
66320       pMem->flags = aFlag[serial_type&1];
66321       return pMem->n;
66322     }
66323   }
66324   return 0;
66325 }
66326 /*
66327 ** This routine is used to allocate sufficient space for an UnpackedRecord
66328 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
66329 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
66330 **
66331 ** The space is either allocated using sqlite3DbMallocRaw() or from within
66332 ** the unaligned buffer passed via the second and third arguments (presumably
66333 ** stack space). If the former, then *ppFree is set to a pointer that should
66334 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
66335 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
66336 ** before returning.
66337 **
66338 ** If an OOM error occurs, NULL is returned.
66339 */
66340 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
66341   KeyInfo *pKeyInfo,              /* Description of the record */
66342   char *pSpace,                   /* Unaligned space available */
66343   int szSpace,                    /* Size of pSpace[] in bytes */
66344   char **ppFree                   /* OUT: Caller should free this pointer */
66345 ){
66346   UnpackedRecord *p;              /* Unpacked record to return */
66347   int nOff;                       /* Increment pSpace by nOff to align it */
66348   int nByte;                      /* Number of bytes required for *p */
66349 
66350   /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
66351   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
66352   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
66353   */
66354   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
66355   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
66356   if( nByte>szSpace+nOff ){
66357     p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
66358     *ppFree = (char *)p;
66359     if( !p ) return 0;
66360   }else{
66361     p = (UnpackedRecord*)&pSpace[nOff];
66362     *ppFree = 0;
66363   }
66364 
66365   p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
66366   assert( pKeyInfo->aSortOrder!=0 );
66367   p->pKeyInfo = pKeyInfo;
66368   p->nField = pKeyInfo->nField + 1;
66369   return p;
66370 }
66371 
66372 /*
66373 ** Given the nKey-byte encoding of a record in pKey[], populate the
66374 ** UnpackedRecord structure indicated by the fourth argument with the
66375 ** contents of the decoded record.
66376 */
66377 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
66378   KeyInfo *pKeyInfo,     /* Information about the record format */
66379   int nKey,              /* Size of the binary record */
66380   const void *pKey,      /* The binary record */
66381   UnpackedRecord *p      /* Populate this structure before returning. */
66382 ){
66383   const unsigned char *aKey = (const unsigned char *)pKey;
66384   int d;
66385   u32 idx;                        /* Offset in aKey[] to read from */
66386   u16 u;                          /* Unsigned loop counter */
66387   u32 szHdr;
66388   Mem *pMem = p->aMem;
66389 
66390   p->default_rc = 0;
66391   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
66392   idx = getVarint32(aKey, szHdr);
66393   d = szHdr;
66394   u = 0;
66395   while( idx<szHdr && d<=nKey ){
66396     u32 serial_type;
66397 
66398     idx += getVarint32(&aKey[idx], serial_type);
66399     pMem->enc = pKeyInfo->enc;
66400     pMem->db = pKeyInfo->db;
66401     /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
66402     pMem->szMalloc = 0;
66403     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
66404     pMem++;
66405     if( (++u)>=p->nField ) break;
66406   }
66407   assert( u<=pKeyInfo->nField + 1 );
66408   p->nField = u;
66409 }
66410 
66411 #if SQLITE_DEBUG
66412 /*
66413 ** This function compares two index or table record keys in the same way
66414 ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
66415 ** this function deserializes and compares values using the
66416 ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
66417 ** in assert() statements to ensure that the optimized code in
66418 ** sqlite3VdbeRecordCompare() returns results with these two primitives.
66419 **
66420 ** Return true if the result of comparison is equivalent to desiredResult.
66421 ** Return false if there is a disagreement.
66422 */
66423 static int vdbeRecordCompareDebug(
66424   int nKey1, const void *pKey1, /* Left key */
66425   const UnpackedRecord *pPKey2, /* Right key */
66426   int desiredResult             /* Correct answer */
66427 ){
66428   u32 d1;            /* Offset into aKey[] of next data element */
66429   u32 idx1;          /* Offset into aKey[] of next header element */
66430   u32 szHdr1;        /* Number of bytes in header */
66431   int i = 0;
66432   int rc = 0;
66433   const unsigned char *aKey1 = (const unsigned char *)pKey1;
66434   KeyInfo *pKeyInfo;
66435   Mem mem1;
66436 
66437   pKeyInfo = pPKey2->pKeyInfo;
66438   if( pKeyInfo->db==0 ) return 1;
66439   mem1.enc = pKeyInfo->enc;
66440   mem1.db = pKeyInfo->db;
66441   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
66442   VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
66443 
66444   /* Compilers may complain that mem1.u.i is potentially uninitialized.
66445   ** We could initialize it, as shown here, to silence those complaints.
66446   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
66447   ** the unnecessary initialization has a measurable negative performance
66448   ** impact, since this routine is a very high runner.  And so, we choose
66449   ** to ignore the compiler warnings and leave this variable uninitialized.
66450   */
66451   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
66452 
66453   idx1 = getVarint32(aKey1, szHdr1);
66454   d1 = szHdr1;
66455   assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
66456   assert( pKeyInfo->aSortOrder!=0 );
66457   assert( pKeyInfo->nField>0 );
66458   assert( idx1<=szHdr1 || CORRUPT_DB );
66459   do{
66460     u32 serial_type1;
66461 
66462     /* Read the serial types for the next element in each key. */
66463     idx1 += getVarint32( aKey1+idx1, serial_type1 );
66464 
66465     /* Verify that there is enough key space remaining to avoid
66466     ** a buffer overread.  The "d1+serial_type1+2" subexpression will
66467     ** always be greater than or equal to the amount of required key space.
66468     ** Use that approximation to avoid the more expensive call to
66469     ** sqlite3VdbeSerialTypeLen() in the common case.
66470     */
66471     if( d1+serial_type1+2>(u32)nKey1
66472      && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
66473     ){
66474       break;
66475     }
66476 
66477     /* Extract the values to be compared.
66478     */
66479     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
66480 
66481     /* Do the comparison
66482     */
66483     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
66484     if( rc!=0 ){
66485       assert( mem1.szMalloc==0 );  /* See comment below */
66486       if( pKeyInfo->aSortOrder[i] ){
66487         rc = -rc;  /* Invert the result for DESC sort order. */
66488       }
66489       goto debugCompareEnd;
66490     }
66491     i++;
66492   }while( idx1<szHdr1 && i<pPKey2->nField );
66493 
66494   /* No memory allocation is ever used on mem1.  Prove this using
66495   ** the following assert().  If the assert() fails, it indicates a
66496   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
66497   */
66498   assert( mem1.szMalloc==0 );
66499 
66500   /* rc==0 here means that one of the keys ran out of fields and
66501   ** all the fields up to that point were equal. Return the default_rc
66502   ** value.  */
66503   rc = pPKey2->default_rc;
66504 
66505 debugCompareEnd:
66506   if( desiredResult==0 && rc==0 ) return 1;
66507   if( desiredResult<0 && rc<0 ) return 1;
66508   if( desiredResult>0 && rc>0 ) return 1;
66509   if( CORRUPT_DB ) return 1;
66510   if( pKeyInfo->db->mallocFailed ) return 1;
66511   return 0;
66512 }
66513 #endif
66514 
66515 /*
66516 ** Both *pMem1 and *pMem2 contain string values. Compare the two values
66517 ** using the collation sequence pColl. As usual, return a negative , zero
66518 ** or positive value if *pMem1 is less than, equal to or greater than
66519 ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
66520 */
66521 static int vdbeCompareMemString(
66522   const Mem *pMem1,
66523   const Mem *pMem2,
66524   const CollSeq *pColl,
66525   u8 *prcErr                      /* If an OOM occurs, set to SQLITE_NOMEM */
66526 ){
66527   if( pMem1->enc==pColl->enc ){
66528     /* The strings are already in the correct encoding.  Call the
66529      ** comparison function directly */
66530     return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
66531   }else{
66532     int rc;
66533     const void *v1, *v2;
66534     int n1, n2;
66535     Mem c1;
66536     Mem c2;
66537     sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
66538     sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
66539     sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
66540     sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
66541     v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
66542     n1 = v1==0 ? 0 : c1.n;
66543     v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
66544     n2 = v2==0 ? 0 : c2.n;
66545     rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
66546     sqlite3VdbeMemRelease(&c1);
66547     sqlite3VdbeMemRelease(&c2);
66548     if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM;
66549     return rc;
66550   }
66551 }
66552 
66553 /*
66554 ** Compare two blobs.  Return negative, zero, or positive if the first
66555 ** is less than, equal to, or greater than the second, respectively.
66556 ** If one blob is a prefix of the other, then the shorter is the lessor.
66557 */
66558 static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
66559   int c = memcmp(pB1->z, pB2->z, pB1->n>pB2->n ? pB2->n : pB1->n);
66560   if( c ) return c;
66561   return pB1->n - pB2->n;
66562 }
66563 
66564 
66565 /*
66566 ** Compare the values contained by the two memory cells, returning
66567 ** negative, zero or positive if pMem1 is less than, equal to, or greater
66568 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
66569 ** and reals) sorted numerically, followed by text ordered by the collating
66570 ** sequence pColl and finally blob's ordered by memcmp().
66571 **
66572 ** Two NULL values are considered equal by this function.
66573 */
66574 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
66575   int f1, f2;
66576   int combined_flags;
66577 
66578   f1 = pMem1->flags;
66579   f2 = pMem2->flags;
66580   combined_flags = f1|f2;
66581   assert( (combined_flags & MEM_RowSet)==0 );
66582 
66583   /* If one value is NULL, it is less than the other. If both values
66584   ** are NULL, return 0.
66585   */
66586   if( combined_flags&MEM_Null ){
66587     return (f2&MEM_Null) - (f1&MEM_Null);
66588   }
66589 
66590   /* If one value is a number and the other is not, the number is less.
66591   ** If both are numbers, compare as reals if one is a real, or as integers
66592   ** if both values are integers.
66593   */
66594   if( combined_flags&(MEM_Int|MEM_Real) ){
66595     double r1, r2;
66596     if( (f1 & f2 & MEM_Int)!=0 ){
66597       if( pMem1->u.i < pMem2->u.i ) return -1;
66598       if( pMem1->u.i > pMem2->u.i ) return 1;
66599       return 0;
66600     }
66601     if( (f1&MEM_Real)!=0 ){
66602       r1 = pMem1->u.r;
66603     }else if( (f1&MEM_Int)!=0 ){
66604       r1 = (double)pMem1->u.i;
66605     }else{
66606       return 1;
66607     }
66608     if( (f2&MEM_Real)!=0 ){
66609       r2 = pMem2->u.r;
66610     }else if( (f2&MEM_Int)!=0 ){
66611       r2 = (double)pMem2->u.i;
66612     }else{
66613       return -1;
66614     }
66615     if( r1<r2 ) return -1;
66616     if( r1>r2 ) return 1;
66617     return 0;
66618   }
66619 
66620   /* If one value is a string and the other is a blob, the string is less.
66621   ** If both are strings, compare using the collating functions.
66622   */
66623   if( combined_flags&MEM_Str ){
66624     if( (f1 & MEM_Str)==0 ){
66625       return 1;
66626     }
66627     if( (f2 & MEM_Str)==0 ){
66628       return -1;
66629     }
66630 
66631     assert( pMem1->enc==pMem2->enc );
66632     assert( pMem1->enc==SQLITE_UTF8 ||
66633             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
66634 
66635     /* The collation sequence must be defined at this point, even if
66636     ** the user deletes the collation sequence after the vdbe program is
66637     ** compiled (this was not always the case).
66638     */
66639     assert( !pColl || pColl->xCmp );
66640 
66641     if( pColl ){
66642       return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
66643     }
66644     /* If a NULL pointer was passed as the collate function, fall through
66645     ** to the blob case and use memcmp().  */
66646   }
66647 
66648   /* Both values must be blobs.  Compare using memcmp().  */
66649   return sqlite3BlobCompare(pMem1, pMem2);
66650 }
66651 
66652 
66653 /*
66654 ** The first argument passed to this function is a serial-type that
66655 ** corresponds to an integer - all values between 1 and 9 inclusive
66656 ** except 7. The second points to a buffer containing an integer value
66657 ** serialized according to serial_type. This function deserializes
66658 ** and returns the value.
66659 */
66660 static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
66661   u32 y;
66662   assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
66663   switch( serial_type ){
66664     case 0:
66665     case 1:
66666       testcase( aKey[0]&0x80 );
66667       return ONE_BYTE_INT(aKey);
66668     case 2:
66669       testcase( aKey[0]&0x80 );
66670       return TWO_BYTE_INT(aKey);
66671     case 3:
66672       testcase( aKey[0]&0x80 );
66673       return THREE_BYTE_INT(aKey);
66674     case 4: {
66675       testcase( aKey[0]&0x80 );
66676       y = FOUR_BYTE_UINT(aKey);
66677       return (i64)*(int*)&y;
66678     }
66679     case 5: {
66680       testcase( aKey[0]&0x80 );
66681       return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
66682     }
66683     case 6: {
66684       u64 x = FOUR_BYTE_UINT(aKey);
66685       testcase( aKey[0]&0x80 );
66686       x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
66687       return (i64)*(i64*)&x;
66688     }
66689   }
66690 
66691   return (serial_type - 8);
66692 }
66693 
66694 /*
66695 ** This function compares the two table rows or index records
66696 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
66697 ** or positive integer if key1 is less than, equal to or
66698 ** greater than key2.  The {nKey1, pKey1} key must be a blob
66699 ** created by the OP_MakeRecord opcode of the VDBE.  The pPKey2
66700 ** key must be a parsed key such as obtained from
66701 ** sqlite3VdbeParseRecord.
66702 **
66703 ** If argument bSkip is non-zero, it is assumed that the caller has already
66704 ** determined that the first fields of the keys are equal.
66705 **
66706 ** Key1 and Key2 do not have to contain the same number of fields. If all
66707 ** fields that appear in both keys are equal, then pPKey2->default_rc is
66708 ** returned.
66709 **
66710 ** If database corruption is discovered, set pPKey2->errCode to
66711 ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
66712 ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
66713 ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
66714 */
66715 static int vdbeRecordCompareWithSkip(
66716   int nKey1, const void *pKey1,   /* Left key */
66717   UnpackedRecord *pPKey2,         /* Right key */
66718   int bSkip                       /* If true, skip the first field */
66719 ){
66720   u32 d1;                         /* Offset into aKey[] of next data element */
66721   int i;                          /* Index of next field to compare */
66722   u32 szHdr1;                     /* Size of record header in bytes */
66723   u32 idx1;                       /* Offset of first type in header */
66724   int rc = 0;                     /* Return value */
66725   Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
66726   KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
66727   const unsigned char *aKey1 = (const unsigned char *)pKey1;
66728   Mem mem1;
66729 
66730   /* If bSkip is true, then the caller has already determined that the first
66731   ** two elements in the keys are equal. Fix the various stack variables so
66732   ** that this routine begins comparing at the second field. */
66733   if( bSkip ){
66734     u32 s1;
66735     idx1 = 1 + getVarint32(&aKey1[1], s1);
66736     szHdr1 = aKey1[0];
66737     d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
66738     i = 1;
66739     pRhs++;
66740   }else{
66741     idx1 = getVarint32(aKey1, szHdr1);
66742     d1 = szHdr1;
66743     if( d1>(unsigned)nKey1 ){
66744       pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
66745       return 0;  /* Corruption */
66746     }
66747     i = 0;
66748   }
66749 
66750   VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
66751   assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
66752        || CORRUPT_DB );
66753   assert( pPKey2->pKeyInfo->aSortOrder!=0 );
66754   assert( pPKey2->pKeyInfo->nField>0 );
66755   assert( idx1<=szHdr1 || CORRUPT_DB );
66756   do{
66757     u32 serial_type;
66758 
66759     /* RHS is an integer */
66760     if( pRhs->flags & MEM_Int ){
66761       serial_type = aKey1[idx1];
66762       testcase( serial_type==12 );
66763       if( serial_type>=12 ){
66764         rc = +1;
66765       }else if( serial_type==0 ){
66766         rc = -1;
66767       }else if( serial_type==7 ){
66768         double rhs = (double)pRhs->u.i;
66769         sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
66770         if( mem1.u.r<rhs ){
66771           rc = -1;
66772         }else if( mem1.u.r>rhs ){
66773           rc = +1;
66774         }
66775       }else{
66776         i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
66777         i64 rhs = pRhs->u.i;
66778         if( lhs<rhs ){
66779           rc = -1;
66780         }else if( lhs>rhs ){
66781           rc = +1;
66782         }
66783       }
66784     }
66785 
66786     /* RHS is real */
66787     else if( pRhs->flags & MEM_Real ){
66788       serial_type = aKey1[idx1];
66789       if( serial_type>=12 ){
66790         rc = +1;
66791       }else if( serial_type==0 ){
66792         rc = -1;
66793       }else{
66794         double rhs = pRhs->u.r;
66795         double lhs;
66796         sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
66797         if( serial_type==7 ){
66798           lhs = mem1.u.r;
66799         }else{
66800           lhs = (double)mem1.u.i;
66801         }
66802         if( lhs<rhs ){
66803           rc = -1;
66804         }else if( lhs>rhs ){
66805           rc = +1;
66806         }
66807       }
66808     }
66809 
66810     /* RHS is a string */
66811     else if( pRhs->flags & MEM_Str ){
66812       getVarint32(&aKey1[idx1], serial_type);
66813       testcase( serial_type==12 );
66814       if( serial_type<12 ){
66815         rc = -1;
66816       }else if( !(serial_type & 0x01) ){
66817         rc = +1;
66818       }else{
66819         mem1.n = (serial_type - 12) / 2;
66820         testcase( (d1+mem1.n)==(unsigned)nKey1 );
66821         testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
66822         if( (d1+mem1.n) > (unsigned)nKey1 ){
66823           pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
66824           return 0;                /* Corruption */
66825         }else if( pKeyInfo->aColl[i] ){
66826           mem1.enc = pKeyInfo->enc;
66827           mem1.db = pKeyInfo->db;
66828           mem1.flags = MEM_Str;
66829           mem1.z = (char*)&aKey1[d1];
66830           rc = vdbeCompareMemString(
66831               &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
66832           );
66833         }else{
66834           int nCmp = MIN(mem1.n, pRhs->n);
66835           rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
66836           if( rc==0 ) rc = mem1.n - pRhs->n;
66837         }
66838       }
66839     }
66840 
66841     /* RHS is a blob */
66842     else if( pRhs->flags & MEM_Blob ){
66843       getVarint32(&aKey1[idx1], serial_type);
66844       testcase( serial_type==12 );
66845       if( serial_type<12 || (serial_type & 0x01) ){
66846         rc = -1;
66847       }else{
66848         int nStr = (serial_type - 12) / 2;
66849         testcase( (d1+nStr)==(unsigned)nKey1 );
66850         testcase( (d1+nStr+1)==(unsigned)nKey1 );
66851         if( (d1+nStr) > (unsigned)nKey1 ){
66852           pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
66853           return 0;                /* Corruption */
66854         }else{
66855           int nCmp = MIN(nStr, pRhs->n);
66856           rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
66857           if( rc==0 ) rc = nStr - pRhs->n;
66858         }
66859       }
66860     }
66861 
66862     /* RHS is null */
66863     else{
66864       serial_type = aKey1[idx1];
66865       rc = (serial_type!=0);
66866     }
66867 
66868     if( rc!=0 ){
66869       if( pKeyInfo->aSortOrder[i] ){
66870         rc = -rc;
66871       }
66872       assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
66873       assert( mem1.szMalloc==0 );  /* See comment below */
66874       return rc;
66875     }
66876 
66877     i++;
66878     pRhs++;
66879     d1 += sqlite3VdbeSerialTypeLen(serial_type);
66880     idx1 += sqlite3VarintLen(serial_type);
66881   }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
66882 
66883   /* No memory allocation is ever used on mem1.  Prove this using
66884   ** the following assert().  If the assert() fails, it indicates a
66885   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
66886   assert( mem1.szMalloc==0 );
66887 
66888   /* rc==0 here means that one or both of the keys ran out of fields and
66889   ** all the fields up to that point were equal. Return the default_rc
66890   ** value.  */
66891   assert( CORRUPT_DB
66892        || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
66893        || pKeyInfo->db->mallocFailed
66894   );
66895   return pPKey2->default_rc;
66896 }
66897 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
66898   int nKey1, const void *pKey1,   /* Left key */
66899   UnpackedRecord *pPKey2          /* Right key */
66900 ){
66901   return vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
66902 }
66903 
66904 
66905 /*
66906 ** This function is an optimized version of sqlite3VdbeRecordCompare()
66907 ** that (a) the first field of pPKey2 is an integer, and (b) the
66908 ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
66909 ** byte (i.e. is less than 128).
66910 **
66911 ** To avoid concerns about buffer overreads, this routine is only used
66912 ** on schemas where the maximum valid header size is 63 bytes or less.
66913 */
66914 static int vdbeRecordCompareInt(
66915   int nKey1, const void *pKey1, /* Left key */
66916   UnpackedRecord *pPKey2        /* Right key */
66917 ){
66918   const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
66919   int serial_type = ((const u8*)pKey1)[1];
66920   int res;
66921   u32 y;
66922   u64 x;
66923   i64 v = pPKey2->aMem[0].u.i;
66924   i64 lhs;
66925 
66926   assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
66927   switch( serial_type ){
66928     case 1: { /* 1-byte signed integer */
66929       lhs = ONE_BYTE_INT(aKey);
66930       testcase( lhs<0 );
66931       break;
66932     }
66933     case 2: { /* 2-byte signed integer */
66934       lhs = TWO_BYTE_INT(aKey);
66935       testcase( lhs<0 );
66936       break;
66937     }
66938     case 3: { /* 3-byte signed integer */
66939       lhs = THREE_BYTE_INT(aKey);
66940       testcase( lhs<0 );
66941       break;
66942     }
66943     case 4: { /* 4-byte signed integer */
66944       y = FOUR_BYTE_UINT(aKey);
66945       lhs = (i64)*(int*)&y;
66946       testcase( lhs<0 );
66947       break;
66948     }
66949     case 5: { /* 6-byte signed integer */
66950       lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
66951       testcase( lhs<0 );
66952       break;
66953     }
66954     case 6: { /* 8-byte signed integer */
66955       x = FOUR_BYTE_UINT(aKey);
66956       x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
66957       lhs = *(i64*)&x;
66958       testcase( lhs<0 );
66959       break;
66960     }
66961     case 8:
66962       lhs = 0;
66963       break;
66964     case 9:
66965       lhs = 1;
66966       break;
66967 
66968     /* This case could be removed without changing the results of running
66969     ** this code. Including it causes gcc to generate a faster switch
66970     ** statement (since the range of switch targets now starts at zero and
66971     ** is contiguous) but does not cause any duplicate code to be generated
66972     ** (as gcc is clever enough to combine the two like cases). Other
66973     ** compilers might be similar.  */
66974     case 0: case 7:
66975       return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
66976 
66977     default:
66978       return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
66979   }
66980 
66981   if( v>lhs ){
66982     res = pPKey2->r1;
66983   }else if( v<lhs ){
66984     res = pPKey2->r2;
66985   }else if( pPKey2->nField>1 ){
66986     /* The first fields of the two keys are equal. Compare the trailing
66987     ** fields.  */
66988     res = vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
66989   }else{
66990     /* The first fields of the two keys are equal and there are no trailing
66991     ** fields. Return pPKey2->default_rc in this case. */
66992     res = pPKey2->default_rc;
66993   }
66994 
66995   assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
66996   return res;
66997 }
66998 
66999 /*
67000 ** This function is an optimized version of sqlite3VdbeRecordCompare()
67001 ** that (a) the first field of pPKey2 is a string, that (b) the first field
67002 ** uses the collation sequence BINARY and (c) that the size-of-header varint
67003 ** at the start of (pKey1/nKey1) fits in a single byte.
67004 */
67005 static int vdbeRecordCompareString(
67006   int nKey1, const void *pKey1, /* Left key */
67007   UnpackedRecord *pPKey2        /* Right key */
67008 ){
67009   const u8 *aKey1 = (const u8*)pKey1;
67010   int serial_type;
67011   int res;
67012 
67013   getVarint32(&aKey1[1], serial_type);
67014   if( serial_type<12 ){
67015     res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
67016   }else if( !(serial_type & 0x01) ){
67017     res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
67018   }else{
67019     int nCmp;
67020     int nStr;
67021     int szHdr = aKey1[0];
67022 
67023     nStr = (serial_type-12) / 2;
67024     if( (szHdr + nStr) > nKey1 ){
67025       pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
67026       return 0;    /* Corruption */
67027     }
67028     nCmp = MIN( pPKey2->aMem[0].n, nStr );
67029     res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
67030 
67031     if( res==0 ){
67032       res = nStr - pPKey2->aMem[0].n;
67033       if( res==0 ){
67034         if( pPKey2->nField>1 ){
67035           res = vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
67036         }else{
67037           res = pPKey2->default_rc;
67038         }
67039       }else if( res>0 ){
67040         res = pPKey2->r2;
67041       }else{
67042         res = pPKey2->r1;
67043       }
67044     }else if( res>0 ){
67045       res = pPKey2->r2;
67046     }else{
67047       res = pPKey2->r1;
67048     }
67049   }
67050 
67051   assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
67052        || CORRUPT_DB
67053        || pPKey2->pKeyInfo->db->mallocFailed
67054   );
67055   return res;
67056 }
67057 
67058 /*
67059 ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
67060 ** suitable for comparing serialized records to the unpacked record passed
67061 ** as the only argument.
67062 */
67063 SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
67064   /* varintRecordCompareInt() and varintRecordCompareString() both assume
67065   ** that the size-of-header varint that occurs at the start of each record
67066   ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
67067   ** also assumes that it is safe to overread a buffer by at least the
67068   ** maximum possible legal header size plus 8 bytes. Because there is
67069   ** guaranteed to be at least 74 (but not 136) bytes of padding following each
67070   ** buffer passed to varintRecordCompareInt() this makes it convenient to
67071   ** limit the size of the header to 64 bytes in cases where the first field
67072   ** is an integer.
67073   **
67074   ** The easiest way to enforce this limit is to consider only records with
67075   ** 13 fields or less. If the first field is an integer, the maximum legal
67076   ** header size is (12*5 + 1 + 1) bytes.  */
67077   if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
67078     int flags = p->aMem[0].flags;
67079     if( p->pKeyInfo->aSortOrder[0] ){
67080       p->r1 = 1;
67081       p->r2 = -1;
67082     }else{
67083       p->r1 = -1;
67084       p->r2 = 1;
67085     }
67086     if( (flags & MEM_Int) ){
67087       return vdbeRecordCompareInt;
67088     }
67089     testcase( flags & MEM_Real );
67090     testcase( flags & MEM_Null );
67091     testcase( flags & MEM_Blob );
67092     if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
67093       assert( flags & MEM_Str );
67094       return vdbeRecordCompareString;
67095     }
67096   }
67097 
67098   return sqlite3VdbeRecordCompare;
67099 }
67100 
67101 /*
67102 ** pCur points at an index entry created using the OP_MakeRecord opcode.
67103 ** Read the rowid (the last field in the record) and store it in *rowid.
67104 ** Return SQLITE_OK if everything works, or an error code otherwise.
67105 **
67106 ** pCur might be pointing to text obtained from a corrupt database file.
67107 ** So the content cannot be trusted.  Do appropriate checks on the content.
67108 */
67109 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
67110   i64 nCellKey = 0;
67111   int rc;
67112   u32 szHdr;        /* Size of the header */
67113   u32 typeRowid;    /* Serial type of the rowid */
67114   u32 lenRowid;     /* Size of the rowid */
67115   Mem m, v;
67116 
67117   /* Get the size of the index entry.  Only indices entries of less
67118   ** than 2GiB are support - anything large must be database corruption.
67119   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
67120   ** this code can safely assume that nCellKey is 32-bits
67121   */
67122   assert( sqlite3BtreeCursorIsValid(pCur) );
67123   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
67124   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
67125   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
67126 
67127   /* Read in the complete content of the index entry */
67128   sqlite3VdbeMemInit(&m, db, 0);
67129   rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
67130   if( rc ){
67131     return rc;
67132   }
67133 
67134   /* The index entry must begin with a header size */
67135   (void)getVarint32((u8*)m.z, szHdr);
67136   testcase( szHdr==3 );
67137   testcase( szHdr==m.n );
67138   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
67139     goto idx_rowid_corruption;
67140   }
67141 
67142   /* The last field of the index should be an integer - the ROWID.
67143   ** Verify that the last entry really is an integer. */
67144   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
67145   testcase( typeRowid==1 );
67146   testcase( typeRowid==2 );
67147   testcase( typeRowid==3 );
67148   testcase( typeRowid==4 );
67149   testcase( typeRowid==5 );
67150   testcase( typeRowid==6 );
67151   testcase( typeRowid==8 );
67152   testcase( typeRowid==9 );
67153   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
67154     goto idx_rowid_corruption;
67155   }
67156   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
67157   testcase( (u32)m.n==szHdr+lenRowid );
67158   if( unlikely((u32)m.n<szHdr+lenRowid) ){
67159     goto idx_rowid_corruption;
67160   }
67161 
67162   /* Fetch the integer off the end of the index record */
67163   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
67164   *rowid = v.u.i;
67165   sqlite3VdbeMemRelease(&m);
67166   return SQLITE_OK;
67167 
67168   /* Jump here if database corruption is detected after m has been
67169   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
67170 idx_rowid_corruption:
67171   testcase( m.szMalloc!=0 );
67172   sqlite3VdbeMemRelease(&m);
67173   return SQLITE_CORRUPT_BKPT;
67174 }
67175 
67176 /*
67177 ** Compare the key of the index entry that cursor pC is pointing to against
67178 ** the key string in pUnpacked.  Write into *pRes a number
67179 ** that is negative, zero, or positive if pC is less than, equal to,
67180 ** or greater than pUnpacked.  Return SQLITE_OK on success.
67181 **
67182 ** pUnpacked is either created without a rowid or is truncated so that it
67183 ** omits the rowid at the end.  The rowid at the end of the index entry
67184 ** is ignored as well.  Hence, this routine only compares the prefixes
67185 ** of the keys prior to the final rowid, not the entire key.
67186 */
67187 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
67188   sqlite3 *db,                     /* Database connection */
67189   VdbeCursor *pC,                  /* The cursor to compare against */
67190   UnpackedRecord *pUnpacked,       /* Unpacked version of key */
67191   int *res                         /* Write the comparison result here */
67192 ){
67193   i64 nCellKey = 0;
67194   int rc;
67195   BtCursor *pCur = pC->pCursor;
67196   Mem m;
67197 
67198   assert( sqlite3BtreeCursorIsValid(pCur) );
67199   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
67200   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
67201   /* nCellKey will always be between 0 and 0xffffffff because of the way
67202   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
67203   if( nCellKey<=0 || nCellKey>0x7fffffff ){
67204     *res = 0;
67205     return SQLITE_CORRUPT_BKPT;
67206   }
67207   sqlite3VdbeMemInit(&m, db, 0);
67208   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (u32)nCellKey, 1, &m);
67209   if( rc ){
67210     return rc;
67211   }
67212   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
67213   sqlite3VdbeMemRelease(&m);
67214   return SQLITE_OK;
67215 }
67216 
67217 /*
67218 ** This routine sets the value to be returned by subsequent calls to
67219 ** sqlite3_changes() on the database handle 'db'.
67220 */
67221 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
67222   assert( sqlite3_mutex_held(db->mutex) );
67223   db->nChange = nChange;
67224   db->nTotalChange += nChange;
67225 }
67226 
67227 /*
67228 ** Set a flag in the vdbe to update the change counter when it is finalised
67229 ** or reset.
67230 */
67231 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
67232   v->changeCntOn = 1;
67233 }
67234 
67235 /*
67236 ** Mark every prepared statement associated with a database connection
67237 ** as expired.
67238 **
67239 ** An expired statement means that recompilation of the statement is
67240 ** recommend.  Statements expire when things happen that make their
67241 ** programs obsolete.  Removing user-defined functions or collating
67242 ** sequences, or changing an authorization function are the types of
67243 ** things that make prepared statements obsolete.
67244 */
67245 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
67246   Vdbe *p;
67247   for(p = db->pVdbe; p; p=p->pNext){
67248     p->expired = 1;
67249   }
67250 }
67251 
67252 /*
67253 ** Return the database associated with the Vdbe.
67254 */
67255 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
67256   return v->db;
67257 }
67258 
67259 /*
67260 ** Return a pointer to an sqlite3_value structure containing the value bound
67261 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
67262 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
67263 ** constants) to the value before returning it.
67264 **
67265 ** The returned value must be freed by the caller using sqlite3ValueFree().
67266 */
67267 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
67268   assert( iVar>0 );
67269   if( v ){
67270     Mem *pMem = &v->aVar[iVar-1];
67271     if( 0==(pMem->flags & MEM_Null) ){
67272       sqlite3_value *pRet = sqlite3ValueNew(v->db);
67273       if( pRet ){
67274         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
67275         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
67276       }
67277       return pRet;
67278     }
67279   }
67280   return 0;
67281 }
67282 
67283 /*
67284 ** Configure SQL variable iVar so that binding a new value to it signals
67285 ** to sqlite3_reoptimize() that re-preparing the statement may result
67286 ** in a better query plan.
67287 */
67288 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
67289   assert( iVar>0 );
67290   if( iVar>32 ){
67291     v->expmask = 0xffffffff;
67292   }else{
67293     v->expmask |= ((u32)1 << (iVar-1));
67294   }
67295 }
67296 
67297 #ifndef SQLITE_OMIT_VIRTUALTABLE
67298 /*
67299 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
67300 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
67301 ** in memory obtained from sqlite3DbMalloc).
67302 */
67303 SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
67304   sqlite3 *db = p->db;
67305   sqlite3DbFree(db, p->zErrMsg);
67306   p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
67307   sqlite3_free(pVtab->zErrMsg);
67308   pVtab->zErrMsg = 0;
67309 }
67310 #endif /* SQLITE_OMIT_VIRTUALTABLE */
67311 
67312 /************** End of vdbeaux.c *********************************************/
67313 /************** Begin file vdbeapi.c *****************************************/
67314 /*
67315 ** 2004 May 26
67316 **
67317 ** The author disclaims copyright to this source code.  In place of
67318 ** a legal notice, here is a blessing:
67319 **
67320 **    May you do good and not evil.
67321 **    May you find forgiveness for yourself and forgive others.
67322 **    May you share freely, never taking more than you give.
67323 **
67324 *************************************************************************
67325 **
67326 ** This file contains code use to implement APIs that are part of the
67327 ** VDBE.
67328 */
67329 
67330 #ifndef SQLITE_OMIT_DEPRECATED
67331 /*
67332 ** Return TRUE (non-zero) of the statement supplied as an argument needs
67333 ** to be recompiled.  A statement needs to be recompiled whenever the
67334 ** execution environment changes in a way that would alter the program
67335 ** that sqlite3_prepare() generates.  For example, if new functions or
67336 ** collating sequences are registered or if an authorizer function is
67337 ** added or changed.
67338 */
67339 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
67340   Vdbe *p = (Vdbe*)pStmt;
67341   return p==0 || p->expired;
67342 }
67343 #endif
67344 
67345 /*
67346 ** Check on a Vdbe to make sure it has not been finalized.  Log
67347 ** an error and return true if it has been finalized (or is otherwise
67348 ** invalid).  Return false if it is ok.
67349 */
67350 static int vdbeSafety(Vdbe *p){
67351   if( p->db==0 ){
67352     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
67353     return 1;
67354   }else{
67355     return 0;
67356   }
67357 }
67358 static int vdbeSafetyNotNull(Vdbe *p){
67359   if( p==0 ){
67360     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
67361     return 1;
67362   }else{
67363     return vdbeSafety(p);
67364   }
67365 }
67366 
67367 /*
67368 ** The following routine destroys a virtual machine that is created by
67369 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
67370 ** success/failure code that describes the result of executing the virtual
67371 ** machine.
67372 **
67373 ** This routine sets the error code and string returned by
67374 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
67375 */
67376 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
67377   int rc;
67378   if( pStmt==0 ){
67379     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
67380     ** pointer is a harmless no-op. */
67381     rc = SQLITE_OK;
67382   }else{
67383     Vdbe *v = (Vdbe*)pStmt;
67384     sqlite3 *db = v->db;
67385     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
67386     sqlite3_mutex_enter(db->mutex);
67387     rc = sqlite3VdbeFinalize(v);
67388     rc = sqlite3ApiExit(db, rc);
67389     sqlite3LeaveMutexAndCloseZombie(db);
67390   }
67391   return rc;
67392 }
67393 
67394 /*
67395 ** Terminate the current execution of an SQL statement and reset it
67396 ** back to its starting state so that it can be reused. A success code from
67397 ** the prior execution is returned.
67398 **
67399 ** This routine sets the error code and string returned by
67400 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
67401 */
67402 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
67403   int rc;
67404   if( pStmt==0 ){
67405     rc = SQLITE_OK;
67406   }else{
67407     Vdbe *v = (Vdbe*)pStmt;
67408     sqlite3_mutex_enter(v->db->mutex);
67409     rc = sqlite3VdbeReset(v);
67410     sqlite3VdbeRewind(v);
67411     assert( (rc & (v->db->errMask))==rc );
67412     rc = sqlite3ApiExit(v->db, rc);
67413     sqlite3_mutex_leave(v->db->mutex);
67414   }
67415   return rc;
67416 }
67417 
67418 /*
67419 ** Set all the parameters in the compiled SQL statement to NULL.
67420 */
67421 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
67422   int i;
67423   int rc = SQLITE_OK;
67424   Vdbe *p = (Vdbe*)pStmt;
67425 #if SQLITE_THREADSAFE
67426   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
67427 #endif
67428   sqlite3_mutex_enter(mutex);
67429   for(i=0; i<p->nVar; i++){
67430     sqlite3VdbeMemRelease(&p->aVar[i]);
67431     p->aVar[i].flags = MEM_Null;
67432   }
67433   if( p->isPrepareV2 && p->expmask ){
67434     p->expired = 1;
67435   }
67436   sqlite3_mutex_leave(mutex);
67437   return rc;
67438 }
67439 
67440 
67441 /**************************** sqlite3_value_  *******************************
67442 ** The following routines extract information from a Mem or sqlite3_value
67443 ** structure.
67444 */
67445 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
67446   Mem *p = (Mem*)pVal;
67447   if( p->flags & (MEM_Blob|MEM_Str) ){
67448     sqlite3VdbeMemExpandBlob(p);
67449     p->flags |= MEM_Blob;
67450     return p->n ? p->z : 0;
67451   }else{
67452     return sqlite3_value_text(pVal);
67453   }
67454 }
67455 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
67456   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
67457 }
67458 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
67459   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
67460 }
67461 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
67462   return sqlite3VdbeRealValue((Mem*)pVal);
67463 }
67464 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
67465   return (int)sqlite3VdbeIntValue((Mem*)pVal);
67466 }
67467 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
67468   return sqlite3VdbeIntValue((Mem*)pVal);
67469 }
67470 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
67471   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
67472 }
67473 #ifndef SQLITE_OMIT_UTF16
67474 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
67475   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
67476 }
67477 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
67478   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
67479 }
67480 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
67481   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
67482 }
67483 #endif /* SQLITE_OMIT_UTF16 */
67484 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
67485   static const u8 aType[] = {
67486      SQLITE_BLOB,     /* 0x00 */
67487      SQLITE_NULL,     /* 0x01 */
67488      SQLITE_TEXT,     /* 0x02 */
67489      SQLITE_NULL,     /* 0x03 */
67490      SQLITE_INTEGER,  /* 0x04 */
67491      SQLITE_NULL,     /* 0x05 */
67492      SQLITE_INTEGER,  /* 0x06 */
67493      SQLITE_NULL,     /* 0x07 */
67494      SQLITE_FLOAT,    /* 0x08 */
67495      SQLITE_NULL,     /* 0x09 */
67496      SQLITE_FLOAT,    /* 0x0a */
67497      SQLITE_NULL,     /* 0x0b */
67498      SQLITE_INTEGER,  /* 0x0c */
67499      SQLITE_NULL,     /* 0x0d */
67500      SQLITE_INTEGER,  /* 0x0e */
67501      SQLITE_NULL,     /* 0x0f */
67502      SQLITE_BLOB,     /* 0x10 */
67503      SQLITE_NULL,     /* 0x11 */
67504      SQLITE_TEXT,     /* 0x12 */
67505      SQLITE_NULL,     /* 0x13 */
67506      SQLITE_INTEGER,  /* 0x14 */
67507      SQLITE_NULL,     /* 0x15 */
67508      SQLITE_INTEGER,  /* 0x16 */
67509      SQLITE_NULL,     /* 0x17 */
67510      SQLITE_FLOAT,    /* 0x18 */
67511      SQLITE_NULL,     /* 0x19 */
67512      SQLITE_FLOAT,    /* 0x1a */
67513      SQLITE_NULL,     /* 0x1b */
67514      SQLITE_INTEGER,  /* 0x1c */
67515      SQLITE_NULL,     /* 0x1d */
67516      SQLITE_INTEGER,  /* 0x1e */
67517      SQLITE_NULL,     /* 0x1f */
67518   };
67519   return aType[pVal->flags&MEM_AffMask];
67520 }
67521 
67522 /**************************** sqlite3_result_  *******************************
67523 ** The following routines are used by user-defined functions to specify
67524 ** the function result.
67525 **
67526 ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
67527 ** result as a string or blob but if the string or blob is too large, it
67528 ** then sets the error code to SQLITE_TOOBIG
67529 **
67530 ** The invokeValueDestructor(P,X) routine invokes destructor function X()
67531 ** on value P is not going to be used and need to be destroyed.
67532 */
67533 static void setResultStrOrError(
67534   sqlite3_context *pCtx,  /* Function context */
67535   const char *z,          /* String pointer */
67536   int n,                  /* Bytes in string, or negative */
67537   u8 enc,                 /* Encoding of z.  0 for BLOBs */
67538   void (*xDel)(void*)     /* Destructor function */
67539 ){
67540   if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
67541     sqlite3_result_error_toobig(pCtx);
67542   }
67543 }
67544 static int invokeValueDestructor(
67545   const void *p,             /* Value to destroy */
67546   void (*xDel)(void*),       /* The destructor */
67547   sqlite3_context *pCtx      /* Set a SQLITE_TOOBIG error if no NULL */
67548 ){
67549   assert( xDel!=SQLITE_DYNAMIC );
67550   if( xDel==0 ){
67551     /* noop */
67552   }else if( xDel==SQLITE_TRANSIENT ){
67553     /* noop */
67554   }else{
67555     xDel((void*)p);
67556   }
67557   if( pCtx ) sqlite3_result_error_toobig(pCtx);
67558   return SQLITE_TOOBIG;
67559 }
67560 SQLITE_API void sqlite3_result_blob(
67561   sqlite3_context *pCtx,
67562   const void *z,
67563   int n,
67564   void (*xDel)(void *)
67565 ){
67566   assert( n>=0 );
67567   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67568   setResultStrOrError(pCtx, z, n, 0, xDel);
67569 }
67570 SQLITE_API void sqlite3_result_blob64(
67571   sqlite3_context *pCtx,
67572   const void *z,
67573   sqlite3_uint64 n,
67574   void (*xDel)(void *)
67575 ){
67576   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67577   assert( xDel!=SQLITE_DYNAMIC );
67578   if( n>0x7fffffff ){
67579     (void)invokeValueDestructor(z, xDel, pCtx);
67580   }else{
67581     setResultStrOrError(pCtx, z, (int)n, 0, xDel);
67582   }
67583 }
67584 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
67585   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67586   sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
67587 }
67588 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
67589   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67590   pCtx->isError = SQLITE_ERROR;
67591   pCtx->fErrorOrAux = 1;
67592   sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
67593 }
67594 #ifndef SQLITE_OMIT_UTF16
67595 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
67596   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67597   pCtx->isError = SQLITE_ERROR;
67598   pCtx->fErrorOrAux = 1;
67599   sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
67600 }
67601 #endif
67602 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
67603   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67604   sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
67605 }
67606 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
67607   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67608   sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
67609 }
67610 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
67611   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67612   sqlite3VdbeMemSetNull(pCtx->pOut);
67613 }
67614 SQLITE_API void sqlite3_result_text(
67615   sqlite3_context *pCtx,
67616   const char *z,
67617   int n,
67618   void (*xDel)(void *)
67619 ){
67620   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67621   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
67622 }
67623 SQLITE_API void sqlite3_result_text64(
67624   sqlite3_context *pCtx,
67625   const char *z,
67626   sqlite3_uint64 n,
67627   void (*xDel)(void *),
67628   unsigned char enc
67629 ){
67630   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67631   assert( xDel!=SQLITE_DYNAMIC );
67632   if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
67633   if( n>0x7fffffff ){
67634     (void)invokeValueDestructor(z, xDel, pCtx);
67635   }else{
67636     setResultStrOrError(pCtx, z, (int)n, enc, xDel);
67637   }
67638 }
67639 #ifndef SQLITE_OMIT_UTF16
67640 SQLITE_API void sqlite3_result_text16(
67641   sqlite3_context *pCtx,
67642   const void *z,
67643   int n,
67644   void (*xDel)(void *)
67645 ){
67646   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67647   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
67648 }
67649 SQLITE_API void sqlite3_result_text16be(
67650   sqlite3_context *pCtx,
67651   const void *z,
67652   int n,
67653   void (*xDel)(void *)
67654 ){
67655   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67656   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
67657 }
67658 SQLITE_API void sqlite3_result_text16le(
67659   sqlite3_context *pCtx,
67660   const void *z,
67661   int n,
67662   void (*xDel)(void *)
67663 ){
67664   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67665   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
67666 }
67667 #endif /* SQLITE_OMIT_UTF16 */
67668 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
67669   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67670   sqlite3VdbeMemCopy(pCtx->pOut, pValue);
67671 }
67672 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
67673   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67674   sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
67675 }
67676 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
67677   pCtx->isError = errCode;
67678   pCtx->fErrorOrAux = 1;
67679   if( pCtx->pOut->flags & MEM_Null ){
67680     sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
67681                          SQLITE_UTF8, SQLITE_STATIC);
67682   }
67683 }
67684 
67685 /* Force an SQLITE_TOOBIG error. */
67686 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
67687   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67688   pCtx->isError = SQLITE_TOOBIG;
67689   pCtx->fErrorOrAux = 1;
67690   sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
67691                        SQLITE_UTF8, SQLITE_STATIC);
67692 }
67693 
67694 /* An SQLITE_NOMEM error. */
67695 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
67696   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
67697   sqlite3VdbeMemSetNull(pCtx->pOut);
67698   pCtx->isError = SQLITE_NOMEM;
67699   pCtx->fErrorOrAux = 1;
67700   pCtx->pOut->db->mallocFailed = 1;
67701 }
67702 
67703 /*
67704 ** This function is called after a transaction has been committed. It
67705 ** invokes callbacks registered with sqlite3_wal_hook() as required.
67706 */
67707 static int doWalCallbacks(sqlite3 *db){
67708   int rc = SQLITE_OK;
67709 #ifndef SQLITE_OMIT_WAL
67710   int i;
67711   for(i=0; i<db->nDb; i++){
67712     Btree *pBt = db->aDb[i].pBt;
67713     if( pBt ){
67714       int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
67715       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
67716         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
67717       }
67718     }
67719   }
67720 #endif
67721   return rc;
67722 }
67723 
67724 /*
67725 ** Execute the statement pStmt, either until a row of data is ready, the
67726 ** statement is completely executed or an error occurs.
67727 **
67728 ** This routine implements the bulk of the logic behind the sqlite_step()
67729 ** API.  The only thing omitted is the automatic recompile if a
67730 ** schema change has occurred.  That detail is handled by the
67731 ** outer sqlite3_step() wrapper procedure.
67732 */
67733 static int sqlite3Step(Vdbe *p){
67734   sqlite3 *db;
67735   int rc;
67736 
67737   assert(p);
67738   if( p->magic!=VDBE_MAGIC_RUN ){
67739     /* We used to require that sqlite3_reset() be called before retrying
67740     ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
67741     ** with version 3.7.0, we changed this so that sqlite3_reset() would
67742     ** be called automatically instead of throwing the SQLITE_MISUSE error.
67743     ** This "automatic-reset" change is not technically an incompatibility,
67744     ** since any application that receives an SQLITE_MISUSE is broken by
67745     ** definition.
67746     **
67747     ** Nevertheless, some published applications that were originally written
67748     ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
67749     ** returns, and those were broken by the automatic-reset change.  As a
67750     ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
67751     ** legacy behavior of returning SQLITE_MISUSE for cases where the
67752     ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
67753     ** or SQLITE_BUSY error.
67754     */
67755 #ifdef SQLITE_OMIT_AUTORESET
67756     if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
67757       sqlite3_reset((sqlite3_stmt*)p);
67758     }else{
67759       return SQLITE_MISUSE_BKPT;
67760     }
67761 #else
67762     sqlite3_reset((sqlite3_stmt*)p);
67763 #endif
67764   }
67765 
67766   /* Check that malloc() has not failed. If it has, return early. */
67767   db = p->db;
67768   if( db->mallocFailed ){
67769     p->rc = SQLITE_NOMEM;
67770     return SQLITE_NOMEM;
67771   }
67772 
67773   if( p->pc<=0 && p->expired ){
67774     p->rc = SQLITE_SCHEMA;
67775     rc = SQLITE_ERROR;
67776     goto end_of_step;
67777   }
67778   if( p->pc<0 ){
67779     /* If there are no other statements currently running, then
67780     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
67781     ** from interrupting a statement that has not yet started.
67782     */
67783     if( db->nVdbeActive==0 ){
67784       db->u1.isInterrupted = 0;
67785     }
67786 
67787     assert( db->nVdbeWrite>0 || db->autoCommit==0
67788         || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
67789     );
67790 
67791 #ifndef SQLITE_OMIT_TRACE
67792     if( db->xProfile && !db->init.busy ){
67793       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
67794     }
67795 #endif
67796 
67797     db->nVdbeActive++;
67798     if( p->readOnly==0 ) db->nVdbeWrite++;
67799     if( p->bIsReader ) db->nVdbeRead++;
67800     p->pc = 0;
67801   }
67802 #ifndef SQLITE_OMIT_EXPLAIN
67803   if( p->explain ){
67804     rc = sqlite3VdbeList(p);
67805   }else
67806 #endif /* SQLITE_OMIT_EXPLAIN */
67807   {
67808     db->nVdbeExec++;
67809     rc = sqlite3VdbeExec(p);
67810     db->nVdbeExec--;
67811   }
67812 
67813 #ifndef SQLITE_OMIT_TRACE
67814   /* Invoke the profile callback if there is one
67815   */
67816   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
67817     sqlite3_int64 iNow;
67818     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
67819     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
67820   }
67821 #endif
67822 
67823   if( rc==SQLITE_DONE ){
67824     assert( p->rc==SQLITE_OK );
67825     p->rc = doWalCallbacks(db);
67826     if( p->rc!=SQLITE_OK ){
67827       rc = SQLITE_ERROR;
67828     }
67829   }
67830 
67831   db->errCode = rc;
67832   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
67833     p->rc = SQLITE_NOMEM;
67834   }
67835 end_of_step:
67836   /* At this point local variable rc holds the value that should be
67837   ** returned if this statement was compiled using the legacy
67838   ** sqlite3_prepare() interface. According to the docs, this can only
67839   ** be one of the values in the first assert() below. Variable p->rc
67840   ** contains the value that would be returned if sqlite3_finalize()
67841   ** were called on statement p.
67842   */
67843   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
67844        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
67845   );
67846   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
67847   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
67848     /* If this statement was prepared using sqlite3_prepare_v2(), and an
67849     ** error has occurred, then return the error code in p->rc to the
67850     ** caller. Set the error code in the database handle to the same value.
67851     */
67852     rc = sqlite3VdbeTransferError(p);
67853   }
67854   return (rc&db->errMask);
67855 }
67856 
67857 /*
67858 ** This is the top-level implementation of sqlite3_step().  Call
67859 ** sqlite3Step() to do most of the work.  If a schema error occurs,
67860 ** call sqlite3Reprepare() and try again.
67861 */
67862 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
67863   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
67864   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
67865   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
67866   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
67867   sqlite3 *db;             /* The database connection */
67868 
67869   if( vdbeSafetyNotNull(v) ){
67870     return SQLITE_MISUSE_BKPT;
67871   }
67872   db = v->db;
67873   sqlite3_mutex_enter(db->mutex);
67874   v->doingRerun = 0;
67875   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
67876          && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
67877     int savedPc = v->pc;
67878     rc2 = rc = sqlite3Reprepare(v);
67879     if( rc!=SQLITE_OK) break;
67880     sqlite3_reset(pStmt);
67881     if( savedPc>=0 ) v->doingRerun = 1;
67882     assert( v->expired==0 );
67883   }
67884   if( rc2!=SQLITE_OK ){
67885     /* This case occurs after failing to recompile an sql statement.
67886     ** The error message from the SQL compiler has already been loaded
67887     ** into the database handle. This block copies the error message
67888     ** from the database handle into the statement and sets the statement
67889     ** program counter to 0 to ensure that when the statement is
67890     ** finalized or reset the parser error message is available via
67891     ** sqlite3_errmsg() and sqlite3_errcode().
67892     */
67893     const char *zErr = (const char *)sqlite3_value_text(db->pErr);
67894     assert( zErr!=0 || db->mallocFailed );
67895     sqlite3DbFree(db, v->zErrMsg);
67896     if( !db->mallocFailed ){
67897       v->zErrMsg = sqlite3DbStrDup(db, zErr);
67898       v->rc = rc2;
67899     } else {
67900       v->zErrMsg = 0;
67901       v->rc = rc = SQLITE_NOMEM;
67902     }
67903   }
67904   rc = sqlite3ApiExit(db, rc);
67905   sqlite3_mutex_leave(db->mutex);
67906   return rc;
67907 }
67908 
67909 
67910 /*
67911 ** Extract the user data from a sqlite3_context structure and return a
67912 ** pointer to it.
67913 */
67914 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
67915   assert( p && p->pFunc );
67916   return p->pFunc->pUserData;
67917 }
67918 
67919 /*
67920 ** Extract the user data from a sqlite3_context structure and return a
67921 ** pointer to it.
67922 **
67923 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
67924 ** returns a copy of the pointer to the database connection (the 1st
67925 ** parameter) of the sqlite3_create_function() and
67926 ** sqlite3_create_function16() routines that originally registered the
67927 ** application defined function.
67928 */
67929 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
67930   assert( p && p->pFunc );
67931   return p->pOut->db;
67932 }
67933 
67934 /*
67935 ** Return the current time for a statement
67936 */
67937 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
67938   Vdbe *v = p->pVdbe;
67939   int rc;
67940   if( v->iCurrentTime==0 ){
67941     rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, &v->iCurrentTime);
67942     if( rc ) v->iCurrentTime = 0;
67943   }
67944   return v->iCurrentTime;
67945 }
67946 
67947 /*
67948 ** The following is the implementation of an SQL function that always
67949 ** fails with an error message stating that the function is used in the
67950 ** wrong context.  The sqlite3_overload_function() API might construct
67951 ** SQL function that use this routine so that the functions will exist
67952 ** for name resolution but are actually overloaded by the xFindFunction
67953 ** method of virtual tables.
67954 */
67955 SQLITE_PRIVATE void sqlite3InvalidFunction(
67956   sqlite3_context *context,  /* The function calling context */
67957   int NotUsed,               /* Number of arguments to the function */
67958   sqlite3_value **NotUsed2   /* Value of each argument */
67959 ){
67960   const char *zName = context->pFunc->zName;
67961   char *zErr;
67962   UNUSED_PARAMETER2(NotUsed, NotUsed2);
67963   zErr = sqlite3_mprintf(
67964       "unable to use function %s in the requested context", zName);
67965   sqlite3_result_error(context, zErr, -1);
67966   sqlite3_free(zErr);
67967 }
67968 
67969 /*
67970 ** Create a new aggregate context for p and return a pointer to
67971 ** its pMem->z element.
67972 */
67973 static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
67974   Mem *pMem = p->pMem;
67975   assert( (pMem->flags & MEM_Agg)==0 );
67976   if( nByte<=0 ){
67977     sqlite3VdbeMemSetNull(pMem);
67978     pMem->z = 0;
67979   }else{
67980     sqlite3VdbeMemClearAndResize(pMem, nByte);
67981     pMem->flags = MEM_Agg;
67982     pMem->u.pDef = p->pFunc;
67983     if( pMem->z ){
67984       memset(pMem->z, 0, nByte);
67985     }
67986   }
67987   return (void*)pMem->z;
67988 }
67989 
67990 /*
67991 ** Allocate or return the aggregate context for a user function.  A new
67992 ** context is allocated on the first call.  Subsequent calls return the
67993 ** same context that was returned on prior calls.
67994 */
67995 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
67996   assert( p && p->pFunc && p->pFunc->xStep );
67997   assert( sqlite3_mutex_held(p->pOut->db->mutex) );
67998   testcase( nByte<0 );
67999   if( (p->pMem->flags & MEM_Agg)==0 ){
68000     return createAggContext(p, nByte);
68001   }else{
68002     return (void*)p->pMem->z;
68003   }
68004 }
68005 
68006 /*
68007 ** Return the auxiliary data pointer, if any, for the iArg'th argument to
68008 ** the user-function defined by pCtx.
68009 */
68010 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
68011   AuxData *pAuxData;
68012 
68013   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
68014   for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
68015     if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
68016   }
68017 
68018   return (pAuxData ? pAuxData->pAux : 0);
68019 }
68020 
68021 /*
68022 ** Set the auxiliary data pointer and delete function, for the iArg'th
68023 ** argument to the user-function defined by pCtx. Any previous value is
68024 ** deleted by calling the delete function specified when it was set.
68025 */
68026 SQLITE_API void sqlite3_set_auxdata(
68027   sqlite3_context *pCtx,
68028   int iArg,
68029   void *pAux,
68030   void (*xDelete)(void*)
68031 ){
68032   AuxData *pAuxData;
68033   Vdbe *pVdbe = pCtx->pVdbe;
68034 
68035   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
68036   if( iArg<0 ) goto failed;
68037 
68038   for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
68039     if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
68040   }
68041   if( pAuxData==0 ){
68042     pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
68043     if( !pAuxData ) goto failed;
68044     pAuxData->iOp = pCtx->iOp;
68045     pAuxData->iArg = iArg;
68046     pAuxData->pNext = pVdbe->pAuxData;
68047     pVdbe->pAuxData = pAuxData;
68048     if( pCtx->fErrorOrAux==0 ){
68049       pCtx->isError = 0;
68050       pCtx->fErrorOrAux = 1;
68051     }
68052   }else if( pAuxData->xDelete ){
68053     pAuxData->xDelete(pAuxData->pAux);
68054   }
68055 
68056   pAuxData->pAux = pAux;
68057   pAuxData->xDelete = xDelete;
68058   return;
68059 
68060 failed:
68061   if( xDelete ){
68062     xDelete(pAux);
68063   }
68064 }
68065 
68066 #ifndef SQLITE_OMIT_DEPRECATED
68067 /*
68068 ** Return the number of times the Step function of an aggregate has been
68069 ** called.
68070 **
68071 ** This function is deprecated.  Do not use it for new code.  It is
68072 ** provide only to avoid breaking legacy code.  New aggregate function
68073 ** implementations should keep their own counts within their aggregate
68074 ** context.
68075 */
68076 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
68077   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
68078   return p->pMem->n;
68079 }
68080 #endif
68081 
68082 /*
68083 ** Return the number of columns in the result set for the statement pStmt.
68084 */
68085 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
68086   Vdbe *pVm = (Vdbe *)pStmt;
68087   return pVm ? pVm->nResColumn : 0;
68088 }
68089 
68090 /*
68091 ** Return the number of values available from the current row of the
68092 ** currently executing statement pStmt.
68093 */
68094 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
68095   Vdbe *pVm = (Vdbe *)pStmt;
68096   if( pVm==0 || pVm->pResultSet==0 ) return 0;
68097   return pVm->nResColumn;
68098 }
68099 
68100 /*
68101 ** Return a pointer to static memory containing an SQL NULL value.
68102 */
68103 static const Mem *columnNullValue(void){
68104   /* Even though the Mem structure contains an element
68105   ** of type i64, on certain architectures (x86) with certain compiler
68106   ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
68107   ** instead of an 8-byte one. This all works fine, except that when
68108   ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
68109   ** that a Mem structure is located on an 8-byte boundary. To prevent
68110   ** these assert()s from failing, when building with SQLITE_DEBUG defined
68111   ** using gcc, we force nullMem to be 8-byte aligned using the magical
68112   ** __attribute__((aligned(8))) macro.  */
68113   static const Mem nullMem
68114 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
68115     __attribute__((aligned(8)))
68116 #endif
68117     = {
68118         /* .u          = */ {0},
68119         /* .flags      = */ MEM_Null,
68120         /* .enc        = */ 0,
68121         /* .n          = */ 0,
68122         /* .z          = */ 0,
68123         /* .zMalloc    = */ 0,
68124         /* .szMalloc   = */ 0,
68125         /* .iPadding1  = */ 0,
68126         /* .db         = */ 0,
68127         /* .xDel       = */ 0,
68128 #ifdef SQLITE_DEBUG
68129         /* .pScopyFrom = */ 0,
68130         /* .pFiller    = */ 0,
68131 #endif
68132       };
68133   return &nullMem;
68134 }
68135 
68136 /*
68137 ** Check to see if column iCol of the given statement is valid.  If
68138 ** it is, return a pointer to the Mem for the value of that column.
68139 ** If iCol is not valid, return a pointer to a Mem which has a value
68140 ** of NULL.
68141 */
68142 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
68143   Vdbe *pVm;
68144   Mem *pOut;
68145 
68146   pVm = (Vdbe *)pStmt;
68147   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
68148     sqlite3_mutex_enter(pVm->db->mutex);
68149     pOut = &pVm->pResultSet[i];
68150   }else{
68151     if( pVm && ALWAYS(pVm->db) ){
68152       sqlite3_mutex_enter(pVm->db->mutex);
68153       sqlite3Error(pVm->db, SQLITE_RANGE);
68154     }
68155     pOut = (Mem*)columnNullValue();
68156   }
68157   return pOut;
68158 }
68159 
68160 /*
68161 ** This function is called after invoking an sqlite3_value_XXX function on a
68162 ** column value (i.e. a value returned by evaluating an SQL expression in the
68163 ** select list of a SELECT statement) that may cause a malloc() failure. If
68164 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
68165 ** code of statement pStmt set to SQLITE_NOMEM.
68166 **
68167 ** Specifically, this is called from within:
68168 **
68169 **     sqlite3_column_int()
68170 **     sqlite3_column_int64()
68171 **     sqlite3_column_text()
68172 **     sqlite3_column_text16()
68173 **     sqlite3_column_real()
68174 **     sqlite3_column_bytes()
68175 **     sqlite3_column_bytes16()
68176 **     sqiite3_column_blob()
68177 */
68178 static void columnMallocFailure(sqlite3_stmt *pStmt)
68179 {
68180   /* If malloc() failed during an encoding conversion within an
68181   ** sqlite3_column_XXX API, then set the return code of the statement to
68182   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
68183   ** and _finalize() will return NOMEM.
68184   */
68185   Vdbe *p = (Vdbe *)pStmt;
68186   if( p ){
68187     p->rc = sqlite3ApiExit(p->db, p->rc);
68188     sqlite3_mutex_leave(p->db->mutex);
68189   }
68190 }
68191 
68192 /**************************** sqlite3_column_  *******************************
68193 ** The following routines are used to access elements of the current row
68194 ** in the result set.
68195 */
68196 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
68197   const void *val;
68198   val = sqlite3_value_blob( columnMem(pStmt,i) );
68199   /* Even though there is no encoding conversion, value_blob() might
68200   ** need to call malloc() to expand the result of a zeroblob()
68201   ** expression.
68202   */
68203   columnMallocFailure(pStmt);
68204   return val;
68205 }
68206 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
68207   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
68208   columnMallocFailure(pStmt);
68209   return val;
68210 }
68211 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
68212   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
68213   columnMallocFailure(pStmt);
68214   return val;
68215 }
68216 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
68217   double val = sqlite3_value_double( columnMem(pStmt,i) );
68218   columnMallocFailure(pStmt);
68219   return val;
68220 }
68221 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
68222   int val = sqlite3_value_int( columnMem(pStmt,i) );
68223   columnMallocFailure(pStmt);
68224   return val;
68225 }
68226 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
68227   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
68228   columnMallocFailure(pStmt);
68229   return val;
68230 }
68231 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
68232   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
68233   columnMallocFailure(pStmt);
68234   return val;
68235 }
68236 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
68237   Mem *pOut = columnMem(pStmt, i);
68238   if( pOut->flags&MEM_Static ){
68239     pOut->flags &= ~MEM_Static;
68240     pOut->flags |= MEM_Ephem;
68241   }
68242   columnMallocFailure(pStmt);
68243   return (sqlite3_value *)pOut;
68244 }
68245 #ifndef SQLITE_OMIT_UTF16
68246 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
68247   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
68248   columnMallocFailure(pStmt);
68249   return val;
68250 }
68251 #endif /* SQLITE_OMIT_UTF16 */
68252 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
68253   int iType = sqlite3_value_type( columnMem(pStmt,i) );
68254   columnMallocFailure(pStmt);
68255   return iType;
68256 }
68257 
68258 /*
68259 ** Convert the N-th element of pStmt->pColName[] into a string using
68260 ** xFunc() then return that string.  If N is out of range, return 0.
68261 **
68262 ** There are up to 5 names for each column.  useType determines which
68263 ** name is returned.  Here are the names:
68264 **
68265 **    0      The column name as it should be displayed for output
68266 **    1      The datatype name for the column
68267 **    2      The name of the database that the column derives from
68268 **    3      The name of the table that the column derives from
68269 **    4      The name of the table column that the result column derives from
68270 **
68271 ** If the result is not a simple column reference (if it is an expression
68272 ** or a constant) then useTypes 2, 3, and 4 return NULL.
68273 */
68274 static const void *columnName(
68275   sqlite3_stmt *pStmt,
68276   int N,
68277   const void *(*xFunc)(Mem*),
68278   int useType
68279 ){
68280   const void *ret = 0;
68281   Vdbe *p = (Vdbe *)pStmt;
68282   int n;
68283   sqlite3 *db = p->db;
68284 
68285   assert( db!=0 );
68286   n = sqlite3_column_count(pStmt);
68287   if( N<n && N>=0 ){
68288     N += useType*n;
68289     sqlite3_mutex_enter(db->mutex);
68290     assert( db->mallocFailed==0 );
68291     ret = xFunc(&p->aColName[N]);
68292      /* A malloc may have failed inside of the xFunc() call. If this
68293     ** is the case, clear the mallocFailed flag and return NULL.
68294     */
68295     if( db->mallocFailed ){
68296       db->mallocFailed = 0;
68297       ret = 0;
68298     }
68299     sqlite3_mutex_leave(db->mutex);
68300   }
68301   return ret;
68302 }
68303 
68304 /*
68305 ** Return the name of the Nth column of the result set returned by SQL
68306 ** statement pStmt.
68307 */
68308 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
68309   return columnName(
68310       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
68311 }
68312 #ifndef SQLITE_OMIT_UTF16
68313 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
68314   return columnName(
68315       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
68316 }
68317 #endif
68318 
68319 /*
68320 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
68321 ** not define OMIT_DECLTYPE.
68322 */
68323 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
68324 # error "Must not define both SQLITE_OMIT_DECLTYPE \
68325          and SQLITE_ENABLE_COLUMN_METADATA"
68326 #endif
68327 
68328 #ifndef SQLITE_OMIT_DECLTYPE
68329 /*
68330 ** Return the column declaration type (if applicable) of the 'i'th column
68331 ** of the result set of SQL statement pStmt.
68332 */
68333 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
68334   return columnName(
68335       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
68336 }
68337 #ifndef SQLITE_OMIT_UTF16
68338 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
68339   return columnName(
68340       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
68341 }
68342 #endif /* SQLITE_OMIT_UTF16 */
68343 #endif /* SQLITE_OMIT_DECLTYPE */
68344 
68345 #ifdef SQLITE_ENABLE_COLUMN_METADATA
68346 /*
68347 ** Return the name of the database from which a result column derives.
68348 ** NULL is returned if the result column is an expression or constant or
68349 ** anything else which is not an unambiguous reference to a database column.
68350 */
68351 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
68352   return columnName(
68353       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
68354 }
68355 #ifndef SQLITE_OMIT_UTF16
68356 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
68357   return columnName(
68358       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
68359 }
68360 #endif /* SQLITE_OMIT_UTF16 */
68361 
68362 /*
68363 ** Return the name of the table from which a result column derives.
68364 ** NULL is returned if the result column is an expression or constant or
68365 ** anything else which is not an unambiguous reference to a database column.
68366 */
68367 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
68368   return columnName(
68369       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
68370 }
68371 #ifndef SQLITE_OMIT_UTF16
68372 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
68373   return columnName(
68374       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
68375 }
68376 #endif /* SQLITE_OMIT_UTF16 */
68377 
68378 /*
68379 ** Return the name of the table column from which a result column derives.
68380 ** NULL is returned if the result column is an expression or constant or
68381 ** anything else which is not an unambiguous reference to a database column.
68382 */
68383 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
68384   return columnName(
68385       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
68386 }
68387 #ifndef SQLITE_OMIT_UTF16
68388 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
68389   return columnName(
68390       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
68391 }
68392 #endif /* SQLITE_OMIT_UTF16 */
68393 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
68394 
68395 
68396 /******************************* sqlite3_bind_  ***************************
68397 **
68398 ** Routines used to attach values to wildcards in a compiled SQL statement.
68399 */
68400 /*
68401 ** Unbind the value bound to variable i in virtual machine p. This is the
68402 ** the same as binding a NULL value to the column. If the "i" parameter is
68403 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
68404 **
68405 ** A successful evaluation of this routine acquires the mutex on p.
68406 ** the mutex is released if any kind of error occurs.
68407 **
68408 ** The error code stored in database p->db is overwritten with the return
68409 ** value in any case.
68410 */
68411 static int vdbeUnbind(Vdbe *p, int i){
68412   Mem *pVar;
68413   if( vdbeSafetyNotNull(p) ){
68414     return SQLITE_MISUSE_BKPT;
68415   }
68416   sqlite3_mutex_enter(p->db->mutex);
68417   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
68418     sqlite3Error(p->db, SQLITE_MISUSE);
68419     sqlite3_mutex_leave(p->db->mutex);
68420     sqlite3_log(SQLITE_MISUSE,
68421         "bind on a busy prepared statement: [%s]", p->zSql);
68422     return SQLITE_MISUSE_BKPT;
68423   }
68424   if( i<1 || i>p->nVar ){
68425     sqlite3Error(p->db, SQLITE_RANGE);
68426     sqlite3_mutex_leave(p->db->mutex);
68427     return SQLITE_RANGE;
68428   }
68429   i--;
68430   pVar = &p->aVar[i];
68431   sqlite3VdbeMemRelease(pVar);
68432   pVar->flags = MEM_Null;
68433   sqlite3Error(p->db, SQLITE_OK);
68434 
68435   /* If the bit corresponding to this variable in Vdbe.expmask is set, then
68436   ** binding a new value to this variable invalidates the current query plan.
68437   **
68438   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
68439   ** parameter in the WHERE clause might influence the choice of query plan
68440   ** for a statement, then the statement will be automatically recompiled,
68441   ** as if there had been a schema change, on the first sqlite3_step() call
68442   ** following any change to the bindings of that parameter.
68443   */
68444   if( p->isPrepareV2 &&
68445      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
68446   ){
68447     p->expired = 1;
68448   }
68449   return SQLITE_OK;
68450 }
68451 
68452 /*
68453 ** Bind a text or BLOB value.
68454 */
68455 static int bindText(
68456   sqlite3_stmt *pStmt,   /* The statement to bind against */
68457   int i,                 /* Index of the parameter to bind */
68458   const void *zData,     /* Pointer to the data to be bound */
68459   int nData,             /* Number of bytes of data to be bound */
68460   void (*xDel)(void*),   /* Destructor for the data */
68461   u8 encoding            /* Encoding for the data */
68462 ){
68463   Vdbe *p = (Vdbe *)pStmt;
68464   Mem *pVar;
68465   int rc;
68466 
68467   rc = vdbeUnbind(p, i);
68468   if( rc==SQLITE_OK ){
68469     if( zData!=0 ){
68470       pVar = &p->aVar[i-1];
68471       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
68472       if( rc==SQLITE_OK && encoding!=0 ){
68473         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
68474       }
68475       sqlite3Error(p->db, rc);
68476       rc = sqlite3ApiExit(p->db, rc);
68477     }
68478     sqlite3_mutex_leave(p->db->mutex);
68479   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
68480     xDel((void*)zData);
68481   }
68482   return rc;
68483 }
68484 
68485 
68486 /*
68487 ** Bind a blob value to an SQL statement variable.
68488 */
68489 SQLITE_API int sqlite3_bind_blob(
68490   sqlite3_stmt *pStmt,
68491   int i,
68492   const void *zData,
68493   int nData,
68494   void (*xDel)(void*)
68495 ){
68496   return bindText(pStmt, i, zData, nData, xDel, 0);
68497 }
68498 SQLITE_API int sqlite3_bind_blob64(
68499   sqlite3_stmt *pStmt,
68500   int i,
68501   const void *zData,
68502   sqlite3_uint64 nData,
68503   void (*xDel)(void*)
68504 ){
68505   assert( xDel!=SQLITE_DYNAMIC );
68506   if( nData>0x7fffffff ){
68507     return invokeValueDestructor(zData, xDel, 0);
68508   }else{
68509     return bindText(pStmt, i, zData, (int)nData, xDel, 0);
68510   }
68511 }
68512 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
68513   int rc;
68514   Vdbe *p = (Vdbe *)pStmt;
68515   rc = vdbeUnbind(p, i);
68516   if( rc==SQLITE_OK ){
68517     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
68518     sqlite3_mutex_leave(p->db->mutex);
68519   }
68520   return rc;
68521 }
68522 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
68523   return sqlite3_bind_int64(p, i, (i64)iValue);
68524 }
68525 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
68526   int rc;
68527   Vdbe *p = (Vdbe *)pStmt;
68528   rc = vdbeUnbind(p, i);
68529   if( rc==SQLITE_OK ){
68530     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
68531     sqlite3_mutex_leave(p->db->mutex);
68532   }
68533   return rc;
68534 }
68535 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
68536   int rc;
68537   Vdbe *p = (Vdbe*)pStmt;
68538   rc = vdbeUnbind(p, i);
68539   if( rc==SQLITE_OK ){
68540     sqlite3_mutex_leave(p->db->mutex);
68541   }
68542   return rc;
68543 }
68544 SQLITE_API int sqlite3_bind_text(
68545   sqlite3_stmt *pStmt,
68546   int i,
68547   const char *zData,
68548   int nData,
68549   void (*xDel)(void*)
68550 ){
68551   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
68552 }
68553 SQLITE_API int sqlite3_bind_text64(
68554   sqlite3_stmt *pStmt,
68555   int i,
68556   const char *zData,
68557   sqlite3_uint64 nData,
68558   void (*xDel)(void*),
68559   unsigned char enc
68560 ){
68561   assert( xDel!=SQLITE_DYNAMIC );
68562   if( nData>0x7fffffff ){
68563     return invokeValueDestructor(zData, xDel, 0);
68564   }else{
68565     if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
68566     return bindText(pStmt, i, zData, (int)nData, xDel, enc);
68567   }
68568 }
68569 #ifndef SQLITE_OMIT_UTF16
68570 SQLITE_API int sqlite3_bind_text16(
68571   sqlite3_stmt *pStmt,
68572   int i,
68573   const void *zData,
68574   int nData,
68575   void (*xDel)(void*)
68576 ){
68577   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
68578 }
68579 #endif /* SQLITE_OMIT_UTF16 */
68580 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
68581   int rc;
68582   switch( sqlite3_value_type((sqlite3_value*)pValue) ){
68583     case SQLITE_INTEGER: {
68584       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
68585       break;
68586     }
68587     case SQLITE_FLOAT: {
68588       rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
68589       break;
68590     }
68591     case SQLITE_BLOB: {
68592       if( pValue->flags & MEM_Zero ){
68593         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
68594       }else{
68595         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
68596       }
68597       break;
68598     }
68599     case SQLITE_TEXT: {
68600       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
68601                               pValue->enc);
68602       break;
68603     }
68604     default: {
68605       rc = sqlite3_bind_null(pStmt, i);
68606       break;
68607     }
68608   }
68609   return rc;
68610 }
68611 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
68612   int rc;
68613   Vdbe *p = (Vdbe *)pStmt;
68614   rc = vdbeUnbind(p, i);
68615   if( rc==SQLITE_OK ){
68616     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
68617     sqlite3_mutex_leave(p->db->mutex);
68618   }
68619   return rc;
68620 }
68621 
68622 /*
68623 ** Return the number of wildcards that can be potentially bound to.
68624 ** This routine is added to support DBD::SQLite.
68625 */
68626 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
68627   Vdbe *p = (Vdbe*)pStmt;
68628   return p ? p->nVar : 0;
68629 }
68630 
68631 /*
68632 ** Return the name of a wildcard parameter.  Return NULL if the index
68633 ** is out of range or if the wildcard is unnamed.
68634 **
68635 ** The result is always UTF-8.
68636 */
68637 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
68638   Vdbe *p = (Vdbe*)pStmt;
68639   if( p==0 || i<1 || i>p->nzVar ){
68640     return 0;
68641   }
68642   return p->azVar[i-1];
68643 }
68644 
68645 /*
68646 ** Given a wildcard parameter name, return the index of the variable
68647 ** with that name.  If there is no variable with the given name,
68648 ** return 0.
68649 */
68650 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
68651   int i;
68652   if( p==0 ){
68653     return 0;
68654   }
68655   if( zName ){
68656     for(i=0; i<p->nzVar; i++){
68657       const char *z = p->azVar[i];
68658       if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
68659         return i+1;
68660       }
68661     }
68662   }
68663   return 0;
68664 }
68665 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
68666   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
68667 }
68668 
68669 /*
68670 ** Transfer all bindings from the first statement over to the second.
68671 */
68672 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
68673   Vdbe *pFrom = (Vdbe*)pFromStmt;
68674   Vdbe *pTo = (Vdbe*)pToStmt;
68675   int i;
68676   assert( pTo->db==pFrom->db );
68677   assert( pTo->nVar==pFrom->nVar );
68678   sqlite3_mutex_enter(pTo->db->mutex);
68679   for(i=0; i<pFrom->nVar; i++){
68680     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
68681   }
68682   sqlite3_mutex_leave(pTo->db->mutex);
68683   return SQLITE_OK;
68684 }
68685 
68686 #ifndef SQLITE_OMIT_DEPRECATED
68687 /*
68688 ** Deprecated external interface.  Internal/core SQLite code
68689 ** should call sqlite3TransferBindings.
68690 **
68691 ** It is misuse to call this routine with statements from different
68692 ** database connections.  But as this is a deprecated interface, we
68693 ** will not bother to check for that condition.
68694 **
68695 ** If the two statements contain a different number of bindings, then
68696 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
68697 ** SQLITE_OK is returned.
68698 */
68699 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
68700   Vdbe *pFrom = (Vdbe*)pFromStmt;
68701   Vdbe *pTo = (Vdbe*)pToStmt;
68702   if( pFrom->nVar!=pTo->nVar ){
68703     return SQLITE_ERROR;
68704   }
68705   if( pTo->isPrepareV2 && pTo->expmask ){
68706     pTo->expired = 1;
68707   }
68708   if( pFrom->isPrepareV2 && pFrom->expmask ){
68709     pFrom->expired = 1;
68710   }
68711   return sqlite3TransferBindings(pFromStmt, pToStmt);
68712 }
68713 #endif
68714 
68715 /*
68716 ** Return the sqlite3* database handle to which the prepared statement given
68717 ** in the argument belongs.  This is the same database handle that was
68718 ** the first argument to the sqlite3_prepare() that was used to create
68719 ** the statement in the first place.
68720 */
68721 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
68722   return pStmt ? ((Vdbe*)pStmt)->db : 0;
68723 }
68724 
68725 /*
68726 ** Return true if the prepared statement is guaranteed to not modify the
68727 ** database.
68728 */
68729 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
68730   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
68731 }
68732 
68733 /*
68734 ** Return true if the prepared statement is in need of being reset.
68735 */
68736 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
68737   Vdbe *v = (Vdbe*)pStmt;
68738   return v!=0 && v->pc>=0 && v->magic==VDBE_MAGIC_RUN;
68739 }
68740 
68741 /*
68742 ** Return a pointer to the next prepared statement after pStmt associated
68743 ** with database connection pDb.  If pStmt is NULL, return the first
68744 ** prepared statement for the database connection.  Return NULL if there
68745 ** are no more.
68746 */
68747 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
68748   sqlite3_stmt *pNext;
68749   sqlite3_mutex_enter(pDb->mutex);
68750   if( pStmt==0 ){
68751     pNext = (sqlite3_stmt*)pDb->pVdbe;
68752   }else{
68753     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
68754   }
68755   sqlite3_mutex_leave(pDb->mutex);
68756   return pNext;
68757 }
68758 
68759 /*
68760 ** Return the value of a status counter for a prepared statement
68761 */
68762 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
68763   Vdbe *pVdbe = (Vdbe*)pStmt;
68764   u32 v = pVdbe->aCounter[op];
68765   if( resetFlag ) pVdbe->aCounter[op] = 0;
68766   return (int)v;
68767 }
68768 
68769 /************** End of vdbeapi.c *********************************************/
68770 /************** Begin file vdbetrace.c ***************************************/
68771 /*
68772 ** 2009 November 25
68773 **
68774 ** The author disclaims copyright to this source code.  In place of
68775 ** a legal notice, here is a blessing:
68776 **
68777 **    May you do good and not evil.
68778 **    May you find forgiveness for yourself and forgive others.
68779 **    May you share freely, never taking more than you give.
68780 **
68781 *************************************************************************
68782 **
68783 ** This file contains code used to insert the values of host parameters
68784 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
68785 **
68786 ** The Vdbe parse-tree explainer is also found here.
68787 */
68788 
68789 #ifndef SQLITE_OMIT_TRACE
68790 
68791 /*
68792 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
68793 ** bytes in this text up to but excluding the first character in
68794 ** a host parameter.  If the text contains no host parameters, return
68795 ** the total number of bytes in the text.
68796 */
68797 static int findNextHostParameter(const char *zSql, int *pnToken){
68798   int tokenType;
68799   int nTotal = 0;
68800   int n;
68801 
68802   *pnToken = 0;
68803   while( zSql[0] ){
68804     n = sqlite3GetToken((u8*)zSql, &tokenType);
68805     assert( n>0 && tokenType!=TK_ILLEGAL );
68806     if( tokenType==TK_VARIABLE ){
68807       *pnToken = n;
68808       break;
68809     }
68810     nTotal += n;
68811     zSql += n;
68812   }
68813   return nTotal;
68814 }
68815 
68816 /*
68817 ** This function returns a pointer to a nul-terminated string in memory
68818 ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
68819 ** string contains a copy of zRawSql but with host parameters expanded to
68820 ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
68821 ** then the returned string holds a copy of zRawSql with "-- " prepended
68822 ** to each line of text.
68823 **
68824 ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
68825 ** then long strings and blobs are truncated to that many bytes.  This
68826 ** can be used to prevent unreasonably large trace strings when dealing
68827 ** with large (multi-megabyte) strings and blobs.
68828 **
68829 ** The calling function is responsible for making sure the memory returned
68830 ** is eventually freed.
68831 **
68832 ** ALGORITHM:  Scan the input string looking for host parameters in any of
68833 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
68834 ** string literals, quoted identifier names, and comments.  For text forms,
68835 ** the host parameter index is found by scanning the prepared
68836 ** statement for the corresponding OP_Variable opcode.  Once the host
68837 ** parameter index is known, locate the value in p->aVar[].  Then render
68838 ** the value as a literal in place of the host parameter name.
68839 */
68840 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
68841   Vdbe *p,                 /* The prepared statement being evaluated */
68842   const char *zRawSql      /* Raw text of the SQL statement */
68843 ){
68844   sqlite3 *db;             /* The database connection */
68845   int idx = 0;             /* Index of a host parameter */
68846   int nextIndex = 1;       /* Index of next ? host parameter */
68847   int n;                   /* Length of a token prefix */
68848   int nToken;              /* Length of the parameter token */
68849   int i;                   /* Loop counter */
68850   Mem *pVar;               /* Value of a host parameter */
68851   StrAccum out;            /* Accumulate the output here */
68852   char zBase[100];         /* Initial working space */
68853 
68854   db = p->db;
68855   sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
68856                       db->aLimit[SQLITE_LIMIT_LENGTH]);
68857   out.db = db;
68858   if( db->nVdbeExec>1 ){
68859     while( *zRawSql ){
68860       const char *zStart = zRawSql;
68861       while( *(zRawSql++)!='\n' && *zRawSql );
68862       sqlite3StrAccumAppend(&out, "-- ", 3);
68863       assert( (zRawSql - zStart) > 0 );
68864       sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
68865     }
68866   }else{
68867     while( zRawSql[0] ){
68868       n = findNextHostParameter(zRawSql, &nToken);
68869       assert( n>0 );
68870       sqlite3StrAccumAppend(&out, zRawSql, n);
68871       zRawSql += n;
68872       assert( zRawSql[0] || nToken==0 );
68873       if( nToken==0 ) break;
68874       if( zRawSql[0]=='?' ){
68875         if( nToken>1 ){
68876           assert( sqlite3Isdigit(zRawSql[1]) );
68877           sqlite3GetInt32(&zRawSql[1], &idx);
68878         }else{
68879           idx = nextIndex;
68880         }
68881       }else{
68882         assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
68883         testcase( zRawSql[0]==':' );
68884         testcase( zRawSql[0]=='$' );
68885         testcase( zRawSql[0]=='@' );
68886         idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
68887         assert( idx>0 );
68888       }
68889       zRawSql += nToken;
68890       nextIndex = idx + 1;
68891       assert( idx>0 && idx<=p->nVar );
68892       pVar = &p->aVar[idx-1];
68893       if( pVar->flags & MEM_Null ){
68894         sqlite3StrAccumAppend(&out, "NULL", 4);
68895       }else if( pVar->flags & MEM_Int ){
68896         sqlite3XPrintf(&out, 0, "%lld", pVar->u.i);
68897       }else if( pVar->flags & MEM_Real ){
68898         sqlite3XPrintf(&out, 0, "%!.15g", pVar->u.r);
68899       }else if( pVar->flags & MEM_Str ){
68900         int nOut;  /* Number of bytes of the string text to include in output */
68901 #ifndef SQLITE_OMIT_UTF16
68902         u8 enc = ENC(db);
68903         Mem utf8;
68904         if( enc!=SQLITE_UTF8 ){
68905           memset(&utf8, 0, sizeof(utf8));
68906           utf8.db = db;
68907           sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
68908           sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
68909           pVar = &utf8;
68910         }
68911 #endif
68912         nOut = pVar->n;
68913 #ifdef SQLITE_TRACE_SIZE_LIMIT
68914         if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
68915           nOut = SQLITE_TRACE_SIZE_LIMIT;
68916           while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
68917         }
68918 #endif
68919         sqlite3XPrintf(&out, 0, "'%.*q'", nOut, pVar->z);
68920 #ifdef SQLITE_TRACE_SIZE_LIMIT
68921         if( nOut<pVar->n ){
68922           sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
68923         }
68924 #endif
68925 #ifndef SQLITE_OMIT_UTF16
68926         if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
68927 #endif
68928       }else if( pVar->flags & MEM_Zero ){
68929         sqlite3XPrintf(&out, 0, "zeroblob(%d)", pVar->u.nZero);
68930       }else{
68931         int nOut;  /* Number of bytes of the blob to include in output */
68932         assert( pVar->flags & MEM_Blob );
68933         sqlite3StrAccumAppend(&out, "x'", 2);
68934         nOut = pVar->n;
68935 #ifdef SQLITE_TRACE_SIZE_LIMIT
68936         if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
68937 #endif
68938         for(i=0; i<nOut; i++){
68939           sqlite3XPrintf(&out, 0, "%02x", pVar->z[i]&0xff);
68940         }
68941         sqlite3StrAccumAppend(&out, "'", 1);
68942 #ifdef SQLITE_TRACE_SIZE_LIMIT
68943         if( nOut<pVar->n ){
68944           sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
68945         }
68946 #endif
68947       }
68948     }
68949   }
68950   return sqlite3StrAccumFinish(&out);
68951 }
68952 
68953 #endif /* #ifndef SQLITE_OMIT_TRACE */
68954 
68955 /************** End of vdbetrace.c *******************************************/
68956 /************** Begin file vdbe.c ********************************************/
68957 /*
68958 ** 2001 September 15
68959 **
68960 ** The author disclaims copyright to this source code.  In place of
68961 ** a legal notice, here is a blessing:
68962 **
68963 **    May you do good and not evil.
68964 **    May you find forgiveness for yourself and forgive others.
68965 **    May you share freely, never taking more than you give.
68966 **
68967 *************************************************************************
68968 ** The code in this file implements the function that runs the
68969 ** bytecode of a prepared statement.
68970 **
68971 ** Various scripts scan this source file in order to generate HTML
68972 ** documentation, headers files, or other derived files.  The formatting
68973 ** of the code in this file is, therefore, important.  See other comments
68974 ** in this file for details.  If in doubt, do not deviate from existing
68975 ** commenting and indentation practices when changing or adding code.
68976 */
68977 
68978 /*
68979 ** Invoke this macro on memory cells just prior to changing the
68980 ** value of the cell.  This macro verifies that shallow copies are
68981 ** not misused.  A shallow copy of a string or blob just copies a
68982 ** pointer to the string or blob, not the content.  If the original
68983 ** is changed while the copy is still in use, the string or blob might
68984 ** be changed out from under the copy.  This macro verifies that nothing
68985 ** like that ever happens.
68986 */
68987 #ifdef SQLITE_DEBUG
68988 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
68989 #else
68990 # define memAboutToChange(P,M)
68991 #endif
68992 
68993 /*
68994 ** The following global variable is incremented every time a cursor
68995 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
68996 ** procedures use this information to make sure that indices are
68997 ** working correctly.  This variable has no function other than to
68998 ** help verify the correct operation of the library.
68999 */
69000 #ifdef SQLITE_TEST
69001 SQLITE_API int sqlite3_search_count = 0;
69002 #endif
69003 
69004 /*
69005 ** When this global variable is positive, it gets decremented once before
69006 ** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
69007 ** field of the sqlite3 structure is set in order to simulate an interrupt.
69008 **
69009 ** This facility is used for testing purposes only.  It does not function
69010 ** in an ordinary build.
69011 */
69012 #ifdef SQLITE_TEST
69013 SQLITE_API int sqlite3_interrupt_count = 0;
69014 #endif
69015 
69016 /*
69017 ** The next global variable is incremented each type the OP_Sort opcode
69018 ** is executed.  The test procedures use this information to make sure that
69019 ** sorting is occurring or not occurring at appropriate times.   This variable
69020 ** has no function other than to help verify the correct operation of the
69021 ** library.
69022 */
69023 #ifdef SQLITE_TEST
69024 SQLITE_API int sqlite3_sort_count = 0;
69025 #endif
69026 
69027 /*
69028 ** The next global variable records the size of the largest MEM_Blob
69029 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
69030 ** use this information to make sure that the zero-blob functionality
69031 ** is working correctly.   This variable has no function other than to
69032 ** help verify the correct operation of the library.
69033 */
69034 #ifdef SQLITE_TEST
69035 SQLITE_API int sqlite3_max_blobsize = 0;
69036 static void updateMaxBlobsize(Mem *p){
69037   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
69038     sqlite3_max_blobsize = p->n;
69039   }
69040 }
69041 #endif
69042 
69043 /*
69044 ** The next global variable is incremented each time the OP_Found opcode
69045 ** is executed. This is used to test whether or not the foreign key
69046 ** operation implemented using OP_FkIsZero is working. This variable
69047 ** has no function other than to help verify the correct operation of the
69048 ** library.
69049 */
69050 #ifdef SQLITE_TEST
69051 SQLITE_API int sqlite3_found_count = 0;
69052 #endif
69053 
69054 /*
69055 ** Test a register to see if it exceeds the current maximum blob size.
69056 ** If it does, record the new maximum blob size.
69057 */
69058 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
69059 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
69060 #else
69061 # define UPDATE_MAX_BLOBSIZE(P)
69062 #endif
69063 
69064 /*
69065 ** Invoke the VDBE coverage callback, if that callback is defined.  This
69066 ** feature is used for test suite validation only and does not appear an
69067 ** production builds.
69068 **
69069 ** M is an integer, 2 or 3, that indices how many different ways the
69070 ** branch can go.  It is usually 2.  "I" is the direction the branch
69071 ** goes.  0 means falls through.  1 means branch is taken.  2 means the
69072 ** second alternative branch is taken.
69073 **
69074 ** iSrcLine is the source code line (from the __LINE__ macro) that
69075 ** generated the VDBE instruction.  This instrumentation assumes that all
69076 ** source code is in a single file (the amalgamation).  Special values 1
69077 ** and 2 for the iSrcLine parameter mean that this particular branch is
69078 ** always taken or never taken, respectively.
69079 */
69080 #if !defined(SQLITE_VDBE_COVERAGE)
69081 # define VdbeBranchTaken(I,M)
69082 #else
69083 # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
69084   static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
69085     if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
69086       M = iSrcLine;
69087       /* Assert the truth of VdbeCoverageAlwaysTaken() and
69088       ** VdbeCoverageNeverTaken() */
69089       assert( (M & I)==I );
69090     }else{
69091       if( sqlite3GlobalConfig.xVdbeBranch==0 ) return;  /*NO_TEST*/
69092       sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
69093                                       iSrcLine,I,M);
69094     }
69095   }
69096 #endif
69097 
69098 /*
69099 ** Convert the given register into a string if it isn't one
69100 ** already. Return non-zero if a malloc() fails.
69101 */
69102 #define Stringify(P, enc) \
69103    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
69104      { goto no_mem; }
69105 
69106 /*
69107 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
69108 ** a pointer to a dynamically allocated string where some other entity
69109 ** is responsible for deallocating that string.  Because the register
69110 ** does not control the string, it might be deleted without the register
69111 ** knowing it.
69112 **
69113 ** This routine converts an ephemeral string into a dynamically allocated
69114 ** string that the register itself controls.  In other words, it
69115 ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
69116 */
69117 #define Deephemeralize(P) \
69118    if( ((P)->flags&MEM_Ephem)!=0 \
69119        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
69120 
69121 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
69122 #define isSorter(x) ((x)->pSorter!=0)
69123 
69124 /*
69125 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
69126 ** if we run out of memory.
69127 */
69128 static VdbeCursor *allocateCursor(
69129   Vdbe *p,              /* The virtual machine */
69130   int iCur,             /* Index of the new VdbeCursor */
69131   int nField,           /* Number of fields in the table or index */
69132   int iDb,              /* Database the cursor belongs to, or -1 */
69133   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
69134 ){
69135   /* Find the memory cell that will be used to store the blob of memory
69136   ** required for this VdbeCursor structure. It is convenient to use a
69137   ** vdbe memory cell to manage the memory allocation required for a
69138   ** VdbeCursor structure for the following reasons:
69139   **
69140   **   * Sometimes cursor numbers are used for a couple of different
69141   **     purposes in a vdbe program. The different uses might require
69142   **     different sized allocations. Memory cells provide growable
69143   **     allocations.
69144   **
69145   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
69146   **     be freed lazily via the sqlite3_release_memory() API. This
69147   **     minimizes the number of malloc calls made by the system.
69148   **
69149   ** Memory cells for cursors are allocated at the top of the address
69150   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
69151   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
69152   */
69153   Mem *pMem = &p->aMem[p->nMem-iCur];
69154 
69155   int nByte;
69156   VdbeCursor *pCx = 0;
69157   nByte =
69158       ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
69159       (isBtreeCursor?sqlite3BtreeCursorSize():0);
69160 
69161   assert( iCur<p->nCursor );
69162   if( p->apCsr[iCur] ){
69163     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
69164     p->apCsr[iCur] = 0;
69165   }
69166   if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
69167     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
69168     memset(pCx, 0, sizeof(VdbeCursor));
69169     pCx->iDb = iDb;
69170     pCx->nField = nField;
69171     pCx->aOffset = &pCx->aType[nField];
69172     if( isBtreeCursor ){
69173       pCx->pCursor = (BtCursor*)
69174           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
69175       sqlite3BtreeCursorZero(pCx->pCursor);
69176     }
69177   }
69178   return pCx;
69179 }
69180 
69181 /*
69182 ** Try to convert a value into a numeric representation if we can
69183 ** do so without loss of information.  In other words, if the string
69184 ** looks like a number, convert it into a number.  If it does not
69185 ** look like a number, leave it alone.
69186 **
69187 ** If the bTryForInt flag is true, then extra effort is made to give
69188 ** an integer representation.  Strings that look like floating point
69189 ** values but which have no fractional component (example: '48.00')
69190 ** will have a MEM_Int representation when bTryForInt is true.
69191 **
69192 ** If bTryForInt is false, then if the input string contains a decimal
69193 ** point or exponential notation, the result is only MEM_Real, even
69194 ** if there is an exact integer representation of the quantity.
69195 */
69196 static void applyNumericAffinity(Mem *pRec, int bTryForInt){
69197   double rValue;
69198   i64 iValue;
69199   u8 enc = pRec->enc;
69200   assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
69201   if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
69202   if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
69203     pRec->u.i = iValue;
69204     pRec->flags |= MEM_Int;
69205   }else{
69206     pRec->u.r = rValue;
69207     pRec->flags |= MEM_Real;
69208     if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
69209   }
69210 }
69211 
69212 /*
69213 ** Processing is determine by the affinity parameter:
69214 **
69215 ** SQLITE_AFF_INTEGER:
69216 ** SQLITE_AFF_REAL:
69217 ** SQLITE_AFF_NUMERIC:
69218 **    Try to convert pRec to an integer representation or a
69219 **    floating-point representation if an integer representation
69220 **    is not possible.  Note that the integer representation is
69221 **    always preferred, even if the affinity is REAL, because
69222 **    an integer representation is more space efficient on disk.
69223 **
69224 ** SQLITE_AFF_TEXT:
69225 **    Convert pRec to a text representation.
69226 **
69227 ** SQLITE_AFF_NONE:
69228 **    No-op.  pRec is unchanged.
69229 */
69230 static void applyAffinity(
69231   Mem *pRec,          /* The value to apply affinity to */
69232   char affinity,      /* The affinity to be applied */
69233   u8 enc              /* Use this text encoding */
69234 ){
69235   if( affinity>=SQLITE_AFF_NUMERIC ){
69236     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
69237              || affinity==SQLITE_AFF_NUMERIC );
69238     if( (pRec->flags & MEM_Int)==0 ){
69239       if( (pRec->flags & MEM_Real)==0 ){
69240         if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
69241       }else{
69242         sqlite3VdbeIntegerAffinity(pRec);
69243       }
69244     }
69245   }else if( affinity==SQLITE_AFF_TEXT ){
69246     /* Only attempt the conversion to TEXT if there is an integer or real
69247     ** representation (blob and NULL do not get converted) but no string
69248     ** representation.
69249     */
69250     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
69251       sqlite3VdbeMemStringify(pRec, enc, 1);
69252     }
69253   }
69254 }
69255 
69256 /*
69257 ** Try to convert the type of a function argument or a result column
69258 ** into a numeric representation.  Use either INTEGER or REAL whichever
69259 ** is appropriate.  But only do the conversion if it is possible without
69260 ** loss of information and return the revised type of the argument.
69261 */
69262 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
69263   int eType = sqlite3_value_type(pVal);
69264   if( eType==SQLITE_TEXT ){
69265     Mem *pMem = (Mem*)pVal;
69266     applyNumericAffinity(pMem, 0);
69267     eType = sqlite3_value_type(pVal);
69268   }
69269   return eType;
69270 }
69271 
69272 /*
69273 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
69274 ** not the internal Mem* type.
69275 */
69276 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
69277   sqlite3_value *pVal,
69278   u8 affinity,
69279   u8 enc
69280 ){
69281   applyAffinity((Mem *)pVal, affinity, enc);
69282 }
69283 
69284 /*
69285 ** pMem currently only holds a string type (or maybe a BLOB that we can
69286 ** interpret as a string if we want to).  Compute its corresponding
69287 ** numeric type, if has one.  Set the pMem->u.r and pMem->u.i fields
69288 ** accordingly.
69289 */
69290 static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
69291   assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
69292   assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
69293   if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
69294     return 0;
69295   }
69296   if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
69297     return MEM_Int;
69298   }
69299   return MEM_Real;
69300 }
69301 
69302 /*
69303 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
69304 ** none.
69305 **
69306 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
69307 ** But it does set pMem->u.r and pMem->u.i appropriately.
69308 */
69309 static u16 numericType(Mem *pMem){
69310   if( pMem->flags & (MEM_Int|MEM_Real) ){
69311     return pMem->flags & (MEM_Int|MEM_Real);
69312   }
69313   if( pMem->flags & (MEM_Str|MEM_Blob) ){
69314     return computeNumericType(pMem);
69315   }
69316   return 0;
69317 }
69318 
69319 #ifdef SQLITE_DEBUG
69320 /*
69321 ** Write a nice string representation of the contents of cell pMem
69322 ** into buffer zBuf, length nBuf.
69323 */
69324 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
69325   char *zCsr = zBuf;
69326   int f = pMem->flags;
69327 
69328   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
69329 
69330   if( f&MEM_Blob ){
69331     int i;
69332     char c;
69333     if( f & MEM_Dyn ){
69334       c = 'z';
69335       assert( (f & (MEM_Static|MEM_Ephem))==0 );
69336     }else if( f & MEM_Static ){
69337       c = 't';
69338       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
69339     }else if( f & MEM_Ephem ){
69340       c = 'e';
69341       assert( (f & (MEM_Static|MEM_Dyn))==0 );
69342     }else{
69343       c = 's';
69344     }
69345 
69346     sqlite3_snprintf(100, zCsr, "%c", c);
69347     zCsr += sqlite3Strlen30(zCsr);
69348     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
69349     zCsr += sqlite3Strlen30(zCsr);
69350     for(i=0; i<16 && i<pMem->n; i++){
69351       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
69352       zCsr += sqlite3Strlen30(zCsr);
69353     }
69354     for(i=0; i<16 && i<pMem->n; i++){
69355       char z = pMem->z[i];
69356       if( z<32 || z>126 ) *zCsr++ = '.';
69357       else *zCsr++ = z;
69358     }
69359 
69360     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
69361     zCsr += sqlite3Strlen30(zCsr);
69362     if( f & MEM_Zero ){
69363       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
69364       zCsr += sqlite3Strlen30(zCsr);
69365     }
69366     *zCsr = '\0';
69367   }else if( f & MEM_Str ){
69368     int j, k;
69369     zBuf[0] = ' ';
69370     if( f & MEM_Dyn ){
69371       zBuf[1] = 'z';
69372       assert( (f & (MEM_Static|MEM_Ephem))==0 );
69373     }else if( f & MEM_Static ){
69374       zBuf[1] = 't';
69375       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
69376     }else if( f & MEM_Ephem ){
69377       zBuf[1] = 'e';
69378       assert( (f & (MEM_Static|MEM_Dyn))==0 );
69379     }else{
69380       zBuf[1] = 's';
69381     }
69382     k = 2;
69383     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
69384     k += sqlite3Strlen30(&zBuf[k]);
69385     zBuf[k++] = '[';
69386     for(j=0; j<15 && j<pMem->n; j++){
69387       u8 c = pMem->z[j];
69388       if( c>=0x20 && c<0x7f ){
69389         zBuf[k++] = c;
69390       }else{
69391         zBuf[k++] = '.';
69392       }
69393     }
69394     zBuf[k++] = ']';
69395     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
69396     k += sqlite3Strlen30(&zBuf[k]);
69397     zBuf[k++] = 0;
69398   }
69399 }
69400 #endif
69401 
69402 #ifdef SQLITE_DEBUG
69403 /*
69404 ** Print the value of a register for tracing purposes:
69405 */
69406 static void memTracePrint(Mem *p){
69407   if( p->flags & MEM_Undefined ){
69408     printf(" undefined");
69409   }else if( p->flags & MEM_Null ){
69410     printf(" NULL");
69411   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
69412     printf(" si:%lld", p->u.i);
69413   }else if( p->flags & MEM_Int ){
69414     printf(" i:%lld", p->u.i);
69415 #ifndef SQLITE_OMIT_FLOATING_POINT
69416   }else if( p->flags & MEM_Real ){
69417     printf(" r:%g", p->u.r);
69418 #endif
69419   }else if( p->flags & MEM_RowSet ){
69420     printf(" (rowset)");
69421   }else{
69422     char zBuf[200];
69423     sqlite3VdbeMemPrettyPrint(p, zBuf);
69424     printf(" %s", zBuf);
69425   }
69426 }
69427 static void registerTrace(int iReg, Mem *p){
69428   printf("REG[%d] = ", iReg);
69429   memTracePrint(p);
69430   printf("\n");
69431 }
69432 #endif
69433 
69434 #ifdef SQLITE_DEBUG
69435 #  define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
69436 #else
69437 #  define REGISTER_TRACE(R,M)
69438 #endif
69439 
69440 
69441 #ifdef VDBE_PROFILE
69442 
69443 /*
69444 ** hwtime.h contains inline assembler code for implementing
69445 ** high-performance timing routines.
69446 */
69447 /************** Include hwtime.h in the middle of vdbe.c *********************/
69448 /************** Begin file hwtime.h ******************************************/
69449 /*
69450 ** 2008 May 27
69451 **
69452 ** The author disclaims copyright to this source code.  In place of
69453 ** a legal notice, here is a blessing:
69454 **
69455 **    May you do good and not evil.
69456 **    May you find forgiveness for yourself and forgive others.
69457 **    May you share freely, never taking more than you give.
69458 **
69459 ******************************************************************************
69460 **
69461 ** This file contains inline asm code for retrieving "high-performance"
69462 ** counters for x86 class CPUs.
69463 */
69464 #ifndef _HWTIME_H_
69465 #define _HWTIME_H_
69466 
69467 /*
69468 ** The following routine only works on pentium-class (or newer) processors.
69469 ** It uses the RDTSC opcode to read the cycle count value out of the
69470 ** processor and returns that value.  This can be used for high-res
69471 ** profiling.
69472 */
69473 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
69474       (defined(i386) || defined(__i386__) || defined(_M_IX86))
69475 
69476   #if defined(__GNUC__)
69477 
69478   __inline__ sqlite_uint64 sqlite3Hwtime(void){
69479      unsigned int lo, hi;
69480      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
69481      return (sqlite_uint64)hi << 32 | lo;
69482   }
69483 
69484   #elif defined(_MSC_VER)
69485 
69486   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
69487      __asm {
69488         rdtsc
69489         ret       ; return value at EDX:EAX
69490      }
69491   }
69492 
69493   #endif
69494 
69495 #elif (defined(__GNUC__) && defined(__x86_64__))
69496 
69497   __inline__ sqlite_uint64 sqlite3Hwtime(void){
69498       unsigned long val;
69499       __asm__ __volatile__ ("rdtsc" : "=A" (val));
69500       return val;
69501   }
69502 
69503 #elif (defined(__GNUC__) && defined(__ppc__))
69504 
69505   __inline__ sqlite_uint64 sqlite3Hwtime(void){
69506       unsigned long long retval;
69507       unsigned long junk;
69508       __asm__ __volatile__ ("\n\
69509           1:      mftbu   %1\n\
69510                   mftb    %L0\n\
69511                   mftbu   %0\n\
69512                   cmpw    %0,%1\n\
69513                   bne     1b"
69514                   : "=r" (retval), "=r" (junk));
69515       return retval;
69516   }
69517 
69518 #else
69519 
69520   #error Need implementation of sqlite3Hwtime() for your platform.
69521 
69522   /*
69523   ** To compile without implementing sqlite3Hwtime() for your platform,
69524   ** you can remove the above #error and use the following
69525   ** stub function.  You will lose timing support for many
69526   ** of the debugging and testing utilities, but it should at
69527   ** least compile and run.
69528   */
69529 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
69530 
69531 #endif
69532 
69533 #endif /* !defined(_HWTIME_H_) */
69534 
69535 /************** End of hwtime.h **********************************************/
69536 /************** Continuing where we left off in vdbe.c ***********************/
69537 
69538 #endif
69539 
69540 #ifndef NDEBUG
69541 /*
69542 ** This function is only called from within an assert() expression. It
69543 ** checks that the sqlite3.nTransaction variable is correctly set to
69544 ** the number of non-transaction savepoints currently in the
69545 ** linked list starting at sqlite3.pSavepoint.
69546 **
69547 ** Usage:
69548 **
69549 **     assert( checkSavepointCount(db) );
69550 */
69551 static int checkSavepointCount(sqlite3 *db){
69552   int n = 0;
69553   Savepoint *p;
69554   for(p=db->pSavepoint; p; p=p->pNext) n++;
69555   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
69556   return 1;
69557 }
69558 #endif
69559 
69560 
69561 /*
69562 ** Execute as much of a VDBE program as we can.
69563 ** This is the core of sqlite3_step().
69564 */
69565 SQLITE_PRIVATE int sqlite3VdbeExec(
69566   Vdbe *p                    /* The VDBE */
69567 ){
69568   int pc=0;                  /* The program counter */
69569   Op *aOp = p->aOp;          /* Copy of p->aOp */
69570   Op *pOp;                   /* Current operation */
69571   int rc = SQLITE_OK;        /* Value to return */
69572   sqlite3 *db = p->db;       /* The database */
69573   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
69574   u8 encoding = ENC(db);     /* The database encoding */
69575   int iCompare = 0;          /* Result of last OP_Compare operation */
69576   unsigned nVmStep = 0;      /* Number of virtual machine steps */
69577 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
69578   unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
69579 #endif
69580   Mem *aMem = p->aMem;       /* Copy of p->aMem */
69581   Mem *pIn1 = 0;             /* 1st input operand */
69582   Mem *pIn2 = 0;             /* 2nd input operand */
69583   Mem *pIn3 = 0;             /* 3rd input operand */
69584   Mem *pOut = 0;             /* Output operand */
69585   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
69586   i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
69587 #ifdef VDBE_PROFILE
69588   u64 start;                 /* CPU clock count at start of opcode */
69589 #endif
69590   /*** INSERT STACK UNION HERE ***/
69591 
69592   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
69593   sqlite3VdbeEnter(p);
69594   if( p->rc==SQLITE_NOMEM ){
69595     /* This happens if a malloc() inside a call to sqlite3_column_text() or
69596     ** sqlite3_column_text16() failed.  */
69597     goto no_mem;
69598   }
69599   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
69600   assert( p->bIsReader || p->readOnly!=0 );
69601   p->rc = SQLITE_OK;
69602   p->iCurrentTime = 0;
69603   assert( p->explain==0 );
69604   p->pResultSet = 0;
69605   db->busyHandler.nBusy = 0;
69606   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
69607   sqlite3VdbeIOTraceSql(p);
69608 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
69609   if( db->xProgress ){
69610     assert( 0 < db->nProgressOps );
69611     nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
69612     if( nProgressLimit==0 ){
69613       nProgressLimit = db->nProgressOps;
69614     }else{
69615       nProgressLimit %= (unsigned)db->nProgressOps;
69616     }
69617   }
69618 #endif
69619 #ifdef SQLITE_DEBUG
69620   sqlite3BeginBenignMalloc();
69621   if( p->pc==0
69622    && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
69623   ){
69624     int i;
69625     int once = 1;
69626     sqlite3VdbePrintSql(p);
69627     if( p->db->flags & SQLITE_VdbeListing ){
69628       printf("VDBE Program Listing:\n");
69629       for(i=0; i<p->nOp; i++){
69630         sqlite3VdbePrintOp(stdout, i, &aOp[i]);
69631       }
69632     }
69633     if( p->db->flags & SQLITE_VdbeEQP ){
69634       for(i=0; i<p->nOp; i++){
69635         if( aOp[i].opcode==OP_Explain ){
69636           if( once ) printf("VDBE Query Plan:\n");
69637           printf("%s\n", aOp[i].p4.z);
69638           once = 0;
69639         }
69640       }
69641     }
69642     if( p->db->flags & SQLITE_VdbeTrace )  printf("VDBE Trace:\n");
69643   }
69644   sqlite3EndBenignMalloc();
69645 #endif
69646   for(pc=p->pc; rc==SQLITE_OK; pc++){
69647     assert( pc>=0 && pc<p->nOp );
69648     if( db->mallocFailed ) goto no_mem;
69649 #ifdef VDBE_PROFILE
69650     start = sqlite3Hwtime();
69651 #endif
69652     nVmStep++;
69653     pOp = &aOp[pc];
69654 
69655     /* Only allow tracing if SQLITE_DEBUG is defined.
69656     */
69657 #ifdef SQLITE_DEBUG
69658     if( db->flags & SQLITE_VdbeTrace ){
69659       sqlite3VdbePrintOp(stdout, pc, pOp);
69660     }
69661 #endif
69662 
69663 
69664     /* Check to see if we need to simulate an interrupt.  This only happens
69665     ** if we have a special test build.
69666     */
69667 #ifdef SQLITE_TEST
69668     if( sqlite3_interrupt_count>0 ){
69669       sqlite3_interrupt_count--;
69670       if( sqlite3_interrupt_count==0 ){
69671         sqlite3_interrupt(db);
69672       }
69673     }
69674 #endif
69675 
69676     /* On any opcode with the "out2-prerelease" tag, free any
69677     ** external allocations out of mem[p2] and set mem[p2] to be
69678     ** an undefined integer.  Opcodes will either fill in the integer
69679     ** value or convert mem[p2] to a different type.
69680     */
69681     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
69682     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
69683       assert( pOp->p2>0 );
69684       assert( pOp->p2<=(p->nMem-p->nCursor) );
69685       pOut = &aMem[pOp->p2];
69686       memAboutToChange(p, pOut);
69687       if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);
69688       pOut->flags = MEM_Int;
69689     }
69690 
69691     /* Sanity checking on other operands */
69692 #ifdef SQLITE_DEBUG
69693     if( (pOp->opflags & OPFLG_IN1)!=0 ){
69694       assert( pOp->p1>0 );
69695       assert( pOp->p1<=(p->nMem-p->nCursor) );
69696       assert( memIsValid(&aMem[pOp->p1]) );
69697       assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
69698       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
69699     }
69700     if( (pOp->opflags & OPFLG_IN2)!=0 ){
69701       assert( pOp->p2>0 );
69702       assert( pOp->p2<=(p->nMem-p->nCursor) );
69703       assert( memIsValid(&aMem[pOp->p2]) );
69704       assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
69705       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
69706     }
69707     if( (pOp->opflags & OPFLG_IN3)!=0 ){
69708       assert( pOp->p3>0 );
69709       assert( pOp->p3<=(p->nMem-p->nCursor) );
69710       assert( memIsValid(&aMem[pOp->p3]) );
69711       assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
69712       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
69713     }
69714     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
69715       assert( pOp->p2>0 );
69716       assert( pOp->p2<=(p->nMem-p->nCursor) );
69717       memAboutToChange(p, &aMem[pOp->p2]);
69718     }
69719     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
69720       assert( pOp->p3>0 );
69721       assert( pOp->p3<=(p->nMem-p->nCursor) );
69722       memAboutToChange(p, &aMem[pOp->p3]);
69723     }
69724 #endif
69725 
69726     switch( pOp->opcode ){
69727 
69728 /*****************************************************************************
69729 ** What follows is a massive switch statement where each case implements a
69730 ** separate instruction in the virtual machine.  If we follow the usual
69731 ** indentation conventions, each case should be indented by 6 spaces.  But
69732 ** that is a lot of wasted space on the left margin.  So the code within
69733 ** the switch statement will break with convention and be flush-left. Another
69734 ** big comment (similar to this one) will mark the point in the code where
69735 ** we transition back to normal indentation.
69736 **
69737 ** The formatting of each case is important.  The makefile for SQLite
69738 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
69739 ** file looking for lines that begin with "case OP_".  The opcodes.h files
69740 ** will be filled with #defines that give unique integer values to each
69741 ** opcode and the opcodes.c file is filled with an array of strings where
69742 ** each string is the symbolic name for the corresponding opcode.  If the
69743 ** case statement is followed by a comment of the form "/# same as ... #/"
69744 ** that comment is used to determine the particular value of the opcode.
69745 **
69746 ** Other keywords in the comment that follows each case are used to
69747 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
69748 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
69749 ** the mkopcodeh.awk script for additional information.
69750 **
69751 ** Documentation about VDBE opcodes is generated by scanning this file
69752 ** for lines of that contain "Opcode:".  That line and all subsequent
69753 ** comment lines are used in the generation of the opcode.html documentation
69754 ** file.
69755 **
69756 ** SUMMARY:
69757 **
69758 **     Formatting is important to scripts that scan this file.
69759 **     Do not deviate from the formatting style currently in use.
69760 **
69761 *****************************************************************************/
69762 
69763 /* Opcode:  Goto * P2 * * *
69764 **
69765 ** An unconditional jump to address P2.
69766 ** The next instruction executed will be
69767 ** the one at index P2 from the beginning of
69768 ** the program.
69769 **
69770 ** The P1 parameter is not actually used by this opcode.  However, it
69771 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
69772 ** that this Goto is the bottom of a loop and that the lines from P2 down
69773 ** to the current line should be indented for EXPLAIN output.
69774 */
69775 case OP_Goto: {             /* jump */
69776   pc = pOp->p2 - 1;
69777 
69778   /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
69779   ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
69780   ** completion.  Check to see if sqlite3_interrupt() has been called
69781   ** or if the progress callback needs to be invoked.
69782   **
69783   ** This code uses unstructured "goto" statements and does not look clean.
69784   ** But that is not due to sloppy coding habits. The code is written this
69785   ** way for performance, to avoid having to run the interrupt and progress
69786   ** checks on every opcode.  This helps sqlite3_step() to run about 1.5%
69787   ** faster according to "valgrind --tool=cachegrind" */
69788 check_for_interrupt:
69789   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
69790 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
69791   /* Call the progress callback if it is configured and the required number
69792   ** of VDBE ops have been executed (either since this invocation of
69793   ** sqlite3VdbeExec() or since last time the progress callback was called).
69794   ** If the progress callback returns non-zero, exit the virtual machine with
69795   ** a return code SQLITE_ABORT.
69796   */
69797   if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
69798     assert( db->nProgressOps!=0 );
69799     nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
69800     if( db->xProgress(db->pProgressArg) ){
69801       rc = SQLITE_INTERRUPT;
69802       goto vdbe_error_halt;
69803     }
69804   }
69805 #endif
69806 
69807   break;
69808 }
69809 
69810 /* Opcode:  Gosub P1 P2 * * *
69811 **
69812 ** Write the current address onto register P1
69813 ** and then jump to address P2.
69814 */
69815 case OP_Gosub: {            /* jump */
69816   assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
69817   pIn1 = &aMem[pOp->p1];
69818   assert( VdbeMemDynamic(pIn1)==0 );
69819   memAboutToChange(p, pIn1);
69820   pIn1->flags = MEM_Int;
69821   pIn1->u.i = pc;
69822   REGISTER_TRACE(pOp->p1, pIn1);
69823   pc = pOp->p2 - 1;
69824   break;
69825 }
69826 
69827 /* Opcode:  Return P1 * * * *
69828 **
69829 ** Jump to the next instruction after the address in register P1.  After
69830 ** the jump, register P1 becomes undefined.
69831 */
69832 case OP_Return: {           /* in1 */
69833   pIn1 = &aMem[pOp->p1];
69834   assert( pIn1->flags==MEM_Int );
69835   pc = (int)pIn1->u.i;
69836   pIn1->flags = MEM_Undefined;
69837   break;
69838 }
69839 
69840 /* Opcode: InitCoroutine P1 P2 P3 * *
69841 **
69842 ** Set up register P1 so that it will Yield to the coroutine
69843 ** located at address P3.
69844 **
69845 ** If P2!=0 then the coroutine implementation immediately follows
69846 ** this opcode.  So jump over the coroutine implementation to
69847 ** address P2.
69848 **
69849 ** See also: EndCoroutine
69850 */
69851 case OP_InitCoroutine: {     /* jump */
69852   assert( pOp->p1>0 &&  pOp->p1<=(p->nMem-p->nCursor) );
69853   assert( pOp->p2>=0 && pOp->p2<p->nOp );
69854   assert( pOp->p3>=0 && pOp->p3<p->nOp );
69855   pOut = &aMem[pOp->p1];
69856   assert( !VdbeMemDynamic(pOut) );
69857   pOut->u.i = pOp->p3 - 1;
69858   pOut->flags = MEM_Int;
69859   if( pOp->p2 ) pc = pOp->p2 - 1;
69860   break;
69861 }
69862 
69863 /* Opcode:  EndCoroutine P1 * * * *
69864 **
69865 ** The instruction at the address in register P1 is a Yield.
69866 ** Jump to the P2 parameter of that Yield.
69867 ** After the jump, register P1 becomes undefined.
69868 **
69869 ** See also: InitCoroutine
69870 */
69871 case OP_EndCoroutine: {           /* in1 */
69872   VdbeOp *pCaller;
69873   pIn1 = &aMem[pOp->p1];
69874   assert( pIn1->flags==MEM_Int );
69875   assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
69876   pCaller = &aOp[pIn1->u.i];
69877   assert( pCaller->opcode==OP_Yield );
69878   assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
69879   pc = pCaller->p2 - 1;
69880   pIn1->flags = MEM_Undefined;
69881   break;
69882 }
69883 
69884 /* Opcode:  Yield P1 P2 * * *
69885 **
69886 ** Swap the program counter with the value in register P1.  This
69887 ** has the effect of yielding to a coroutine.
69888 **
69889 ** If the coroutine that is launched by this instruction ends with
69890 ** Yield or Return then continue to the next instruction.  But if
69891 ** the coroutine launched by this instruction ends with
69892 ** EndCoroutine, then jump to P2 rather than continuing with the
69893 ** next instruction.
69894 **
69895 ** See also: InitCoroutine
69896 */
69897 case OP_Yield: {            /* in1, jump */
69898   int pcDest;
69899   pIn1 = &aMem[pOp->p1];
69900   assert( VdbeMemDynamic(pIn1)==0 );
69901   pIn1->flags = MEM_Int;
69902   pcDest = (int)pIn1->u.i;
69903   pIn1->u.i = pc;
69904   REGISTER_TRACE(pOp->p1, pIn1);
69905   pc = pcDest;
69906   break;
69907 }
69908 
69909 /* Opcode:  HaltIfNull  P1 P2 P3 P4 P5
69910 ** Synopsis:  if r[P3]=null halt
69911 **
69912 ** Check the value in register P3.  If it is NULL then Halt using
69913 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
69914 ** value in register P3 is not NULL, then this routine is a no-op.
69915 ** The P5 parameter should be 1.
69916 */
69917 case OP_HaltIfNull: {      /* in3 */
69918   pIn3 = &aMem[pOp->p3];
69919   if( (pIn3->flags & MEM_Null)==0 ) break;
69920   /* Fall through into OP_Halt */
69921 }
69922 
69923 /* Opcode:  Halt P1 P2 * P4 P5
69924 **
69925 ** Exit immediately.  All open cursors, etc are closed
69926 ** automatically.
69927 **
69928 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
69929 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
69930 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
69931 ** whether or not to rollback the current transaction.  Do not rollback
69932 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
69933 ** then back out all changes that have occurred during this execution of the
69934 ** VDBE, but do not rollback the transaction.
69935 **
69936 ** If P4 is not null then it is an error message string.
69937 **
69938 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
69939 **
69940 **    0:  (no change)
69941 **    1:  NOT NULL contraint failed: P4
69942 **    2:  UNIQUE constraint failed: P4
69943 **    3:  CHECK constraint failed: P4
69944 **    4:  FOREIGN KEY constraint failed: P4
69945 **
69946 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
69947 ** omitted.
69948 **
69949 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
69950 ** every program.  So a jump past the last instruction of the program
69951 ** is the same as executing Halt.
69952 */
69953 case OP_Halt: {
69954   const char *zType;
69955   const char *zLogFmt;
69956 
69957   if( pOp->p1==SQLITE_OK && p->pFrame ){
69958     /* Halt the sub-program. Return control to the parent frame. */
69959     VdbeFrame *pFrame = p->pFrame;
69960     p->pFrame = pFrame->pParent;
69961     p->nFrame--;
69962     sqlite3VdbeSetChanges(db, p->nChange);
69963     pc = sqlite3VdbeFrameRestore(pFrame);
69964     lastRowid = db->lastRowid;
69965     if( pOp->p2==OE_Ignore ){
69966       /* Instruction pc is the OP_Program that invoked the sub-program
69967       ** currently being halted. If the p2 instruction of this OP_Halt
69968       ** instruction is set to OE_Ignore, then the sub-program is throwing
69969       ** an IGNORE exception. In this case jump to the address specified
69970       ** as the p2 of the calling OP_Program.  */
69971       pc = p->aOp[pc].p2-1;
69972     }
69973     aOp = p->aOp;
69974     aMem = p->aMem;
69975     break;
69976   }
69977   p->rc = pOp->p1;
69978   p->errorAction = (u8)pOp->p2;
69979   p->pc = pc;
69980   if( p->rc ){
69981     if( pOp->p5 ){
69982       static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
69983                                              "FOREIGN KEY" };
69984       assert( pOp->p5>=1 && pOp->p5<=4 );
69985       testcase( pOp->p5==1 );
69986       testcase( pOp->p5==2 );
69987       testcase( pOp->p5==3 );
69988       testcase( pOp->p5==4 );
69989       zType = azType[pOp->p5-1];
69990     }else{
69991       zType = 0;
69992     }
69993     assert( zType!=0 || pOp->p4.z!=0 );
69994     zLogFmt = "abort at %d in [%s]: %s";
69995     if( zType && pOp->p4.z ){
69996       sqlite3SetString(&p->zErrMsg, db, "%s constraint failed: %s",
69997                        zType, pOp->p4.z);
69998     }else if( pOp->p4.z ){
69999       sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
70000     }else{
70001       sqlite3SetString(&p->zErrMsg, db, "%s constraint failed", zType);
70002     }
70003     sqlite3_log(pOp->p1, zLogFmt, pc, p->zSql, p->zErrMsg);
70004   }
70005   rc = sqlite3VdbeHalt(p);
70006   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
70007   if( rc==SQLITE_BUSY ){
70008     p->rc = rc = SQLITE_BUSY;
70009   }else{
70010     assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
70011     assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
70012     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
70013   }
70014   goto vdbe_return;
70015 }
70016 
70017 /* Opcode: Integer P1 P2 * * *
70018 ** Synopsis: r[P2]=P1
70019 **
70020 ** The 32-bit integer value P1 is written into register P2.
70021 */
70022 case OP_Integer: {         /* out2-prerelease */
70023   pOut->u.i = pOp->p1;
70024   break;
70025 }
70026 
70027 /* Opcode: Int64 * P2 * P4 *
70028 ** Synopsis: r[P2]=P4
70029 **
70030 ** P4 is a pointer to a 64-bit integer value.
70031 ** Write that value into register P2.
70032 */
70033 case OP_Int64: {           /* out2-prerelease */
70034   assert( pOp->p4.pI64!=0 );
70035   pOut->u.i = *pOp->p4.pI64;
70036   break;
70037 }
70038 
70039 #ifndef SQLITE_OMIT_FLOATING_POINT
70040 /* Opcode: Real * P2 * P4 *
70041 ** Synopsis: r[P2]=P4
70042 **
70043 ** P4 is a pointer to a 64-bit floating point value.
70044 ** Write that value into register P2.
70045 */
70046 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
70047   pOut->flags = MEM_Real;
70048   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
70049   pOut->u.r = *pOp->p4.pReal;
70050   break;
70051 }
70052 #endif
70053 
70054 /* Opcode: String8 * P2 * P4 *
70055 ** Synopsis: r[P2]='P4'
70056 **
70057 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
70058 ** into a String before it is executed for the first time.  During
70059 ** this transformation, the length of string P4 is computed and stored
70060 ** as the P1 parameter.
70061 */
70062 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
70063   assert( pOp->p4.z!=0 );
70064   pOp->opcode = OP_String;
70065   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
70066 
70067 #ifndef SQLITE_OMIT_UTF16
70068   if( encoding!=SQLITE_UTF8 ){
70069     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
70070     if( rc==SQLITE_TOOBIG ) goto too_big;
70071     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
70072     assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
70073     assert( VdbeMemDynamic(pOut)==0 );
70074     pOut->szMalloc = 0;
70075     pOut->flags |= MEM_Static;
70076     if( pOp->p4type==P4_DYNAMIC ){
70077       sqlite3DbFree(db, pOp->p4.z);
70078     }
70079     pOp->p4type = P4_DYNAMIC;
70080     pOp->p4.z = pOut->z;
70081     pOp->p1 = pOut->n;
70082   }
70083 #endif
70084   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
70085     goto too_big;
70086   }
70087   /* Fall through to the next case, OP_String */
70088 }
70089 
70090 /* Opcode: String P1 P2 * P4 *
70091 ** Synopsis: r[P2]='P4' (len=P1)
70092 **
70093 ** The string value P4 of length P1 (bytes) is stored in register P2.
70094 */
70095 case OP_String: {          /* out2-prerelease */
70096   assert( pOp->p4.z!=0 );
70097   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
70098   pOut->z = pOp->p4.z;
70099   pOut->n = pOp->p1;
70100   pOut->enc = encoding;
70101   UPDATE_MAX_BLOBSIZE(pOut);
70102   break;
70103 }
70104 
70105 /* Opcode: Null P1 P2 P3 * *
70106 ** Synopsis:  r[P2..P3]=NULL
70107 **
70108 ** Write a NULL into registers P2.  If P3 greater than P2, then also write
70109 ** NULL into register P3 and every register in between P2 and P3.  If P3
70110 ** is less than P2 (typically P3 is zero) then only register P2 is
70111 ** set to NULL.
70112 **
70113 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
70114 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
70115 ** OP_Ne or OP_Eq.
70116 */
70117 case OP_Null: {           /* out2-prerelease */
70118   int cnt;
70119   u16 nullFlag;
70120   cnt = pOp->p3-pOp->p2;
70121   assert( pOp->p3<=(p->nMem-p->nCursor) );
70122   pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
70123   while( cnt>0 ){
70124     pOut++;
70125     memAboutToChange(p, pOut);
70126     sqlite3VdbeMemSetNull(pOut);
70127     pOut->flags = nullFlag;
70128     cnt--;
70129   }
70130   break;
70131 }
70132 
70133 /* Opcode: SoftNull P1 * * * *
70134 ** Synopsis:  r[P1]=NULL
70135 **
70136 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
70137 ** instruction, but do not free any string or blob memory associated with
70138 ** the register, so that if the value was a string or blob that was
70139 ** previously copied using OP_SCopy, the copies will continue to be valid.
70140 */
70141 case OP_SoftNull: {
70142   assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
70143   pOut = &aMem[pOp->p1];
70144   pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
70145   break;
70146 }
70147 
70148 /* Opcode: Blob P1 P2 * P4 *
70149 ** Synopsis: r[P2]=P4 (len=P1)
70150 **
70151 ** P4 points to a blob of data P1 bytes long.  Store this
70152 ** blob in register P2.
70153 */
70154 case OP_Blob: {                /* out2-prerelease */
70155   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
70156   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
70157   pOut->enc = encoding;
70158   UPDATE_MAX_BLOBSIZE(pOut);
70159   break;
70160 }
70161 
70162 /* Opcode: Variable P1 P2 * P4 *
70163 ** Synopsis: r[P2]=parameter(P1,P4)
70164 **
70165 ** Transfer the values of bound parameter P1 into register P2
70166 **
70167 ** If the parameter is named, then its name appears in P4.
70168 ** The P4 value is used by sqlite3_bind_parameter_name().
70169 */
70170 case OP_Variable: {            /* out2-prerelease */
70171   Mem *pVar;       /* Value being transferred */
70172 
70173   assert( pOp->p1>0 && pOp->p1<=p->nVar );
70174   assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
70175   pVar = &p->aVar[pOp->p1 - 1];
70176   if( sqlite3VdbeMemTooBig(pVar) ){
70177     goto too_big;
70178   }
70179   sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
70180   UPDATE_MAX_BLOBSIZE(pOut);
70181   break;
70182 }
70183 
70184 /* Opcode: Move P1 P2 P3 * *
70185 ** Synopsis:  r[P2@P3]=r[P1@P3]
70186 **
70187 ** Move the P3 values in register P1..P1+P3-1 over into
70188 ** registers P2..P2+P3-1.  Registers P1..P1+P3-1 are
70189 ** left holding a NULL.  It is an error for register ranges
70190 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.  It is an error
70191 ** for P3 to be less than 1.
70192 */
70193 case OP_Move: {
70194   int n;           /* Number of registers left to copy */
70195   int p1;          /* Register to copy from */
70196   int p2;          /* Register to copy to */
70197 
70198   n = pOp->p3;
70199   p1 = pOp->p1;
70200   p2 = pOp->p2;
70201   assert( n>0 && p1>0 && p2>0 );
70202   assert( p1+n<=p2 || p2+n<=p1 );
70203 
70204   pIn1 = &aMem[p1];
70205   pOut = &aMem[p2];
70206   do{
70207     assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
70208     assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
70209     assert( memIsValid(pIn1) );
70210     memAboutToChange(p, pOut);
70211     sqlite3VdbeMemMove(pOut, pIn1);
70212 #ifdef SQLITE_DEBUG
70213     if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<&aMem[p1+pOp->p3] ){
70214       pOut->pScopyFrom += p1 - pOp->p2;
70215     }
70216 #endif
70217     REGISTER_TRACE(p2++, pOut);
70218     pIn1++;
70219     pOut++;
70220   }while( --n );
70221   break;
70222 }
70223 
70224 /* Opcode: Copy P1 P2 P3 * *
70225 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
70226 **
70227 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
70228 **
70229 ** This instruction makes a deep copy of the value.  A duplicate
70230 ** is made of any string or blob constant.  See also OP_SCopy.
70231 */
70232 case OP_Copy: {
70233   int n;
70234 
70235   n = pOp->p3;
70236   pIn1 = &aMem[pOp->p1];
70237   pOut = &aMem[pOp->p2];
70238   assert( pOut!=pIn1 );
70239   while( 1 ){
70240     sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
70241     Deephemeralize(pOut);
70242 #ifdef SQLITE_DEBUG
70243     pOut->pScopyFrom = 0;
70244 #endif
70245     REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
70246     if( (n--)==0 ) break;
70247     pOut++;
70248     pIn1++;
70249   }
70250   break;
70251 }
70252 
70253 /* Opcode: SCopy P1 P2 * * *
70254 ** Synopsis: r[P2]=r[P1]
70255 **
70256 ** Make a shallow copy of register P1 into register P2.
70257 **
70258 ** This instruction makes a shallow copy of the value.  If the value
70259 ** is a string or blob, then the copy is only a pointer to the
70260 ** original and hence if the original changes so will the copy.
70261 ** Worse, if the original is deallocated, the copy becomes invalid.
70262 ** Thus the program must guarantee that the original will not change
70263 ** during the lifetime of the copy.  Use OP_Copy to make a complete
70264 ** copy.
70265 */
70266 case OP_SCopy: {            /* out2 */
70267   pIn1 = &aMem[pOp->p1];
70268   pOut = &aMem[pOp->p2];
70269   assert( pOut!=pIn1 );
70270   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
70271 #ifdef SQLITE_DEBUG
70272   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
70273 #endif
70274   break;
70275 }
70276 
70277 /* Opcode: ResultRow P1 P2 * * *
70278 ** Synopsis:  output=r[P1@P2]
70279 **
70280 ** The registers P1 through P1+P2-1 contain a single row of
70281 ** results. This opcode causes the sqlite3_step() call to terminate
70282 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
70283 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
70284 ** the result row.
70285 */
70286 case OP_ResultRow: {
70287   Mem *pMem;
70288   int i;
70289   assert( p->nResColumn==pOp->p2 );
70290   assert( pOp->p1>0 );
70291   assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
70292 
70293 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
70294   /* Run the progress counter just before returning.
70295   */
70296   if( db->xProgress!=0
70297    && nVmStep>=nProgressLimit
70298    && db->xProgress(db->pProgressArg)!=0
70299   ){
70300     rc = SQLITE_INTERRUPT;
70301     goto vdbe_error_halt;
70302   }
70303 #endif
70304 
70305   /* If this statement has violated immediate foreign key constraints, do
70306   ** not return the number of rows modified. And do not RELEASE the statement
70307   ** transaction. It needs to be rolled back.  */
70308   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
70309     assert( db->flags&SQLITE_CountRows );
70310     assert( p->usesStmtJournal );
70311     break;
70312   }
70313 
70314   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
70315   ** DML statements invoke this opcode to return the number of rows
70316   ** modified to the user. This is the only way that a VM that
70317   ** opens a statement transaction may invoke this opcode.
70318   **
70319   ** In case this is such a statement, close any statement transaction
70320   ** opened by this VM before returning control to the user. This is to
70321   ** ensure that statement-transactions are always nested, not overlapping.
70322   ** If the open statement-transaction is not closed here, then the user
70323   ** may step another VM that opens its own statement transaction. This
70324   ** may lead to overlapping statement transactions.
70325   **
70326   ** The statement transaction is never a top-level transaction.  Hence
70327   ** the RELEASE call below can never fail.
70328   */
70329   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
70330   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
70331   if( NEVER(rc!=SQLITE_OK) ){
70332     break;
70333   }
70334 
70335   /* Invalidate all ephemeral cursor row caches */
70336   p->cacheCtr = (p->cacheCtr + 2)|1;
70337 
70338   /* Make sure the results of the current row are \000 terminated
70339   ** and have an assigned type.  The results are de-ephemeralized as
70340   ** a side effect.
70341   */
70342   pMem = p->pResultSet = &aMem[pOp->p1];
70343   for(i=0; i<pOp->p2; i++){
70344     assert( memIsValid(&pMem[i]) );
70345     Deephemeralize(&pMem[i]);
70346     assert( (pMem[i].flags & MEM_Ephem)==0
70347             || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
70348     sqlite3VdbeMemNulTerminate(&pMem[i]);
70349     REGISTER_TRACE(pOp->p1+i, &pMem[i]);
70350   }
70351   if( db->mallocFailed ) goto no_mem;
70352 
70353   /* Return SQLITE_ROW
70354   */
70355   p->pc = pc + 1;
70356   rc = SQLITE_ROW;
70357   goto vdbe_return;
70358 }
70359 
70360 /* Opcode: Concat P1 P2 P3 * *
70361 ** Synopsis: r[P3]=r[P2]+r[P1]
70362 **
70363 ** Add the text in register P1 onto the end of the text in
70364 ** register P2 and store the result in register P3.
70365 ** If either the P1 or P2 text are NULL then store NULL in P3.
70366 **
70367 **   P3 = P2 || P1
70368 **
70369 ** It is illegal for P1 and P3 to be the same register. Sometimes,
70370 ** if P3 is the same register as P2, the implementation is able
70371 ** to avoid a memcpy().
70372 */
70373 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
70374   i64 nByte;
70375 
70376   pIn1 = &aMem[pOp->p1];
70377   pIn2 = &aMem[pOp->p2];
70378   pOut = &aMem[pOp->p3];
70379   assert( pIn1!=pOut );
70380   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
70381     sqlite3VdbeMemSetNull(pOut);
70382     break;
70383   }
70384   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
70385   Stringify(pIn1, encoding);
70386   Stringify(pIn2, encoding);
70387   nByte = pIn1->n + pIn2->n;
70388   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
70389     goto too_big;
70390   }
70391   if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
70392     goto no_mem;
70393   }
70394   MemSetTypeFlag(pOut, MEM_Str);
70395   if( pOut!=pIn2 ){
70396     memcpy(pOut->z, pIn2->z, pIn2->n);
70397   }
70398   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
70399   pOut->z[nByte]=0;
70400   pOut->z[nByte+1] = 0;
70401   pOut->flags |= MEM_Term;
70402   pOut->n = (int)nByte;
70403   pOut->enc = encoding;
70404   UPDATE_MAX_BLOBSIZE(pOut);
70405   break;
70406 }
70407 
70408 /* Opcode: Add P1 P2 P3 * *
70409 ** Synopsis:  r[P3]=r[P1]+r[P2]
70410 **
70411 ** Add the value in register P1 to the value in register P2
70412 ** and store the result in register P3.
70413 ** If either input is NULL, the result is NULL.
70414 */
70415 /* Opcode: Multiply P1 P2 P3 * *
70416 ** Synopsis:  r[P3]=r[P1]*r[P2]
70417 **
70418 **
70419 ** Multiply the value in register P1 by the value in register P2
70420 ** and store the result in register P3.
70421 ** If either input is NULL, the result is NULL.
70422 */
70423 /* Opcode: Subtract P1 P2 P3 * *
70424 ** Synopsis:  r[P3]=r[P2]-r[P1]
70425 **
70426 ** Subtract the value in register P1 from the value in register P2
70427 ** and store the result in register P3.
70428 ** If either input is NULL, the result is NULL.
70429 */
70430 /* Opcode: Divide P1 P2 P3 * *
70431 ** Synopsis:  r[P3]=r[P2]/r[P1]
70432 **
70433 ** Divide the value in register P1 by the value in register P2
70434 ** and store the result in register P3 (P3=P2/P1). If the value in
70435 ** register P1 is zero, then the result is NULL. If either input is
70436 ** NULL, the result is NULL.
70437 */
70438 /* Opcode: Remainder P1 P2 P3 * *
70439 ** Synopsis:  r[P3]=r[P2]%r[P1]
70440 **
70441 ** Compute the remainder after integer register P2 is divided by
70442 ** register P1 and store the result in register P3.
70443 ** If the value in register P1 is zero the result is NULL.
70444 ** If either operand is NULL, the result is NULL.
70445 */
70446 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
70447 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
70448 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
70449 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
70450 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
70451   char bIntint;   /* Started out as two integer operands */
70452   u16 flags;      /* Combined MEM_* flags from both inputs */
70453   u16 type1;      /* Numeric type of left operand */
70454   u16 type2;      /* Numeric type of right operand */
70455   i64 iA;         /* Integer value of left operand */
70456   i64 iB;         /* Integer value of right operand */
70457   double rA;      /* Real value of left operand */
70458   double rB;      /* Real value of right operand */
70459 
70460   pIn1 = &aMem[pOp->p1];
70461   type1 = numericType(pIn1);
70462   pIn2 = &aMem[pOp->p2];
70463   type2 = numericType(pIn2);
70464   pOut = &aMem[pOp->p3];
70465   flags = pIn1->flags | pIn2->flags;
70466   if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
70467   if( (type1 & type2 & MEM_Int)!=0 ){
70468     iA = pIn1->u.i;
70469     iB = pIn2->u.i;
70470     bIntint = 1;
70471     switch( pOp->opcode ){
70472       case OP_Add:       if( sqlite3AddInt64(&iB,iA) ) goto fp_math;  break;
70473       case OP_Subtract:  if( sqlite3SubInt64(&iB,iA) ) goto fp_math;  break;
70474       case OP_Multiply:  if( sqlite3MulInt64(&iB,iA) ) goto fp_math;  break;
70475       case OP_Divide: {
70476         if( iA==0 ) goto arithmetic_result_is_null;
70477         if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
70478         iB /= iA;
70479         break;
70480       }
70481       default: {
70482         if( iA==0 ) goto arithmetic_result_is_null;
70483         if( iA==-1 ) iA = 1;
70484         iB %= iA;
70485         break;
70486       }
70487     }
70488     pOut->u.i = iB;
70489     MemSetTypeFlag(pOut, MEM_Int);
70490   }else{
70491     bIntint = 0;
70492 fp_math:
70493     rA = sqlite3VdbeRealValue(pIn1);
70494     rB = sqlite3VdbeRealValue(pIn2);
70495     switch( pOp->opcode ){
70496       case OP_Add:         rB += rA;       break;
70497       case OP_Subtract:    rB -= rA;       break;
70498       case OP_Multiply:    rB *= rA;       break;
70499       case OP_Divide: {
70500         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
70501         if( rA==(double)0 ) goto arithmetic_result_is_null;
70502         rB /= rA;
70503         break;
70504       }
70505       default: {
70506         iA = (i64)rA;
70507         iB = (i64)rB;
70508         if( iA==0 ) goto arithmetic_result_is_null;
70509         if( iA==-1 ) iA = 1;
70510         rB = (double)(iB % iA);
70511         break;
70512       }
70513     }
70514 #ifdef SQLITE_OMIT_FLOATING_POINT
70515     pOut->u.i = rB;
70516     MemSetTypeFlag(pOut, MEM_Int);
70517 #else
70518     if( sqlite3IsNaN(rB) ){
70519       goto arithmetic_result_is_null;
70520     }
70521     pOut->u.r = rB;
70522     MemSetTypeFlag(pOut, MEM_Real);
70523     if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
70524       sqlite3VdbeIntegerAffinity(pOut);
70525     }
70526 #endif
70527   }
70528   break;
70529 
70530 arithmetic_result_is_null:
70531   sqlite3VdbeMemSetNull(pOut);
70532   break;
70533 }
70534 
70535 /* Opcode: CollSeq P1 * * P4
70536 **
70537 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
70538 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
70539 ** be returned. This is used by the built-in min(), max() and nullif()
70540 ** functions.
70541 **
70542 ** If P1 is not zero, then it is a register that a subsequent min() or
70543 ** max() aggregate will set to 1 if the current row is not the minimum or
70544 ** maximum.  The P1 register is initialized to 0 by this instruction.
70545 **
70546 ** The interface used by the implementation of the aforementioned functions
70547 ** to retrieve the collation sequence set by this opcode is not available
70548 ** publicly, only to user functions defined in func.c.
70549 */
70550 case OP_CollSeq: {
70551   assert( pOp->p4type==P4_COLLSEQ );
70552   if( pOp->p1 ){
70553     sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
70554   }
70555   break;
70556 }
70557 
70558 /* Opcode: Function P1 P2 P3 P4 P5
70559 ** Synopsis: r[P3]=func(r[P2@P5])
70560 **
70561 ** Invoke a user function (P4 is a pointer to a Function structure that
70562 ** defines the function) with P5 arguments taken from register P2 and
70563 ** successors.  The result of the function is stored in register P3.
70564 ** Register P3 must not be one of the function inputs.
70565 **
70566 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
70567 ** function was determined to be constant at compile time. If the first
70568 ** argument was constant then bit 0 of P1 is set. This is used to determine
70569 ** whether meta data associated with a user function argument using the
70570 ** sqlite3_set_auxdata() API may be safely retained until the next
70571 ** invocation of this opcode.
70572 **
70573 ** See also: AggStep and AggFinal
70574 */
70575 case OP_Function: {
70576   int i;
70577   Mem *pArg;
70578   sqlite3_context ctx;
70579   sqlite3_value **apVal;
70580   int n;
70581 
70582   n = pOp->p5;
70583   apVal = p->apArg;
70584   assert( apVal || n==0 );
70585   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
70586   ctx.pOut = &aMem[pOp->p3];
70587   memAboutToChange(p, ctx.pOut);
70588 
70589   assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
70590   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
70591   pArg = &aMem[pOp->p2];
70592   for(i=0; i<n; i++, pArg++){
70593     assert( memIsValid(pArg) );
70594     apVal[i] = pArg;
70595     Deephemeralize(pArg);
70596     REGISTER_TRACE(pOp->p2+i, pArg);
70597   }
70598 
70599   assert( pOp->p4type==P4_FUNCDEF );
70600   ctx.pFunc = pOp->p4.pFunc;
70601   ctx.iOp = pc;
70602   ctx.pVdbe = p;
70603   MemSetTypeFlag(ctx.pOut, MEM_Null);
70604   ctx.fErrorOrAux = 0;
70605   db->lastRowid = lastRowid;
70606   (*ctx.pFunc->xFunc)(&ctx, n, apVal); /* IMP: R-24505-23230 */
70607   lastRowid = db->lastRowid;  /* Remember rowid changes made by xFunc */
70608 
70609   /* If the function returned an error, throw an exception */
70610   if( ctx.fErrorOrAux ){
70611     if( ctx.isError ){
70612       sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(ctx.pOut));
70613       rc = ctx.isError;
70614     }
70615     sqlite3VdbeDeleteAuxData(p, pc, pOp->p1);
70616   }
70617 
70618   /* Copy the result of the function into register P3 */
70619   sqlite3VdbeChangeEncoding(ctx.pOut, encoding);
70620   if( sqlite3VdbeMemTooBig(ctx.pOut) ){
70621     goto too_big;
70622   }
70623 
70624   REGISTER_TRACE(pOp->p3, ctx.pOut);
70625   UPDATE_MAX_BLOBSIZE(ctx.pOut);
70626   break;
70627 }
70628 
70629 /* Opcode: BitAnd P1 P2 P3 * *
70630 ** Synopsis:  r[P3]=r[P1]&r[P2]
70631 **
70632 ** Take the bit-wise AND of the values in register P1 and P2 and
70633 ** store the result in register P3.
70634 ** If either input is NULL, the result is NULL.
70635 */
70636 /* Opcode: BitOr P1 P2 P3 * *
70637 ** Synopsis:  r[P3]=r[P1]|r[P2]
70638 **
70639 ** Take the bit-wise OR of the values in register P1 and P2 and
70640 ** store the result in register P3.
70641 ** If either input is NULL, the result is NULL.
70642 */
70643 /* Opcode: ShiftLeft P1 P2 P3 * *
70644 ** Synopsis:  r[P3]=r[P2]<<r[P1]
70645 **
70646 ** Shift the integer value in register P2 to the left by the
70647 ** number of bits specified by the integer in register P1.
70648 ** Store the result in register P3.
70649 ** If either input is NULL, the result is NULL.
70650 */
70651 /* Opcode: ShiftRight P1 P2 P3 * *
70652 ** Synopsis:  r[P3]=r[P2]>>r[P1]
70653 **
70654 ** Shift the integer value in register P2 to the right by the
70655 ** number of bits specified by the integer in register P1.
70656 ** Store the result in register P3.
70657 ** If either input is NULL, the result is NULL.
70658 */
70659 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
70660 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
70661 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
70662 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
70663   i64 iA;
70664   u64 uA;
70665   i64 iB;
70666   u8 op;
70667 
70668   pIn1 = &aMem[pOp->p1];
70669   pIn2 = &aMem[pOp->p2];
70670   pOut = &aMem[pOp->p3];
70671   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
70672     sqlite3VdbeMemSetNull(pOut);
70673     break;
70674   }
70675   iA = sqlite3VdbeIntValue(pIn2);
70676   iB = sqlite3VdbeIntValue(pIn1);
70677   op = pOp->opcode;
70678   if( op==OP_BitAnd ){
70679     iA &= iB;
70680   }else if( op==OP_BitOr ){
70681     iA |= iB;
70682   }else if( iB!=0 ){
70683     assert( op==OP_ShiftRight || op==OP_ShiftLeft );
70684 
70685     /* If shifting by a negative amount, shift in the other direction */
70686     if( iB<0 ){
70687       assert( OP_ShiftRight==OP_ShiftLeft+1 );
70688       op = 2*OP_ShiftLeft + 1 - op;
70689       iB = iB>(-64) ? -iB : 64;
70690     }
70691 
70692     if( iB>=64 ){
70693       iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
70694     }else{
70695       memcpy(&uA, &iA, sizeof(uA));
70696       if( op==OP_ShiftLeft ){
70697         uA <<= iB;
70698       }else{
70699         uA >>= iB;
70700         /* Sign-extend on a right shift of a negative number */
70701         if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
70702       }
70703       memcpy(&iA, &uA, sizeof(iA));
70704     }
70705   }
70706   pOut->u.i = iA;
70707   MemSetTypeFlag(pOut, MEM_Int);
70708   break;
70709 }
70710 
70711 /* Opcode: AddImm  P1 P2 * * *
70712 ** Synopsis:  r[P1]=r[P1]+P2
70713 **
70714 ** Add the constant P2 to the value in register P1.
70715 ** The result is always an integer.
70716 **
70717 ** To force any register to be an integer, just add 0.
70718 */
70719 case OP_AddImm: {            /* in1 */
70720   pIn1 = &aMem[pOp->p1];
70721   memAboutToChange(p, pIn1);
70722   sqlite3VdbeMemIntegerify(pIn1);
70723   pIn1->u.i += pOp->p2;
70724   break;
70725 }
70726 
70727 /* Opcode: MustBeInt P1 P2 * * *
70728 **
70729 ** Force the value in register P1 to be an integer.  If the value
70730 ** in P1 is not an integer and cannot be converted into an integer
70731 ** without data loss, then jump immediately to P2, or if P2==0
70732 ** raise an SQLITE_MISMATCH exception.
70733 */
70734 case OP_MustBeInt: {            /* jump, in1 */
70735   pIn1 = &aMem[pOp->p1];
70736   if( (pIn1->flags & MEM_Int)==0 ){
70737     applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
70738     VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
70739     if( (pIn1->flags & MEM_Int)==0 ){
70740       if( pOp->p2==0 ){
70741         rc = SQLITE_MISMATCH;
70742         goto abort_due_to_error;
70743       }else{
70744         pc = pOp->p2 - 1;
70745         break;
70746       }
70747     }
70748   }
70749   MemSetTypeFlag(pIn1, MEM_Int);
70750   break;
70751 }
70752 
70753 #ifndef SQLITE_OMIT_FLOATING_POINT
70754 /* Opcode: RealAffinity P1 * * * *
70755 **
70756 ** If register P1 holds an integer convert it to a real value.
70757 **
70758 ** This opcode is used when extracting information from a column that
70759 ** has REAL affinity.  Such column values may still be stored as
70760 ** integers, for space efficiency, but after extraction we want them
70761 ** to have only a real value.
70762 */
70763 case OP_RealAffinity: {                  /* in1 */
70764   pIn1 = &aMem[pOp->p1];
70765   if( pIn1->flags & MEM_Int ){
70766     sqlite3VdbeMemRealify(pIn1);
70767   }
70768   break;
70769 }
70770 #endif
70771 
70772 #ifndef SQLITE_OMIT_CAST
70773 /* Opcode: Cast P1 P2 * * *
70774 ** Synopsis: affinity(r[P1])
70775 **
70776 ** Force the value in register P1 to be the type defined by P2.
70777 **
70778 ** <ul>
70779 ** <li value="97"> TEXT
70780 ** <li value="98"> BLOB
70781 ** <li value="99"> NUMERIC
70782 ** <li value="100"> INTEGER
70783 ** <li value="101"> REAL
70784 ** </ul>
70785 **
70786 ** A NULL value is not changed by this routine.  It remains NULL.
70787 */
70788 case OP_Cast: {                  /* in1 */
70789   assert( pOp->p2>=SQLITE_AFF_NONE && pOp->p2<=SQLITE_AFF_REAL );
70790   testcase( pOp->p2==SQLITE_AFF_TEXT );
70791   testcase( pOp->p2==SQLITE_AFF_NONE );
70792   testcase( pOp->p2==SQLITE_AFF_NUMERIC );
70793   testcase( pOp->p2==SQLITE_AFF_INTEGER );
70794   testcase( pOp->p2==SQLITE_AFF_REAL );
70795   pIn1 = &aMem[pOp->p1];
70796   memAboutToChange(p, pIn1);
70797   rc = ExpandBlob(pIn1);
70798   sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
70799   UPDATE_MAX_BLOBSIZE(pIn1);
70800   break;
70801 }
70802 #endif /* SQLITE_OMIT_CAST */
70803 
70804 /* Opcode: Lt P1 P2 P3 P4 P5
70805 ** Synopsis: if r[P1]<r[P3] goto P2
70806 **
70807 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
70808 ** jump to address P2.
70809 **
70810 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
70811 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
70812 ** bit is clear then fall through if either operand is NULL.
70813 **
70814 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
70815 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
70816 ** to coerce both inputs according to this affinity before the
70817 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
70818 ** affinity is used. Note that the affinity conversions are stored
70819 ** back into the input registers P1 and P3.  So this opcode can cause
70820 ** persistent changes to registers P1 and P3.
70821 **
70822 ** Once any conversions have taken place, and neither value is NULL,
70823 ** the values are compared. If both values are blobs then memcmp() is
70824 ** used to determine the results of the comparison.  If both values
70825 ** are text, then the appropriate collating function specified in
70826 ** P4 is  used to do the comparison.  If P4 is not specified then
70827 ** memcmp() is used to compare text string.  If both values are
70828 ** numeric, then a numeric comparison is used. If the two values
70829 ** are of different types, then numbers are considered less than
70830 ** strings and strings are considered less than blobs.
70831 **
70832 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
70833 ** store a boolean result (either 0, or 1, or NULL) in register P2.
70834 **
70835 ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
70836 ** equal to one another, provided that they do not have their MEM_Cleared
70837 ** bit set.
70838 */
70839 /* Opcode: Ne P1 P2 P3 P4 P5
70840 ** Synopsis: if r[P1]!=r[P3] goto P2
70841 **
70842 ** This works just like the Lt opcode except that the jump is taken if
70843 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
70844 ** additional information.
70845 **
70846 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
70847 ** true or false and is never NULL.  If both operands are NULL then the result
70848 ** of comparison is false.  If either operand is NULL then the result is true.
70849 ** If neither operand is NULL the result is the same as it would be if
70850 ** the SQLITE_NULLEQ flag were omitted from P5.
70851 */
70852 /* Opcode: Eq P1 P2 P3 P4 P5
70853 ** Synopsis: if r[P1]==r[P3] goto P2
70854 **
70855 ** This works just like the Lt opcode except that the jump is taken if
70856 ** the operands in registers P1 and P3 are equal.
70857 ** See the Lt opcode for additional information.
70858 **
70859 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
70860 ** true or false and is never NULL.  If both operands are NULL then the result
70861 ** of comparison is true.  If either operand is NULL then the result is false.
70862 ** If neither operand is NULL the result is the same as it would be if
70863 ** the SQLITE_NULLEQ flag were omitted from P5.
70864 */
70865 /* Opcode: Le P1 P2 P3 P4 P5
70866 ** Synopsis: if r[P1]<=r[P3] goto P2
70867 **
70868 ** This works just like the Lt opcode except that the jump is taken if
70869 ** the content of register P3 is less than or equal to the content of
70870 ** register P1.  See the Lt opcode for additional information.
70871 */
70872 /* Opcode: Gt P1 P2 P3 P4 P5
70873 ** Synopsis: if r[P1]>r[P3] goto P2
70874 **
70875 ** This works just like the Lt opcode except that the jump is taken if
70876 ** the content of register P3 is greater than the content of
70877 ** register P1.  See the Lt opcode for additional information.
70878 */
70879 /* Opcode: Ge P1 P2 P3 P4 P5
70880 ** Synopsis: if r[P1]>=r[P3] goto P2
70881 **
70882 ** This works just like the Lt opcode except that the jump is taken if
70883 ** the content of register P3 is greater than or equal to the content of
70884 ** register P1.  See the Lt opcode for additional information.
70885 */
70886 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
70887 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
70888 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
70889 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
70890 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
70891 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
70892   int res;            /* Result of the comparison of pIn1 against pIn3 */
70893   char affinity;      /* Affinity to use for comparison */
70894   u16 flags1;         /* Copy of initial value of pIn1->flags */
70895   u16 flags3;         /* Copy of initial value of pIn3->flags */
70896 
70897   pIn1 = &aMem[pOp->p1];
70898   pIn3 = &aMem[pOp->p3];
70899   flags1 = pIn1->flags;
70900   flags3 = pIn3->flags;
70901   if( (flags1 | flags3)&MEM_Null ){
70902     /* One or both operands are NULL */
70903     if( pOp->p5 & SQLITE_NULLEQ ){
70904       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
70905       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
70906       ** or not both operands are null.
70907       */
70908       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
70909       assert( (flags1 & MEM_Cleared)==0 );
70910       assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
70911       if( (flags1&MEM_Null)!=0
70912        && (flags3&MEM_Null)!=0
70913        && (flags3&MEM_Cleared)==0
70914       ){
70915         res = 0;  /* Results are equal */
70916       }else{
70917         res = 1;  /* Results are not equal */
70918       }
70919     }else{
70920       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
70921       ** then the result is always NULL.
70922       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
70923       */
70924       if( pOp->p5 & SQLITE_STOREP2 ){
70925         pOut = &aMem[pOp->p2];
70926         MemSetTypeFlag(pOut, MEM_Null);
70927         REGISTER_TRACE(pOp->p2, pOut);
70928       }else{
70929         VdbeBranchTaken(2,3);
70930         if( pOp->p5 & SQLITE_JUMPIFNULL ){
70931           pc = pOp->p2-1;
70932         }
70933       }
70934       break;
70935     }
70936   }else{
70937     /* Neither operand is NULL.  Do a comparison. */
70938     affinity = pOp->p5 & SQLITE_AFF_MASK;
70939     if( affinity>=SQLITE_AFF_NUMERIC ){
70940       if( (pIn1->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
70941         applyNumericAffinity(pIn1,0);
70942       }
70943       if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
70944         applyNumericAffinity(pIn3,0);
70945       }
70946     }else if( affinity==SQLITE_AFF_TEXT ){
70947       if( (pIn1->flags & MEM_Str)==0 && (pIn1->flags & (MEM_Int|MEM_Real))!=0 ){
70948         testcase( pIn1->flags & MEM_Int );
70949         testcase( pIn1->flags & MEM_Real );
70950         sqlite3VdbeMemStringify(pIn1, encoding, 1);
70951       }
70952       if( (pIn3->flags & MEM_Str)==0 && (pIn3->flags & (MEM_Int|MEM_Real))!=0 ){
70953         testcase( pIn3->flags & MEM_Int );
70954         testcase( pIn3->flags & MEM_Real );
70955         sqlite3VdbeMemStringify(pIn3, encoding, 1);
70956       }
70957     }
70958     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
70959     if( pIn1->flags & MEM_Zero ){
70960       sqlite3VdbeMemExpandBlob(pIn1);
70961       flags1 &= ~MEM_Zero;
70962     }
70963     if( pIn3->flags & MEM_Zero ){
70964       sqlite3VdbeMemExpandBlob(pIn3);
70965       flags3 &= ~MEM_Zero;
70966     }
70967     if( db->mallocFailed ) goto no_mem;
70968     res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
70969   }
70970   switch( pOp->opcode ){
70971     case OP_Eq:    res = res==0;     break;
70972     case OP_Ne:    res = res!=0;     break;
70973     case OP_Lt:    res = res<0;      break;
70974     case OP_Le:    res = res<=0;     break;
70975     case OP_Gt:    res = res>0;      break;
70976     default:       res = res>=0;     break;
70977   }
70978 
70979   if( pOp->p5 & SQLITE_STOREP2 ){
70980     pOut = &aMem[pOp->p2];
70981     memAboutToChange(p, pOut);
70982     MemSetTypeFlag(pOut, MEM_Int);
70983     pOut->u.i = res;
70984     REGISTER_TRACE(pOp->p2, pOut);
70985   }else{
70986     VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
70987     if( res ){
70988       pc = pOp->p2-1;
70989     }
70990   }
70991   /* Undo any changes made by applyAffinity() to the input registers. */
70992   pIn1->flags = flags1;
70993   pIn3->flags = flags3;
70994   break;
70995 }
70996 
70997 /* Opcode: Permutation * * * P4 *
70998 **
70999 ** Set the permutation used by the OP_Compare operator to be the array
71000 ** of integers in P4.
71001 **
71002 ** The permutation is only valid until the next OP_Compare that has
71003 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
71004 ** occur immediately prior to the OP_Compare.
71005 */
71006 case OP_Permutation: {
71007   assert( pOp->p4type==P4_INTARRAY );
71008   assert( pOp->p4.ai );
71009   aPermute = pOp->p4.ai;
71010   break;
71011 }
71012 
71013 /* Opcode: Compare P1 P2 P3 P4 P5
71014 ** Synopsis: r[P1@P3] <-> r[P2@P3]
71015 **
71016 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
71017 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
71018 ** the comparison for use by the next OP_Jump instruct.
71019 **
71020 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
71021 ** determined by the most recent OP_Permutation operator.  If the
71022 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
71023 ** order.
71024 **
71025 ** P4 is a KeyInfo structure that defines collating sequences and sort
71026 ** orders for the comparison.  The permutation applies to registers
71027 ** only.  The KeyInfo elements are used sequentially.
71028 **
71029 ** The comparison is a sort comparison, so NULLs compare equal,
71030 ** NULLs are less than numbers, numbers are less than strings,
71031 ** and strings are less than blobs.
71032 */
71033 case OP_Compare: {
71034   int n;
71035   int i;
71036   int p1;
71037   int p2;
71038   const KeyInfo *pKeyInfo;
71039   int idx;
71040   CollSeq *pColl;    /* Collating sequence to use on this term */
71041   int bRev;          /* True for DESCENDING sort order */
71042 
71043   if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
71044   n = pOp->p3;
71045   pKeyInfo = pOp->p4.pKeyInfo;
71046   assert( n>0 );
71047   assert( pKeyInfo!=0 );
71048   p1 = pOp->p1;
71049   p2 = pOp->p2;
71050 #if SQLITE_DEBUG
71051   if( aPermute ){
71052     int k, mx = 0;
71053     for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
71054     assert( p1>0 && p1+mx<=(p->nMem-p->nCursor)+1 );
71055     assert( p2>0 && p2+mx<=(p->nMem-p->nCursor)+1 );
71056   }else{
71057     assert( p1>0 && p1+n<=(p->nMem-p->nCursor)+1 );
71058     assert( p2>0 && p2+n<=(p->nMem-p->nCursor)+1 );
71059   }
71060 #endif /* SQLITE_DEBUG */
71061   for(i=0; i<n; i++){
71062     idx = aPermute ? aPermute[i] : i;
71063     assert( memIsValid(&aMem[p1+idx]) );
71064     assert( memIsValid(&aMem[p2+idx]) );
71065     REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
71066     REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
71067     assert( i<pKeyInfo->nField );
71068     pColl = pKeyInfo->aColl[i];
71069     bRev = pKeyInfo->aSortOrder[i];
71070     iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
71071     if( iCompare ){
71072       if( bRev ) iCompare = -iCompare;
71073       break;
71074     }
71075   }
71076   aPermute = 0;
71077   break;
71078 }
71079 
71080 /* Opcode: Jump P1 P2 P3 * *
71081 **
71082 ** Jump to the instruction at address P1, P2, or P3 depending on whether
71083 ** in the most recent OP_Compare instruction the P1 vector was less than
71084 ** equal to, or greater than the P2 vector, respectively.
71085 */
71086 case OP_Jump: {             /* jump */
71087   if( iCompare<0 ){
71088     pc = pOp->p1 - 1;  VdbeBranchTaken(0,3);
71089   }else if( iCompare==0 ){
71090     pc = pOp->p2 - 1;  VdbeBranchTaken(1,3);
71091   }else{
71092     pc = pOp->p3 - 1;  VdbeBranchTaken(2,3);
71093   }
71094   break;
71095 }
71096 
71097 /* Opcode: And P1 P2 P3 * *
71098 ** Synopsis: r[P3]=(r[P1] && r[P2])
71099 **
71100 ** Take the logical AND of the values in registers P1 and P2 and
71101 ** write the result into register P3.
71102 **
71103 ** If either P1 or P2 is 0 (false) then the result is 0 even if
71104 ** the other input is NULL.  A NULL and true or two NULLs give
71105 ** a NULL output.
71106 */
71107 /* Opcode: Or P1 P2 P3 * *
71108 ** Synopsis: r[P3]=(r[P1] || r[P2])
71109 **
71110 ** Take the logical OR of the values in register P1 and P2 and
71111 ** store the answer in register P3.
71112 **
71113 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
71114 ** even if the other input is NULL.  A NULL and false or two NULLs
71115 ** give a NULL output.
71116 */
71117 case OP_And:              /* same as TK_AND, in1, in2, out3 */
71118 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
71119   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
71120   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
71121 
71122   pIn1 = &aMem[pOp->p1];
71123   if( pIn1->flags & MEM_Null ){
71124     v1 = 2;
71125   }else{
71126     v1 = sqlite3VdbeIntValue(pIn1)!=0;
71127   }
71128   pIn2 = &aMem[pOp->p2];
71129   if( pIn2->flags & MEM_Null ){
71130     v2 = 2;
71131   }else{
71132     v2 = sqlite3VdbeIntValue(pIn2)!=0;
71133   }
71134   if( pOp->opcode==OP_And ){
71135     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
71136     v1 = and_logic[v1*3+v2];
71137   }else{
71138     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
71139     v1 = or_logic[v1*3+v2];
71140   }
71141   pOut = &aMem[pOp->p3];
71142   if( v1==2 ){
71143     MemSetTypeFlag(pOut, MEM_Null);
71144   }else{
71145     pOut->u.i = v1;
71146     MemSetTypeFlag(pOut, MEM_Int);
71147   }
71148   break;
71149 }
71150 
71151 /* Opcode: Not P1 P2 * * *
71152 ** Synopsis: r[P2]= !r[P1]
71153 **
71154 ** Interpret the value in register P1 as a boolean value.  Store the
71155 ** boolean complement in register P2.  If the value in register P1 is
71156 ** NULL, then a NULL is stored in P2.
71157 */
71158 case OP_Not: {                /* same as TK_NOT, in1, out2 */
71159   pIn1 = &aMem[pOp->p1];
71160   pOut = &aMem[pOp->p2];
71161   sqlite3VdbeMemSetNull(pOut);
71162   if( (pIn1->flags & MEM_Null)==0 ){
71163     pOut->flags = MEM_Int;
71164     pOut->u.i = !sqlite3VdbeIntValue(pIn1);
71165   }
71166   break;
71167 }
71168 
71169 /* Opcode: BitNot P1 P2 * * *
71170 ** Synopsis: r[P1]= ~r[P1]
71171 **
71172 ** Interpret the content of register P1 as an integer.  Store the
71173 ** ones-complement of the P1 value into register P2.  If P1 holds
71174 ** a NULL then store a NULL in P2.
71175 */
71176 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
71177   pIn1 = &aMem[pOp->p1];
71178   pOut = &aMem[pOp->p2];
71179   sqlite3VdbeMemSetNull(pOut);
71180   if( (pIn1->flags & MEM_Null)==0 ){
71181     pOut->flags = MEM_Int;
71182     pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
71183   }
71184   break;
71185 }
71186 
71187 /* Opcode: Once P1 P2 * * *
71188 **
71189 ** Check the "once" flag number P1. If it is set, jump to instruction P2.
71190 ** Otherwise, set the flag and fall through to the next instruction.
71191 ** In other words, this opcode causes all following opcodes up through P2
71192 ** (but not including P2) to run just once and to be skipped on subsequent
71193 ** times through the loop.
71194 **
71195 ** All "once" flags are initially cleared whenever a prepared statement
71196 ** first begins to run.
71197 */
71198 case OP_Once: {             /* jump */
71199   assert( pOp->p1<p->nOnceFlag );
71200   VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
71201   if( p->aOnceFlag[pOp->p1] ){
71202     pc = pOp->p2-1;
71203   }else{
71204     p->aOnceFlag[pOp->p1] = 1;
71205   }
71206   break;
71207 }
71208 
71209 /* Opcode: If P1 P2 P3 * *
71210 **
71211 ** Jump to P2 if the value in register P1 is true.  The value
71212 ** is considered true if it is numeric and non-zero.  If the value
71213 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
71214 */
71215 /* Opcode: IfNot P1 P2 P3 * *
71216 **
71217 ** Jump to P2 if the value in register P1 is False.  The value
71218 ** is considered false if it has a numeric value of zero.  If the value
71219 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
71220 */
71221 case OP_If:                 /* jump, in1 */
71222 case OP_IfNot: {            /* jump, in1 */
71223   int c;
71224   pIn1 = &aMem[pOp->p1];
71225   if( pIn1->flags & MEM_Null ){
71226     c = pOp->p3;
71227   }else{
71228 #ifdef SQLITE_OMIT_FLOATING_POINT
71229     c = sqlite3VdbeIntValue(pIn1)!=0;
71230 #else
71231     c = sqlite3VdbeRealValue(pIn1)!=0.0;
71232 #endif
71233     if( pOp->opcode==OP_IfNot ) c = !c;
71234   }
71235   VdbeBranchTaken(c!=0, 2);
71236   if( c ){
71237     pc = pOp->p2-1;
71238   }
71239   break;
71240 }
71241 
71242 /* Opcode: IsNull P1 P2 * * *
71243 ** Synopsis:  if r[P1]==NULL goto P2
71244 **
71245 ** Jump to P2 if the value in register P1 is NULL.
71246 */
71247 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
71248   pIn1 = &aMem[pOp->p1];
71249   VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
71250   if( (pIn1->flags & MEM_Null)!=0 ){
71251     pc = pOp->p2 - 1;
71252   }
71253   break;
71254 }
71255 
71256 /* Opcode: NotNull P1 P2 * * *
71257 ** Synopsis: if r[P1]!=NULL goto P2
71258 **
71259 ** Jump to P2 if the value in register P1 is not NULL.
71260 */
71261 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
71262   pIn1 = &aMem[pOp->p1];
71263   VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
71264   if( (pIn1->flags & MEM_Null)==0 ){
71265     pc = pOp->p2 - 1;
71266   }
71267   break;
71268 }
71269 
71270 /* Opcode: Column P1 P2 P3 P4 P5
71271 ** Synopsis:  r[P3]=PX
71272 **
71273 ** Interpret the data that cursor P1 points to as a structure built using
71274 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
71275 ** information about the format of the data.)  Extract the P2-th column
71276 ** from this record.  If there are less that (P2+1)
71277 ** values in the record, extract a NULL.
71278 **
71279 ** The value extracted is stored in register P3.
71280 **
71281 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
71282 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
71283 ** the result.
71284 **
71285 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
71286 ** then the cache of the cursor is reset prior to extracting the column.
71287 ** The first OP_Column against a pseudo-table after the value of the content
71288 ** register has changed should have this bit set.
71289 **
71290 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
71291 ** the result is guaranteed to only be used as the argument of a length()
71292 ** or typeof() function, respectively.  The loading of large blobs can be
71293 ** skipped for length() and all content loading can be skipped for typeof().
71294 */
71295 case OP_Column: {
71296   i64 payloadSize64; /* Number of bytes in the record */
71297   int p2;            /* column number to retrieve */
71298   VdbeCursor *pC;    /* The VDBE cursor */
71299   BtCursor *pCrsr;   /* The BTree cursor */
71300   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
71301   int len;           /* The length of the serialized data for the column */
71302   int i;             /* Loop counter */
71303   Mem *pDest;        /* Where to write the extracted value */
71304   Mem sMem;          /* For storing the record being decoded */
71305   const u8 *zData;   /* Part of the record being decoded */
71306   const u8 *zHdr;    /* Next unparsed byte of the header */
71307   const u8 *zEndHdr; /* Pointer to first byte after the header */
71308   u32 offset;        /* Offset into the data */
71309   u32 szField;       /* Number of bytes in the content of a field */
71310   u32 avail;         /* Number of bytes of available data */
71311   u32 t;             /* A type code from the record header */
71312   u16 fx;            /* pDest->flags value */
71313   Mem *pReg;         /* PseudoTable input register */
71314 
71315   p2 = pOp->p2;
71316   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
71317   pDest = &aMem[pOp->p3];
71318   memAboutToChange(p, pDest);
71319   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
71320   pC = p->apCsr[pOp->p1];
71321   assert( pC!=0 );
71322   assert( p2<pC->nField );
71323   aOffset = pC->aOffset;
71324 #ifndef SQLITE_OMIT_VIRTUALTABLE
71325   assert( pC->pVtabCursor==0 ); /* OP_Column never called on virtual table */
71326 #endif
71327   pCrsr = pC->pCursor;
71328   assert( pCrsr!=0 || pC->pseudoTableReg>0 ); /* pCrsr NULL on PseudoTables */
71329   assert( pCrsr!=0 || pC->nullRow );          /* pC->nullRow on PseudoTables */
71330 
71331   /* If the cursor cache is stale, bring it up-to-date */
71332   rc = sqlite3VdbeCursorMoveto(pC);
71333   if( rc ) goto abort_due_to_error;
71334   if( pC->cacheStatus!=p->cacheCtr ){
71335     if( pC->nullRow ){
71336       if( pCrsr==0 ){
71337         assert( pC->pseudoTableReg>0 );
71338         pReg = &aMem[pC->pseudoTableReg];
71339         assert( pReg->flags & MEM_Blob );
71340         assert( memIsValid(pReg) );
71341         pC->payloadSize = pC->szRow = avail = pReg->n;
71342         pC->aRow = (u8*)pReg->z;
71343       }else{
71344         sqlite3VdbeMemSetNull(pDest);
71345         goto op_column_out;
71346       }
71347     }else{
71348       assert( pCrsr );
71349       if( pC->isTable==0 ){
71350         assert( sqlite3BtreeCursorIsValid(pCrsr) );
71351         VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &payloadSize64);
71352         assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
71353         /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
71354         ** payload size, so it is impossible for payloadSize64 to be
71355         ** larger than 32 bits. */
71356         assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
71357         pC->aRow = sqlite3BtreeKeyFetch(pCrsr, &avail);
71358         pC->payloadSize = (u32)payloadSize64;
71359       }else{
71360         assert( sqlite3BtreeCursorIsValid(pCrsr) );
71361         VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &pC->payloadSize);
71362         assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
71363         pC->aRow = sqlite3BtreeDataFetch(pCrsr, &avail);
71364       }
71365       assert( avail<=65536 );  /* Maximum page size is 64KiB */
71366       if( pC->payloadSize <= (u32)avail ){
71367         pC->szRow = pC->payloadSize;
71368       }else{
71369         pC->szRow = avail;
71370       }
71371       if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
71372         goto too_big;
71373       }
71374     }
71375     pC->cacheStatus = p->cacheCtr;
71376     pC->iHdrOffset = getVarint32(pC->aRow, offset);
71377     pC->nHdrParsed = 0;
71378     aOffset[0] = offset;
71379 
71380     /* Make sure a corrupt database has not given us an oversize header.
71381     ** Do this now to avoid an oversize memory allocation.
71382     **
71383     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
71384     ** types use so much data space that there can only be 4096 and 32 of
71385     ** them, respectively.  So the maximum header length results from a
71386     ** 3-byte type for each of the maximum of 32768 columns plus three
71387     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
71388     */
71389     if( offset > 98307 || offset > pC->payloadSize ){
71390       rc = SQLITE_CORRUPT_BKPT;
71391       goto op_column_error;
71392     }
71393 
71394     if( avail<offset ){
71395       /* pC->aRow does not have to hold the entire row, but it does at least
71396       ** need to cover the header of the record.  If pC->aRow does not contain
71397       ** the complete header, then set it to zero, forcing the header to be
71398       ** dynamically allocated. */
71399       pC->aRow = 0;
71400       pC->szRow = 0;
71401     }
71402 
71403     /* The following goto is an optimization.  It can be omitted and
71404     ** everything will still work.  But OP_Column is measurably faster
71405     ** by skipping the subsequent conditional, which is always true.
71406     */
71407     assert( pC->nHdrParsed<=p2 );         /* Conditional skipped */
71408     goto op_column_read_header;
71409   }
71410 
71411   /* Make sure at least the first p2+1 entries of the header have been
71412   ** parsed and valid information is in aOffset[] and pC->aType[].
71413   */
71414   if( pC->nHdrParsed<=p2 ){
71415     /* If there is more header available for parsing in the record, try
71416     ** to extract additional fields up through the p2+1-th field
71417     */
71418     op_column_read_header:
71419     if( pC->iHdrOffset<aOffset[0] ){
71420       /* Make sure zData points to enough of the record to cover the header. */
71421       if( pC->aRow==0 ){
71422         memset(&sMem, 0, sizeof(sMem));
71423         rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0],
71424                                      !pC->isTable, &sMem);
71425         if( rc!=SQLITE_OK ){
71426           goto op_column_error;
71427         }
71428         zData = (u8*)sMem.z;
71429       }else{
71430         zData = pC->aRow;
71431       }
71432 
71433       /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
71434       i = pC->nHdrParsed;
71435       offset = aOffset[i];
71436       zHdr = zData + pC->iHdrOffset;
71437       zEndHdr = zData + aOffset[0];
71438       assert( i<=p2 && zHdr<zEndHdr );
71439       do{
71440         if( zHdr[0]<0x80 ){
71441           t = zHdr[0];
71442           zHdr++;
71443         }else{
71444           zHdr += sqlite3GetVarint32(zHdr, &t);
71445         }
71446         pC->aType[i] = t;
71447         szField = sqlite3VdbeSerialTypeLen(t);
71448         offset += szField;
71449         if( offset<szField ){  /* True if offset overflows */
71450           zHdr = &zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
71451           break;
71452         }
71453         i++;
71454         aOffset[i] = offset;
71455       }while( i<=p2 && zHdr<zEndHdr );
71456       pC->nHdrParsed = i;
71457       pC->iHdrOffset = (u32)(zHdr - zData);
71458       if( pC->aRow==0 ){
71459         sqlite3VdbeMemRelease(&sMem);
71460         sMem.flags = MEM_Null;
71461       }
71462 
71463       /* The record is corrupt if any of the following are true:
71464       ** (1) the bytes of the header extend past the declared header size
71465       **          (zHdr>zEndHdr)
71466       ** (2) the entire header was used but not all data was used
71467       **          (zHdr==zEndHdr && offset!=pC->payloadSize)
71468       ** (3) the end of the data extends beyond the end of the record.
71469       **          (offset > pC->payloadSize)
71470       */
71471       if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset!=pC->payloadSize))
71472        || (offset > pC->payloadSize)
71473       ){
71474         rc = SQLITE_CORRUPT_BKPT;
71475         goto op_column_error;
71476       }
71477     }
71478 
71479     /* If after trying to extra new entries from the header, nHdrParsed is
71480     ** still not up to p2, that means that the record has fewer than p2
71481     ** columns.  So the result will be either the default value or a NULL.
71482     */
71483     if( pC->nHdrParsed<=p2 ){
71484       if( pOp->p4type==P4_MEM ){
71485         sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
71486       }else{
71487         sqlite3VdbeMemSetNull(pDest);
71488       }
71489       goto op_column_out;
71490     }
71491   }
71492 
71493   /* Extract the content for the p2+1-th column.  Control can only
71494   ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
71495   ** all valid.
71496   */
71497   assert( p2<pC->nHdrParsed );
71498   assert( rc==SQLITE_OK );
71499   assert( sqlite3VdbeCheckMemInvariants(pDest) );
71500   if( VdbeMemDynamic(pDest) ) sqlite3VdbeMemSetNull(pDest);
71501   t = pC->aType[p2];
71502   if( pC->szRow>=aOffset[p2+1] ){
71503     /* This is the common case where the desired content fits on the original
71504     ** page - where the content is not on an overflow page */
71505     sqlite3VdbeSerialGet(pC->aRow+aOffset[p2], t, pDest);
71506   }else{
71507     /* This branch happens only when content is on overflow pages */
71508     if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
71509           && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
71510      || (len = sqlite3VdbeSerialTypeLen(t))==0
71511     ){
71512       /* Content is irrelevant for
71513       **    1. the typeof() function,
71514       **    2. the length(X) function if X is a blob, and
71515       **    3. if the content length is zero.
71516       ** So we might as well use bogus content rather than reading
71517       ** content from disk.  NULL will work for the value for strings
71518       ** and blobs and whatever is in the payloadSize64 variable
71519       ** will work for everything else. */
71520       sqlite3VdbeSerialGet(t<=13 ? (u8*)&payloadSize64 : 0, t, pDest);
71521     }else{
71522       rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
71523                                    pDest);
71524       if( rc!=SQLITE_OK ){
71525         goto op_column_error;
71526       }
71527       sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
71528       pDest->flags &= ~MEM_Ephem;
71529     }
71530   }
71531   pDest->enc = encoding;
71532 
71533 op_column_out:
71534   /* If the column value is an ephemeral string, go ahead and persist
71535   ** that string in case the cursor moves before the column value is
71536   ** used.  The following code does the equivalent of Deephemeralize()
71537   ** but does it faster. */
71538   if( (pDest->flags & MEM_Ephem)!=0 && pDest->z ){
71539     fx = pDest->flags & (MEM_Str|MEM_Blob);
71540     assert( fx!=0 );
71541     zData = (const u8*)pDest->z;
71542     len = pDest->n;
71543     if( sqlite3VdbeMemClearAndResize(pDest, len+2) ) goto no_mem;
71544     memcpy(pDest->z, zData, len);
71545     pDest->z[len] = 0;
71546     pDest->z[len+1] = 0;
71547     pDest->flags = fx|MEM_Term;
71548   }
71549 op_column_error:
71550   UPDATE_MAX_BLOBSIZE(pDest);
71551   REGISTER_TRACE(pOp->p3, pDest);
71552   break;
71553 }
71554 
71555 /* Opcode: Affinity P1 P2 * P4 *
71556 ** Synopsis: affinity(r[P1@P2])
71557 **
71558 ** Apply affinities to a range of P2 registers starting with P1.
71559 **
71560 ** P4 is a string that is P2 characters long. The nth character of the
71561 ** string indicates the column affinity that should be used for the nth
71562 ** memory cell in the range.
71563 */
71564 case OP_Affinity: {
71565   const char *zAffinity;   /* The affinity to be applied */
71566   char cAff;               /* A single character of affinity */
71567 
71568   zAffinity = pOp->p4.z;
71569   assert( zAffinity!=0 );
71570   assert( zAffinity[pOp->p2]==0 );
71571   pIn1 = &aMem[pOp->p1];
71572   while( (cAff = *(zAffinity++))!=0 ){
71573     assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
71574     assert( memIsValid(pIn1) );
71575     applyAffinity(pIn1, cAff, encoding);
71576     pIn1++;
71577   }
71578   break;
71579 }
71580 
71581 /* Opcode: MakeRecord P1 P2 P3 P4 *
71582 ** Synopsis: r[P3]=mkrec(r[P1@P2])
71583 **
71584 ** Convert P2 registers beginning with P1 into the [record format]
71585 ** use as a data record in a database table or as a key
71586 ** in an index.  The OP_Column opcode can decode the record later.
71587 **
71588 ** P4 may be a string that is P2 characters long.  The nth character of the
71589 ** string indicates the column affinity that should be used for the nth
71590 ** field of the index key.
71591 **
71592 ** The mapping from character to affinity is given by the SQLITE_AFF_
71593 ** macros defined in sqliteInt.h.
71594 **
71595 ** If P4 is NULL then all index fields have the affinity NONE.
71596 */
71597 case OP_MakeRecord: {
71598   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
71599   Mem *pRec;             /* The new record */
71600   u64 nData;             /* Number of bytes of data space */
71601   int nHdr;              /* Number of bytes of header space */
71602   i64 nByte;             /* Data space required for this record */
71603   int nZero;             /* Number of zero bytes at the end of the record */
71604   int nVarint;           /* Number of bytes in a varint */
71605   u32 serial_type;       /* Type field */
71606   Mem *pData0;           /* First field to be combined into the record */
71607   Mem *pLast;            /* Last field of the record */
71608   int nField;            /* Number of fields in the record */
71609   char *zAffinity;       /* The affinity string for the record */
71610   int file_format;       /* File format to use for encoding */
71611   int i;                 /* Space used in zNewRecord[] header */
71612   int j;                 /* Space used in zNewRecord[] content */
71613   int len;               /* Length of a field */
71614 
71615   /* Assuming the record contains N fields, the record format looks
71616   ** like this:
71617   **
71618   ** ------------------------------------------------------------------------
71619   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
71620   ** ------------------------------------------------------------------------
71621   **
71622   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
71623   ** and so forth.
71624   **
71625   ** Each type field is a varint representing the serial type of the
71626   ** corresponding data element (see sqlite3VdbeSerialType()). The
71627   ** hdr-size field is also a varint which is the offset from the beginning
71628   ** of the record to data0.
71629   */
71630   nData = 0;         /* Number of bytes of data space */
71631   nHdr = 0;          /* Number of bytes of header space */
71632   nZero = 0;         /* Number of zero bytes at the end of the record */
71633   nField = pOp->p1;
71634   zAffinity = pOp->p4.z;
71635   assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem-p->nCursor)+1 );
71636   pData0 = &aMem[nField];
71637   nField = pOp->p2;
71638   pLast = &pData0[nField-1];
71639   file_format = p->minWriteFileFormat;
71640 
71641   /* Identify the output register */
71642   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
71643   pOut = &aMem[pOp->p3];
71644   memAboutToChange(p, pOut);
71645 
71646   /* Apply the requested affinity to all inputs
71647   */
71648   assert( pData0<=pLast );
71649   if( zAffinity ){
71650     pRec = pData0;
71651     do{
71652       applyAffinity(pRec++, *(zAffinity++), encoding);
71653       assert( zAffinity[0]==0 || pRec<=pLast );
71654     }while( zAffinity[0] );
71655   }
71656 
71657   /* Loop through the elements that will make up the record to figure
71658   ** out how much space is required for the new record.
71659   */
71660   pRec = pLast;
71661   do{
71662     assert( memIsValid(pRec) );
71663     pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format);
71664     len = sqlite3VdbeSerialTypeLen(serial_type);
71665     if( pRec->flags & MEM_Zero ){
71666       if( nData ){
71667         sqlite3VdbeMemExpandBlob(pRec);
71668       }else{
71669         nZero += pRec->u.nZero;
71670         len -= pRec->u.nZero;
71671       }
71672     }
71673     nData += len;
71674     testcase( serial_type==127 );
71675     testcase( serial_type==128 );
71676     nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
71677   }while( (--pRec)>=pData0 );
71678 
71679   /* Add the initial header varint and total the size */
71680   testcase( nHdr==126 );
71681   testcase( nHdr==127 );
71682   if( nHdr<=126 ){
71683     /* The common case */
71684     nHdr += 1;
71685   }else{
71686     /* Rare case of a really large header */
71687     nVarint = sqlite3VarintLen(nHdr);
71688     nHdr += nVarint;
71689     if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
71690   }
71691   nByte = nHdr+nData;
71692   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
71693     goto too_big;
71694   }
71695 
71696   /* Make sure the output register has a buffer large enough to store
71697   ** the new record. The output register (pOp->p3) is not allowed to
71698   ** be one of the input registers (because the following call to
71699   ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
71700   */
71701   if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
71702     goto no_mem;
71703   }
71704   zNewRecord = (u8 *)pOut->z;
71705 
71706   /* Write the record */
71707   i = putVarint32(zNewRecord, nHdr);
71708   j = nHdr;
71709   assert( pData0<=pLast );
71710   pRec = pData0;
71711   do{
71712     serial_type = pRec->uTemp;
71713     i += putVarint32(&zNewRecord[i], serial_type);            /* serial type */
71714     j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
71715   }while( (++pRec)<=pLast );
71716   assert( i==nHdr );
71717   assert( j==nByte );
71718 
71719   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
71720   pOut->n = (int)nByte;
71721   pOut->flags = MEM_Blob;
71722   if( nZero ){
71723     pOut->u.nZero = nZero;
71724     pOut->flags |= MEM_Zero;
71725   }
71726   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
71727   REGISTER_TRACE(pOp->p3, pOut);
71728   UPDATE_MAX_BLOBSIZE(pOut);
71729   break;
71730 }
71731 
71732 /* Opcode: Count P1 P2 * * *
71733 ** Synopsis: r[P2]=count()
71734 **
71735 ** Store the number of entries (an integer value) in the table or index
71736 ** opened by cursor P1 in register P2
71737 */
71738 #ifndef SQLITE_OMIT_BTREECOUNT
71739 case OP_Count: {         /* out2-prerelease */
71740   i64 nEntry;
71741   BtCursor *pCrsr;
71742 
71743   pCrsr = p->apCsr[pOp->p1]->pCursor;
71744   assert( pCrsr );
71745   nEntry = 0;  /* Not needed.  Only used to silence a warning. */
71746   rc = sqlite3BtreeCount(pCrsr, &nEntry);
71747   pOut->u.i = nEntry;
71748   break;
71749 }
71750 #endif
71751 
71752 /* Opcode: Savepoint P1 * * P4 *
71753 **
71754 ** Open, release or rollback the savepoint named by parameter P4, depending
71755 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
71756 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
71757 */
71758 case OP_Savepoint: {
71759   int p1;                         /* Value of P1 operand */
71760   char *zName;                    /* Name of savepoint */
71761   int nName;
71762   Savepoint *pNew;
71763   Savepoint *pSavepoint;
71764   Savepoint *pTmp;
71765   int iSavepoint;
71766   int ii;
71767 
71768   p1 = pOp->p1;
71769   zName = pOp->p4.z;
71770 
71771   /* Assert that the p1 parameter is valid. Also that if there is no open
71772   ** transaction, then there cannot be any savepoints.
71773   */
71774   assert( db->pSavepoint==0 || db->autoCommit==0 );
71775   assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
71776   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
71777   assert( checkSavepointCount(db) );
71778   assert( p->bIsReader );
71779 
71780   if( p1==SAVEPOINT_BEGIN ){
71781     if( db->nVdbeWrite>0 ){
71782       /* A new savepoint cannot be created if there are active write
71783       ** statements (i.e. open read/write incremental blob handles).
71784       */
71785       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
71786         "SQL statements in progress");
71787       rc = SQLITE_BUSY;
71788     }else{
71789       nName = sqlite3Strlen30(zName);
71790 
71791 #ifndef SQLITE_OMIT_VIRTUALTABLE
71792       /* This call is Ok even if this savepoint is actually a transaction
71793       ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
71794       ** If this is a transaction savepoint being opened, it is guaranteed
71795       ** that the db->aVTrans[] array is empty.  */
71796       assert( db->autoCommit==0 || db->nVTrans==0 );
71797       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
71798                                 db->nStatement+db->nSavepoint);
71799       if( rc!=SQLITE_OK ) goto abort_due_to_error;
71800 #endif
71801 
71802       /* Create a new savepoint structure. */
71803       pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
71804       if( pNew ){
71805         pNew->zName = (char *)&pNew[1];
71806         memcpy(pNew->zName, zName, nName+1);
71807 
71808         /* If there is no open transaction, then mark this as a special
71809         ** "transaction savepoint". */
71810         if( db->autoCommit ){
71811           db->autoCommit = 0;
71812           db->isTransactionSavepoint = 1;
71813         }else{
71814           db->nSavepoint++;
71815         }
71816 
71817         /* Link the new savepoint into the database handle's list. */
71818         pNew->pNext = db->pSavepoint;
71819         db->pSavepoint = pNew;
71820         pNew->nDeferredCons = db->nDeferredCons;
71821         pNew->nDeferredImmCons = db->nDeferredImmCons;
71822       }
71823     }
71824   }else{
71825     iSavepoint = 0;
71826 
71827     /* Find the named savepoint. If there is no such savepoint, then an
71828     ** an error is returned to the user.  */
71829     for(
71830       pSavepoint = db->pSavepoint;
71831       pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
71832       pSavepoint = pSavepoint->pNext
71833     ){
71834       iSavepoint++;
71835     }
71836     if( !pSavepoint ){
71837       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", zName);
71838       rc = SQLITE_ERROR;
71839     }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
71840       /* It is not possible to release (commit) a savepoint if there are
71841       ** active write statements.
71842       */
71843       sqlite3SetString(&p->zErrMsg, db,
71844         "cannot release savepoint - SQL statements in progress"
71845       );
71846       rc = SQLITE_BUSY;
71847     }else{
71848 
71849       /* Determine whether or not this is a transaction savepoint. If so,
71850       ** and this is a RELEASE command, then the current transaction
71851       ** is committed.
71852       */
71853       int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
71854       if( isTransaction && p1==SAVEPOINT_RELEASE ){
71855         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
71856           goto vdbe_return;
71857         }
71858         db->autoCommit = 1;
71859         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
71860           p->pc = pc;
71861           db->autoCommit = 0;
71862           p->rc = rc = SQLITE_BUSY;
71863           goto vdbe_return;
71864         }
71865         db->isTransactionSavepoint = 0;
71866         rc = p->rc;
71867       }else{
71868         int isSchemaChange;
71869         iSavepoint = db->nSavepoint - iSavepoint - 1;
71870         if( p1==SAVEPOINT_ROLLBACK ){
71871           isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
71872           for(ii=0; ii<db->nDb; ii++){
71873             rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
71874                                        SQLITE_ABORT_ROLLBACK,
71875                                        isSchemaChange==0);
71876             if( rc!=SQLITE_OK ) goto abort_due_to_error;
71877           }
71878         }else{
71879           isSchemaChange = 0;
71880         }
71881         for(ii=0; ii<db->nDb; ii++){
71882           rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
71883           if( rc!=SQLITE_OK ){
71884             goto abort_due_to_error;
71885           }
71886         }
71887         if( isSchemaChange ){
71888           sqlite3ExpirePreparedStatements(db);
71889           sqlite3ResetAllSchemasOfConnection(db);
71890           db->flags = (db->flags | SQLITE_InternChanges);
71891         }
71892       }
71893 
71894       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
71895       ** savepoints nested inside of the savepoint being operated on. */
71896       while( db->pSavepoint!=pSavepoint ){
71897         pTmp = db->pSavepoint;
71898         db->pSavepoint = pTmp->pNext;
71899         sqlite3DbFree(db, pTmp);
71900         db->nSavepoint--;
71901       }
71902 
71903       /* If it is a RELEASE, then destroy the savepoint being operated on
71904       ** too. If it is a ROLLBACK TO, then set the number of deferred
71905       ** constraint violations present in the database to the value stored
71906       ** when the savepoint was created.  */
71907       if( p1==SAVEPOINT_RELEASE ){
71908         assert( pSavepoint==db->pSavepoint );
71909         db->pSavepoint = pSavepoint->pNext;
71910         sqlite3DbFree(db, pSavepoint);
71911         if( !isTransaction ){
71912           db->nSavepoint--;
71913         }
71914       }else{
71915         db->nDeferredCons = pSavepoint->nDeferredCons;
71916         db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
71917       }
71918 
71919       if( !isTransaction ){
71920         rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
71921         if( rc!=SQLITE_OK ) goto abort_due_to_error;
71922       }
71923     }
71924   }
71925 
71926   break;
71927 }
71928 
71929 /* Opcode: AutoCommit P1 P2 * * *
71930 **
71931 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
71932 ** back any currently active btree transactions. If there are any active
71933 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
71934 ** there are active writing VMs or active VMs that use shared cache.
71935 **
71936 ** This instruction causes the VM to halt.
71937 */
71938 case OP_AutoCommit: {
71939   int desiredAutoCommit;
71940   int iRollback;
71941   int turnOnAC;
71942 
71943   desiredAutoCommit = pOp->p1;
71944   iRollback = pOp->p2;
71945   turnOnAC = desiredAutoCommit && !db->autoCommit;
71946   assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
71947   assert( desiredAutoCommit==1 || iRollback==0 );
71948   assert( db->nVdbeActive>0 );  /* At least this one VM is active */
71949   assert( p->bIsReader );
71950 
71951 #if 0
71952   if( turnOnAC && iRollback && db->nVdbeActive>1 ){
71953     /* If this instruction implements a ROLLBACK and other VMs are
71954     ** still running, and a transaction is active, return an error indicating
71955     ** that the other VMs must complete first.
71956     */
71957     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
71958         "SQL statements in progress");
71959     rc = SQLITE_BUSY;
71960   }else
71961 #endif
71962   if( turnOnAC && !iRollback && db->nVdbeWrite>0 ){
71963     /* If this instruction implements a COMMIT and other VMs are writing
71964     ** return an error indicating that the other VMs must complete first.
71965     */
71966     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
71967         "SQL statements in progress");
71968     rc = SQLITE_BUSY;
71969   }else if( desiredAutoCommit!=db->autoCommit ){
71970     if( iRollback ){
71971       assert( desiredAutoCommit==1 );
71972       sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
71973       db->autoCommit = 1;
71974     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
71975       goto vdbe_return;
71976     }else{
71977       db->autoCommit = (u8)desiredAutoCommit;
71978       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
71979         p->pc = pc;
71980         db->autoCommit = (u8)(1-desiredAutoCommit);
71981         p->rc = rc = SQLITE_BUSY;
71982         goto vdbe_return;
71983       }
71984     }
71985     assert( db->nStatement==0 );
71986     sqlite3CloseSavepoints(db);
71987     if( p->rc==SQLITE_OK ){
71988       rc = SQLITE_DONE;
71989     }else{
71990       rc = SQLITE_ERROR;
71991     }
71992     goto vdbe_return;
71993   }else{
71994     sqlite3SetString(&p->zErrMsg, db,
71995         (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
71996         (iRollback)?"cannot rollback - no transaction is active":
71997                    "cannot commit - no transaction is active"));
71998 
71999     rc = SQLITE_ERROR;
72000   }
72001   break;
72002 }
72003 
72004 /* Opcode: Transaction P1 P2 P3 P4 P5
72005 **
72006 ** Begin a transaction on database P1 if a transaction is not already
72007 ** active.
72008 ** If P2 is non-zero, then a write-transaction is started, or if a
72009 ** read-transaction is already active, it is upgraded to a write-transaction.
72010 ** If P2 is zero, then a read-transaction is started.
72011 **
72012 ** P1 is the index of the database file on which the transaction is
72013 ** started.  Index 0 is the main database file and index 1 is the
72014 ** file used for temporary tables.  Indices of 2 or more are used for
72015 ** attached databases.
72016 **
72017 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
72018 ** true (this flag is set if the Vdbe may modify more than one row and may
72019 ** throw an ABORT exception), a statement transaction may also be opened.
72020 ** More specifically, a statement transaction is opened iff the database
72021 ** connection is currently not in autocommit mode, or if there are other
72022 ** active statements. A statement transaction allows the changes made by this
72023 ** VDBE to be rolled back after an error without having to roll back the
72024 ** entire transaction. If no error is encountered, the statement transaction
72025 ** will automatically commit when the VDBE halts.
72026 **
72027 ** If P5!=0 then this opcode also checks the schema cookie against P3
72028 ** and the schema generation counter against P4.
72029 ** The cookie changes its value whenever the database schema changes.
72030 ** This operation is used to detect when that the cookie has changed
72031 ** and that the current process needs to reread the schema.  If the schema
72032 ** cookie in P3 differs from the schema cookie in the database header or
72033 ** if the schema generation counter in P4 differs from the current
72034 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
72035 ** halts.  The sqlite3_step() wrapper function might then reprepare the
72036 ** statement and rerun it from the beginning.
72037 */
72038 case OP_Transaction: {
72039   Btree *pBt;
72040   int iMeta;
72041   int iGen;
72042 
72043   assert( p->bIsReader );
72044   assert( p->readOnly==0 || pOp->p2==0 );
72045   assert( pOp->p1>=0 && pOp->p1<db->nDb );
72046   assert( DbMaskTest(p->btreeMask, pOp->p1) );
72047   if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
72048     rc = SQLITE_READONLY;
72049     goto abort_due_to_error;
72050   }
72051   pBt = db->aDb[pOp->p1].pBt;
72052 
72053   if( pBt ){
72054     rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
72055     if( rc==SQLITE_BUSY ){
72056       p->pc = pc;
72057       p->rc = rc = SQLITE_BUSY;
72058       goto vdbe_return;
72059     }
72060     if( rc!=SQLITE_OK ){
72061       goto abort_due_to_error;
72062     }
72063 
72064     if( pOp->p2 && p->usesStmtJournal
72065      && (db->autoCommit==0 || db->nVdbeRead>1)
72066     ){
72067       assert( sqlite3BtreeIsInTrans(pBt) );
72068       if( p->iStatement==0 ){
72069         assert( db->nStatement>=0 && db->nSavepoint>=0 );
72070         db->nStatement++;
72071         p->iStatement = db->nSavepoint + db->nStatement;
72072       }
72073 
72074       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
72075       if( rc==SQLITE_OK ){
72076         rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
72077       }
72078 
72079       /* Store the current value of the database handles deferred constraint
72080       ** counter. If the statement transaction needs to be rolled back,
72081       ** the value of this counter needs to be restored too.  */
72082       p->nStmtDefCons = db->nDeferredCons;
72083       p->nStmtDefImmCons = db->nDeferredImmCons;
72084     }
72085 
72086     /* Gather the schema version number for checking */
72087     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
72088     iGen = db->aDb[pOp->p1].pSchema->iGeneration;
72089   }else{
72090     iGen = iMeta = 0;
72091   }
72092   assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
72093   if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
72094     sqlite3DbFree(db, p->zErrMsg);
72095     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
72096     /* If the schema-cookie from the database file matches the cookie
72097     ** stored with the in-memory representation of the schema, do
72098     ** not reload the schema from the database file.
72099     **
72100     ** If virtual-tables are in use, this is not just an optimization.
72101     ** Often, v-tables store their data in other SQLite tables, which
72102     ** are queried from within xNext() and other v-table methods using
72103     ** prepared queries. If such a query is out-of-date, we do not want to
72104     ** discard the database schema, as the user code implementing the
72105     ** v-table would have to be ready for the sqlite3_vtab structure itself
72106     ** to be invalidated whenever sqlite3_step() is called from within
72107     ** a v-table method.
72108     */
72109     if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
72110       sqlite3ResetOneSchema(db, pOp->p1);
72111     }
72112     p->expired = 1;
72113     rc = SQLITE_SCHEMA;
72114   }
72115   break;
72116 }
72117 
72118 /* Opcode: ReadCookie P1 P2 P3 * *
72119 **
72120 ** Read cookie number P3 from database P1 and write it into register P2.
72121 ** P3==1 is the schema version.  P3==2 is the database format.
72122 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
72123 ** the main database file and P1==1 is the database file used to store
72124 ** temporary tables.
72125 **
72126 ** There must be a read-lock on the database (either a transaction
72127 ** must be started or there must be an open cursor) before
72128 ** executing this instruction.
72129 */
72130 case OP_ReadCookie: {               /* out2-prerelease */
72131   int iMeta;
72132   int iDb;
72133   int iCookie;
72134 
72135   assert( p->bIsReader );
72136   iDb = pOp->p1;
72137   iCookie = pOp->p3;
72138   assert( pOp->p3<SQLITE_N_BTREE_META );
72139   assert( iDb>=0 && iDb<db->nDb );
72140   assert( db->aDb[iDb].pBt!=0 );
72141   assert( DbMaskTest(p->btreeMask, iDb) );
72142 
72143   sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
72144   pOut->u.i = iMeta;
72145   break;
72146 }
72147 
72148 /* Opcode: SetCookie P1 P2 P3 * *
72149 **
72150 ** Write the content of register P3 (interpreted as an integer)
72151 ** into cookie number P2 of database P1.  P2==1 is the schema version.
72152 ** P2==2 is the database format. P2==3 is the recommended pager cache
72153 ** size, and so forth.  P1==0 is the main database file and P1==1 is the
72154 ** database file used to store temporary tables.
72155 **
72156 ** A transaction must be started before executing this opcode.
72157 */
72158 case OP_SetCookie: {       /* in3 */
72159   Db *pDb;
72160   assert( pOp->p2<SQLITE_N_BTREE_META );
72161   assert( pOp->p1>=0 && pOp->p1<db->nDb );
72162   assert( DbMaskTest(p->btreeMask, pOp->p1) );
72163   assert( p->readOnly==0 );
72164   pDb = &db->aDb[pOp->p1];
72165   assert( pDb->pBt!=0 );
72166   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
72167   pIn3 = &aMem[pOp->p3];
72168   sqlite3VdbeMemIntegerify(pIn3);
72169   /* See note about index shifting on OP_ReadCookie */
72170   rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, (int)pIn3->u.i);
72171   if( pOp->p2==BTREE_SCHEMA_VERSION ){
72172     /* When the schema cookie changes, record the new cookie internally */
72173     pDb->pSchema->schema_cookie = (int)pIn3->u.i;
72174     db->flags |= SQLITE_InternChanges;
72175   }else if( pOp->p2==BTREE_FILE_FORMAT ){
72176     /* Record changes in the file format */
72177     pDb->pSchema->file_format = (u8)pIn3->u.i;
72178   }
72179   if( pOp->p1==1 ){
72180     /* Invalidate all prepared statements whenever the TEMP database
72181     ** schema is changed.  Ticket #1644 */
72182     sqlite3ExpirePreparedStatements(db);
72183     p->expired = 0;
72184   }
72185   break;
72186 }
72187 
72188 /* Opcode: OpenRead P1 P2 P3 P4 P5
72189 ** Synopsis: root=P2 iDb=P3
72190 **
72191 ** Open a read-only cursor for the database table whose root page is
72192 ** P2 in a database file.  The database file is determined by P3.
72193 ** P3==0 means the main database, P3==1 means the database used for
72194 ** temporary tables, and P3>1 means used the corresponding attached
72195 ** database.  Give the new cursor an identifier of P1.  The P1
72196 ** values need not be contiguous but all P1 values should be small integers.
72197 ** It is an error for P1 to be negative.
72198 **
72199 ** If P5!=0 then use the content of register P2 as the root page, not
72200 ** the value of P2 itself.
72201 **
72202 ** There will be a read lock on the database whenever there is an
72203 ** open cursor.  If the database was unlocked prior to this instruction
72204 ** then a read lock is acquired as part of this instruction.  A read
72205 ** lock allows other processes to read the database but prohibits
72206 ** any other process from modifying the database.  The read lock is
72207 ** released when all cursors are closed.  If this instruction attempts
72208 ** to get a read lock but fails, the script terminates with an
72209 ** SQLITE_BUSY error code.
72210 **
72211 ** The P4 value may be either an integer (P4_INT32) or a pointer to
72212 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
72213 ** structure, then said structure defines the content and collating
72214 ** sequence of the index being opened. Otherwise, if P4 is an integer
72215 ** value, it is set to the number of columns in the table.
72216 **
72217 ** See also: OpenWrite, ReopenIdx
72218 */
72219 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
72220 ** Synopsis: root=P2 iDb=P3
72221 **
72222 ** The ReopenIdx opcode works exactly like ReadOpen except that it first
72223 ** checks to see if the cursor on P1 is already open with a root page
72224 ** number of P2 and if it is this opcode becomes a no-op.  In other words,
72225 ** if the cursor is already open, do not reopen it.
72226 **
72227 ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
72228 ** a P4_KEYINFO object.  Furthermore, the P3 value must be the same as
72229 ** every other ReopenIdx or OpenRead for the same cursor number.
72230 **
72231 ** See the OpenRead opcode documentation for additional information.
72232 */
72233 /* Opcode: OpenWrite P1 P2 P3 P4 P5
72234 ** Synopsis: root=P2 iDb=P3
72235 **
72236 ** Open a read/write cursor named P1 on the table or index whose root
72237 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
72238 ** root page.
72239 **
72240 ** The P4 value may be either an integer (P4_INT32) or a pointer to
72241 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
72242 ** structure, then said structure defines the content and collating
72243 ** sequence of the index being opened. Otherwise, if P4 is an integer
72244 ** value, it is set to the number of columns in the table, or to the
72245 ** largest index of any column of the table that is actually used.
72246 **
72247 ** This instruction works just like OpenRead except that it opens the cursor
72248 ** in read/write mode.  For a given table, there can be one or more read-only
72249 ** cursors or a single read/write cursor but not both.
72250 **
72251 ** See also OpenRead.
72252 */
72253 case OP_ReopenIdx: {
72254   VdbeCursor *pCur;
72255 
72256   assert( pOp->p5==0 );
72257   assert( pOp->p4type==P4_KEYINFO );
72258   pCur = p->apCsr[pOp->p1];
72259   if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
72260     assert( pCur->iDb==pOp->p3 );      /* Guaranteed by the code generator */
72261     break;
72262   }
72263   /* If the cursor is not currently open or is open on a different
72264   ** index, then fall through into OP_OpenRead to force a reopen */
72265 }
72266 case OP_OpenRead:
72267 case OP_OpenWrite: {
72268   int nField;
72269   KeyInfo *pKeyInfo;
72270   int p2;
72271   int iDb;
72272   int wrFlag;
72273   Btree *pX;
72274   VdbeCursor *pCur;
72275   Db *pDb;
72276 
72277   assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
72278   assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
72279   assert( p->bIsReader );
72280   assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
72281           || p->readOnly==0 );
72282 
72283   if( p->expired ){
72284     rc = SQLITE_ABORT_ROLLBACK;
72285     break;
72286   }
72287 
72288   nField = 0;
72289   pKeyInfo = 0;
72290   p2 = pOp->p2;
72291   iDb = pOp->p3;
72292   assert( iDb>=0 && iDb<db->nDb );
72293   assert( DbMaskTest(p->btreeMask, iDb) );
72294   pDb = &db->aDb[iDb];
72295   pX = pDb->pBt;
72296   assert( pX!=0 );
72297   if( pOp->opcode==OP_OpenWrite ){
72298     wrFlag = 1;
72299     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
72300     if( pDb->pSchema->file_format < p->minWriteFileFormat ){
72301       p->minWriteFileFormat = pDb->pSchema->file_format;
72302     }
72303   }else{
72304     wrFlag = 0;
72305   }
72306   if( pOp->p5 & OPFLAG_P2ISREG ){
72307     assert( p2>0 );
72308     assert( p2<=(p->nMem-p->nCursor) );
72309     pIn2 = &aMem[p2];
72310     assert( memIsValid(pIn2) );
72311     assert( (pIn2->flags & MEM_Int)!=0 );
72312     sqlite3VdbeMemIntegerify(pIn2);
72313     p2 = (int)pIn2->u.i;
72314     /* The p2 value always comes from a prior OP_CreateTable opcode and
72315     ** that opcode will always set the p2 value to 2 or more or else fail.
72316     ** If there were a failure, the prepared statement would have halted
72317     ** before reaching this instruction. */
72318     if( NEVER(p2<2) ) {
72319       rc = SQLITE_CORRUPT_BKPT;
72320       goto abort_due_to_error;
72321     }
72322   }
72323   if( pOp->p4type==P4_KEYINFO ){
72324     pKeyInfo = pOp->p4.pKeyInfo;
72325     assert( pKeyInfo->enc==ENC(db) );
72326     assert( pKeyInfo->db==db );
72327     nField = pKeyInfo->nField+pKeyInfo->nXField;
72328   }else if( pOp->p4type==P4_INT32 ){
72329     nField = pOp->p4.i;
72330   }
72331   assert( pOp->p1>=0 );
72332   assert( nField>=0 );
72333   testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */
72334   pCur = allocateCursor(p, pOp->p1, nField, iDb, 1);
72335   if( pCur==0 ) goto no_mem;
72336   pCur->nullRow = 1;
72337   pCur->isOrdered = 1;
72338   pCur->pgnoRoot = p2;
72339   rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor);
72340   pCur->pKeyInfo = pKeyInfo;
72341   assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
72342   sqlite3BtreeCursorHints(pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
72343 
72344   /* Set the VdbeCursor.isTable variable. Previous versions of
72345   ** SQLite used to check if the root-page flags were sane at this point
72346   ** and report database corruption if they were not, but this check has
72347   ** since moved into the btree layer.  */
72348   pCur->isTable = pOp->p4type!=P4_KEYINFO;
72349   break;
72350 }
72351 
72352 /* Opcode: OpenEphemeral P1 P2 * P4 P5
72353 ** Synopsis: nColumn=P2
72354 **
72355 ** Open a new cursor P1 to a transient table.
72356 ** The cursor is always opened read/write even if
72357 ** the main database is read-only.  The ephemeral
72358 ** table is deleted automatically when the cursor is closed.
72359 **
72360 ** P2 is the number of columns in the ephemeral table.
72361 ** The cursor points to a BTree table if P4==0 and to a BTree index
72362 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
72363 ** that defines the format of keys in the index.
72364 **
72365 ** The P5 parameter can be a mask of the BTREE_* flags defined
72366 ** in btree.h.  These flags control aspects of the operation of
72367 ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
72368 ** added automatically.
72369 */
72370 /* Opcode: OpenAutoindex P1 P2 * P4 *
72371 ** Synopsis: nColumn=P2
72372 **
72373 ** This opcode works the same as OP_OpenEphemeral.  It has a
72374 ** different name to distinguish its use.  Tables created using
72375 ** by this opcode will be used for automatically created transient
72376 ** indices in joins.
72377 */
72378 case OP_OpenAutoindex:
72379 case OP_OpenEphemeral: {
72380   VdbeCursor *pCx;
72381   KeyInfo *pKeyInfo;
72382 
72383   static const int vfsFlags =
72384       SQLITE_OPEN_READWRITE |
72385       SQLITE_OPEN_CREATE |
72386       SQLITE_OPEN_EXCLUSIVE |
72387       SQLITE_OPEN_DELETEONCLOSE |
72388       SQLITE_OPEN_TRANSIENT_DB;
72389   assert( pOp->p1>=0 );
72390   assert( pOp->p2>=0 );
72391   pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
72392   if( pCx==0 ) goto no_mem;
72393   pCx->nullRow = 1;
72394   pCx->isEphemeral = 1;
72395   rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
72396                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
72397   if( rc==SQLITE_OK ){
72398     rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
72399   }
72400   if( rc==SQLITE_OK ){
72401     /* If a transient index is required, create it by calling
72402     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
72403     ** opening it. If a transient table is required, just use the
72404     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
72405     */
72406     if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
72407       int pgno;
72408       assert( pOp->p4type==P4_KEYINFO );
72409       rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
72410       if( rc==SQLITE_OK ){
72411         assert( pgno==MASTER_ROOT+1 );
72412         assert( pKeyInfo->db==db );
72413         assert( pKeyInfo->enc==ENC(db) );
72414         pCx->pKeyInfo = pKeyInfo;
72415         rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, pKeyInfo, pCx->pCursor);
72416       }
72417       pCx->isTable = 0;
72418     }else{
72419       rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
72420       pCx->isTable = 1;
72421     }
72422   }
72423   pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
72424   break;
72425 }
72426 
72427 /* Opcode: SorterOpen P1 P2 P3 P4 *
72428 **
72429 ** This opcode works like OP_OpenEphemeral except that it opens
72430 ** a transient index that is specifically designed to sort large
72431 ** tables using an external merge-sort algorithm.
72432 **
72433 ** If argument P3 is non-zero, then it indicates that the sorter may
72434 ** assume that a stable sort considering the first P3 fields of each
72435 ** key is sufficient to produce the required results.
72436 */
72437 case OP_SorterOpen: {
72438   VdbeCursor *pCx;
72439 
72440   assert( pOp->p1>=0 );
72441   assert( pOp->p2>=0 );
72442   pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
72443   if( pCx==0 ) goto no_mem;
72444   pCx->pKeyInfo = pOp->p4.pKeyInfo;
72445   assert( pCx->pKeyInfo->db==db );
72446   assert( pCx->pKeyInfo->enc==ENC(db) );
72447   rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
72448   break;
72449 }
72450 
72451 /* Opcode: SequenceTest P1 P2 * * *
72452 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
72453 **
72454 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
72455 ** to P2. Regardless of whether or not the jump is taken, increment the
72456 ** the sequence value.
72457 */
72458 case OP_SequenceTest: {
72459   VdbeCursor *pC;
72460   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72461   pC = p->apCsr[pOp->p1];
72462   assert( pC->pSorter );
72463   if( (pC->seqCount++)==0 ){
72464     pc = pOp->p2 - 1;
72465   }
72466   break;
72467 }
72468 
72469 /* Opcode: OpenPseudo P1 P2 P3 * *
72470 ** Synopsis: P3 columns in r[P2]
72471 **
72472 ** Open a new cursor that points to a fake table that contains a single
72473 ** row of data.  The content of that one row is the content of memory
72474 ** register P2.  In other words, cursor P1 becomes an alias for the
72475 ** MEM_Blob content contained in register P2.
72476 **
72477 ** A pseudo-table created by this opcode is used to hold a single
72478 ** row output from the sorter so that the row can be decomposed into
72479 ** individual columns using the OP_Column opcode.  The OP_Column opcode
72480 ** is the only cursor opcode that works with a pseudo-table.
72481 **
72482 ** P3 is the number of fields in the records that will be stored by
72483 ** the pseudo-table.
72484 */
72485 case OP_OpenPseudo: {
72486   VdbeCursor *pCx;
72487 
72488   assert( pOp->p1>=0 );
72489   assert( pOp->p3>=0 );
72490   pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
72491   if( pCx==0 ) goto no_mem;
72492   pCx->nullRow = 1;
72493   pCx->pseudoTableReg = pOp->p2;
72494   pCx->isTable = 1;
72495   assert( pOp->p5==0 );
72496   break;
72497 }
72498 
72499 /* Opcode: Close P1 * * * *
72500 **
72501 ** Close a cursor previously opened as P1.  If P1 is not
72502 ** currently open, this instruction is a no-op.
72503 */
72504 case OP_Close: {
72505   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72506   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
72507   p->apCsr[pOp->p1] = 0;
72508   break;
72509 }
72510 
72511 /* Opcode: SeekGE P1 P2 P3 P4 *
72512 ** Synopsis: key=r[P3@P4]
72513 **
72514 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
72515 ** use the value in register P3 as the key.  If cursor P1 refers
72516 ** to an SQL index, then P3 is the first in an array of P4 registers
72517 ** that are used as an unpacked index key.
72518 **
72519 ** Reposition cursor P1 so that  it points to the smallest entry that
72520 ** is greater than or equal to the key value. If there are no records
72521 ** greater than or equal to the key and P2 is not zero, then jump to P2.
72522 **
72523 ** This opcode leaves the cursor configured to move in forward order,
72524 ** from the beginning toward the end.  In other words, the cursor is
72525 ** configured to use Next, not Prev.
72526 **
72527 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
72528 */
72529 /* Opcode: SeekGT P1 P2 P3 P4 *
72530 ** Synopsis: key=r[P3@P4]
72531 **
72532 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
72533 ** use the value in register P3 as a key. If cursor P1 refers
72534 ** to an SQL index, then P3 is the first in an array of P4 registers
72535 ** that are used as an unpacked index key.
72536 **
72537 ** Reposition cursor P1 so that  it points to the smallest entry that
72538 ** is greater than the key value. If there are no records greater than
72539 ** the key and P2 is not zero, then jump to P2.
72540 **
72541 ** This opcode leaves the cursor configured to move in forward order,
72542 ** from the beginning toward the end.  In other words, the cursor is
72543 ** configured to use Next, not Prev.
72544 **
72545 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
72546 */
72547 /* Opcode: SeekLT P1 P2 P3 P4 *
72548 ** Synopsis: key=r[P3@P4]
72549 **
72550 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
72551 ** use the value in register P3 as a key. If cursor P1 refers
72552 ** to an SQL index, then P3 is the first in an array of P4 registers
72553 ** that are used as an unpacked index key.
72554 **
72555 ** Reposition cursor P1 so that  it points to the largest entry that
72556 ** is less than the key value. If there are no records less than
72557 ** the key and P2 is not zero, then jump to P2.
72558 **
72559 ** This opcode leaves the cursor configured to move in reverse order,
72560 ** from the end toward the beginning.  In other words, the cursor is
72561 ** configured to use Prev, not Next.
72562 **
72563 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
72564 */
72565 /* Opcode: SeekLE P1 P2 P3 P4 *
72566 ** Synopsis: key=r[P3@P4]
72567 **
72568 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
72569 ** use the value in register P3 as a key. If cursor P1 refers
72570 ** to an SQL index, then P3 is the first in an array of P4 registers
72571 ** that are used as an unpacked index key.
72572 **
72573 ** Reposition cursor P1 so that it points to the largest entry that
72574 ** is less than or equal to the key value. If there are no records
72575 ** less than or equal to the key and P2 is not zero, then jump to P2.
72576 **
72577 ** This opcode leaves the cursor configured to move in reverse order,
72578 ** from the end toward the beginning.  In other words, the cursor is
72579 ** configured to use Prev, not Next.
72580 **
72581 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
72582 */
72583 case OP_SeekLT:         /* jump, in3 */
72584 case OP_SeekLE:         /* jump, in3 */
72585 case OP_SeekGE:         /* jump, in3 */
72586 case OP_SeekGT: {       /* jump, in3 */
72587   int res;
72588   int oc;
72589   VdbeCursor *pC;
72590   UnpackedRecord r;
72591   int nField;
72592   i64 iKey;      /* The rowid we are to seek to */
72593 
72594   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72595   assert( pOp->p2!=0 );
72596   pC = p->apCsr[pOp->p1];
72597   assert( pC!=0 );
72598   assert( pC->pseudoTableReg==0 );
72599   assert( OP_SeekLE == OP_SeekLT+1 );
72600   assert( OP_SeekGE == OP_SeekLT+2 );
72601   assert( OP_SeekGT == OP_SeekLT+3 );
72602   assert( pC->isOrdered );
72603   assert( pC->pCursor!=0 );
72604   oc = pOp->opcode;
72605   pC->nullRow = 0;
72606 #ifdef SQLITE_DEBUG
72607   pC->seekOp = pOp->opcode;
72608 #endif
72609   if( pC->isTable ){
72610     /* The input value in P3 might be of any type: integer, real, string,
72611     ** blob, or NULL.  But it needs to be an integer before we can do
72612     ** the seek, so convert it. */
72613     pIn3 = &aMem[pOp->p3];
72614     if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
72615       applyNumericAffinity(pIn3, 0);
72616     }
72617     iKey = sqlite3VdbeIntValue(pIn3);
72618 
72619     /* If the P3 value could not be converted into an integer without
72620     ** loss of information, then special processing is required... */
72621     if( (pIn3->flags & MEM_Int)==0 ){
72622       if( (pIn3->flags & MEM_Real)==0 ){
72623         /* If the P3 value cannot be converted into any kind of a number,
72624         ** then the seek is not possible, so jump to P2 */
72625         pc = pOp->p2 - 1;  VdbeBranchTaken(1,2);
72626         break;
72627       }
72628 
72629       /* If the approximation iKey is larger than the actual real search
72630       ** term, substitute >= for > and < for <=. e.g. if the search term
72631       ** is 4.9 and the integer approximation 5:
72632       **
72633       **        (x >  4.9)    ->     (x >= 5)
72634       **        (x <= 4.9)    ->     (x <  5)
72635       */
72636       if( pIn3->u.r<(double)iKey ){
72637         assert( OP_SeekGE==(OP_SeekGT-1) );
72638         assert( OP_SeekLT==(OP_SeekLE-1) );
72639         assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
72640         if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
72641       }
72642 
72643       /* If the approximation iKey is smaller than the actual real search
72644       ** term, substitute <= for < and > for >=.  */
72645       else if( pIn3->u.r>(double)iKey ){
72646         assert( OP_SeekLE==(OP_SeekLT+1) );
72647         assert( OP_SeekGT==(OP_SeekGE+1) );
72648         assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
72649         if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
72650       }
72651     }
72652     rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
72653     pC->movetoTarget = iKey;  /* Used by OP_Delete */
72654     if( rc!=SQLITE_OK ){
72655       goto abort_due_to_error;
72656     }
72657   }else{
72658     nField = pOp->p4.i;
72659     assert( pOp->p4type==P4_INT32 );
72660     assert( nField>0 );
72661     r.pKeyInfo = pC->pKeyInfo;
72662     r.nField = (u16)nField;
72663 
72664     /* The next line of code computes as follows, only faster:
72665     **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
72666     **     r.default_rc = -1;
72667     **   }else{
72668     **     r.default_rc = +1;
72669     **   }
72670     */
72671     r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
72672     assert( oc!=OP_SeekGT || r.default_rc==-1 );
72673     assert( oc!=OP_SeekLE || r.default_rc==-1 );
72674     assert( oc!=OP_SeekGE || r.default_rc==+1 );
72675     assert( oc!=OP_SeekLT || r.default_rc==+1 );
72676 
72677     r.aMem = &aMem[pOp->p3];
72678 #ifdef SQLITE_DEBUG
72679     { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
72680 #endif
72681     ExpandBlob(r.aMem);
72682     rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
72683     if( rc!=SQLITE_OK ){
72684       goto abort_due_to_error;
72685     }
72686   }
72687   pC->deferredMoveto = 0;
72688   pC->cacheStatus = CACHE_STALE;
72689 #ifdef SQLITE_TEST
72690   sqlite3_search_count++;
72691 #endif
72692   if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
72693     if( res<0 || (res==0 && oc==OP_SeekGT) ){
72694       res = 0;
72695       rc = sqlite3BtreeNext(pC->pCursor, &res);
72696       if( rc!=SQLITE_OK ) goto abort_due_to_error;
72697     }else{
72698       res = 0;
72699     }
72700   }else{
72701     assert( oc==OP_SeekLT || oc==OP_SeekLE );
72702     if( res>0 || (res==0 && oc==OP_SeekLT) ){
72703       res = 0;
72704       rc = sqlite3BtreePrevious(pC->pCursor, &res);
72705       if( rc!=SQLITE_OK ) goto abort_due_to_error;
72706     }else{
72707       /* res might be negative because the table is empty.  Check to
72708       ** see if this is the case.
72709       */
72710       res = sqlite3BtreeEof(pC->pCursor);
72711     }
72712   }
72713   assert( pOp->p2>0 );
72714   VdbeBranchTaken(res!=0,2);
72715   if( res ){
72716     pc = pOp->p2 - 1;
72717   }
72718   break;
72719 }
72720 
72721 /* Opcode: Seek P1 P2 * * *
72722 ** Synopsis:  intkey=r[P2]
72723 **
72724 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
72725 ** for P1 to move so that it points to the rowid given by P2.
72726 **
72727 ** This is actually a deferred seek.  Nothing actually happens until
72728 ** the cursor is used to read a record.  That way, if no reads
72729 ** occur, no unnecessary I/O happens.
72730 */
72731 case OP_Seek: {    /* in2 */
72732   VdbeCursor *pC;
72733 
72734   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72735   pC = p->apCsr[pOp->p1];
72736   assert( pC!=0 );
72737   assert( pC->pCursor!=0 );
72738   assert( pC->isTable );
72739   pC->nullRow = 0;
72740   pIn2 = &aMem[pOp->p2];
72741   pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
72742   pC->deferredMoveto = 1;
72743   break;
72744 }
72745 
72746 
72747 /* Opcode: Found P1 P2 P3 P4 *
72748 ** Synopsis: key=r[P3@P4]
72749 **
72750 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
72751 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
72752 ** record.
72753 **
72754 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
72755 ** is a prefix of any entry in P1 then a jump is made to P2 and
72756 ** P1 is left pointing at the matching entry.
72757 **
72758 ** This operation leaves the cursor in a state where it can be
72759 ** advanced in the forward direction.  The Next instruction will work,
72760 ** but not the Prev instruction.
72761 **
72762 ** See also: NotFound, NoConflict, NotExists. SeekGe
72763 */
72764 /* Opcode: NotFound P1 P2 P3 P4 *
72765 ** Synopsis: key=r[P3@P4]
72766 **
72767 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
72768 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
72769 ** record.
72770 **
72771 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
72772 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
72773 ** does contain an entry whose prefix matches the P3/P4 record then control
72774 ** falls through to the next instruction and P1 is left pointing at the
72775 ** matching entry.
72776 **
72777 ** This operation leaves the cursor in a state where it cannot be
72778 ** advanced in either direction.  In other words, the Next and Prev
72779 ** opcodes do not work after this operation.
72780 **
72781 ** See also: Found, NotExists, NoConflict
72782 */
72783 /* Opcode: NoConflict P1 P2 P3 P4 *
72784 ** Synopsis: key=r[P3@P4]
72785 **
72786 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
72787 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
72788 ** record.
72789 **
72790 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
72791 ** contains any NULL value, jump immediately to P2.  If all terms of the
72792 ** record are not-NULL then a check is done to determine if any row in the
72793 ** P1 index btree has a matching key prefix.  If there are no matches, jump
72794 ** immediately to P2.  If there is a match, fall through and leave the P1
72795 ** cursor pointing to the matching row.
72796 **
72797 ** This opcode is similar to OP_NotFound with the exceptions that the
72798 ** branch is always taken if any part of the search key input is NULL.
72799 **
72800 ** This operation leaves the cursor in a state where it cannot be
72801 ** advanced in either direction.  In other words, the Next and Prev
72802 ** opcodes do not work after this operation.
72803 **
72804 ** See also: NotFound, Found, NotExists
72805 */
72806 case OP_NoConflict:     /* jump, in3 */
72807 case OP_NotFound:       /* jump, in3 */
72808 case OP_Found: {        /* jump, in3 */
72809   int alreadyExists;
72810   int ii;
72811   VdbeCursor *pC;
72812   int res;
72813   char *pFree;
72814   UnpackedRecord *pIdxKey;
72815   UnpackedRecord r;
72816   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
72817 
72818 #ifdef SQLITE_TEST
72819   if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
72820 #endif
72821 
72822   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72823   assert( pOp->p4type==P4_INT32 );
72824   pC = p->apCsr[pOp->p1];
72825   assert( pC!=0 );
72826 #ifdef SQLITE_DEBUG
72827   pC->seekOp = pOp->opcode;
72828 #endif
72829   pIn3 = &aMem[pOp->p3];
72830   assert( pC->pCursor!=0 );
72831   assert( pC->isTable==0 );
72832   pFree = 0;  /* Not needed.  Only used to suppress a compiler warning. */
72833   if( pOp->p4.i>0 ){
72834     r.pKeyInfo = pC->pKeyInfo;
72835     r.nField = (u16)pOp->p4.i;
72836     r.aMem = pIn3;
72837     for(ii=0; ii<r.nField; ii++){
72838       assert( memIsValid(&r.aMem[ii]) );
72839       ExpandBlob(&r.aMem[ii]);
72840 #ifdef SQLITE_DEBUG
72841       if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
72842 #endif
72843     }
72844     pIdxKey = &r;
72845   }else{
72846     pIdxKey = sqlite3VdbeAllocUnpackedRecord(
72847         pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
72848     );
72849     if( pIdxKey==0 ) goto no_mem;
72850     assert( pIn3->flags & MEM_Blob );
72851     assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
72852     sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
72853   }
72854   pIdxKey->default_rc = 0;
72855   if( pOp->opcode==OP_NoConflict ){
72856     /* For the OP_NoConflict opcode, take the jump if any of the
72857     ** input fields are NULL, since any key with a NULL will not
72858     ** conflict */
72859     for(ii=0; ii<r.nField; ii++){
72860       if( r.aMem[ii].flags & MEM_Null ){
72861         pc = pOp->p2 - 1; VdbeBranchTaken(1,2);
72862         break;
72863       }
72864     }
72865   }
72866   rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
72867   if( pOp->p4.i==0 ){
72868     sqlite3DbFree(db, pFree);
72869   }
72870   if( rc!=SQLITE_OK ){
72871     break;
72872   }
72873   pC->seekResult = res;
72874   alreadyExists = (res==0);
72875   pC->nullRow = 1-alreadyExists;
72876   pC->deferredMoveto = 0;
72877   pC->cacheStatus = CACHE_STALE;
72878   if( pOp->opcode==OP_Found ){
72879     VdbeBranchTaken(alreadyExists!=0,2);
72880     if( alreadyExists ) pc = pOp->p2 - 1;
72881   }else{
72882     VdbeBranchTaken(alreadyExists==0,2);
72883     if( !alreadyExists ) pc = pOp->p2 - 1;
72884   }
72885   break;
72886 }
72887 
72888 /* Opcode: NotExists P1 P2 P3 * *
72889 ** Synopsis: intkey=r[P3]
72890 **
72891 ** P1 is the index of a cursor open on an SQL table btree (with integer
72892 ** keys).  P3 is an integer rowid.  If P1 does not contain a record with
72893 ** rowid P3 then jump immediately to P2.  If P1 does contain a record
72894 ** with rowid P3 then leave the cursor pointing at that record and fall
72895 ** through to the next instruction.
72896 **
72897 ** The OP_NotFound opcode performs the same operation on index btrees
72898 ** (with arbitrary multi-value keys).
72899 **
72900 ** This opcode leaves the cursor in a state where it cannot be advanced
72901 ** in either direction.  In other words, the Next and Prev opcodes will
72902 ** not work following this opcode.
72903 **
72904 ** See also: Found, NotFound, NoConflict
72905 */
72906 case OP_NotExists: {        /* jump, in3 */
72907   VdbeCursor *pC;
72908   BtCursor *pCrsr;
72909   int res;
72910   u64 iKey;
72911 
72912   pIn3 = &aMem[pOp->p3];
72913   assert( pIn3->flags & MEM_Int );
72914   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72915   pC = p->apCsr[pOp->p1];
72916   assert( pC!=0 );
72917 #ifdef SQLITE_DEBUG
72918   pC->seekOp = 0;
72919 #endif
72920   assert( pC->isTable );
72921   assert( pC->pseudoTableReg==0 );
72922   pCrsr = pC->pCursor;
72923   assert( pCrsr!=0 );
72924   res = 0;
72925   iKey = pIn3->u.i;
72926   rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
72927   pC->movetoTarget = iKey;  /* Used by OP_Delete */
72928   pC->nullRow = 0;
72929   pC->cacheStatus = CACHE_STALE;
72930   pC->deferredMoveto = 0;
72931   VdbeBranchTaken(res!=0,2);
72932   if( res!=0 ){
72933     pc = pOp->p2 - 1;
72934   }
72935   pC->seekResult = res;
72936   break;
72937 }
72938 
72939 /* Opcode: Sequence P1 P2 * * *
72940 ** Synopsis: r[P2]=cursor[P1].ctr++
72941 **
72942 ** Find the next available sequence number for cursor P1.
72943 ** Write the sequence number into register P2.
72944 ** The sequence number on the cursor is incremented after this
72945 ** instruction.
72946 */
72947 case OP_Sequence: {           /* out2-prerelease */
72948   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72949   assert( p->apCsr[pOp->p1]!=0 );
72950   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
72951   break;
72952 }
72953 
72954 
72955 /* Opcode: NewRowid P1 P2 P3 * *
72956 ** Synopsis: r[P2]=rowid
72957 **
72958 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
72959 ** The record number is not previously used as a key in the database
72960 ** table that cursor P1 points to.  The new record number is written
72961 ** written to register P2.
72962 **
72963 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
72964 ** the largest previously generated record number. No new record numbers are
72965 ** allowed to be less than this value. When this value reaches its maximum,
72966 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
72967 ** generated record number. This P3 mechanism is used to help implement the
72968 ** AUTOINCREMENT feature.
72969 */
72970 case OP_NewRowid: {           /* out2-prerelease */
72971   i64 v;                 /* The new rowid */
72972   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
72973   int res;               /* Result of an sqlite3BtreeLast() */
72974   int cnt;               /* Counter to limit the number of searches */
72975   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
72976   VdbeFrame *pFrame;     /* Root frame of VDBE */
72977 
72978   v = 0;
72979   res = 0;
72980   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72981   pC = p->apCsr[pOp->p1];
72982   assert( pC!=0 );
72983   if( NEVER(pC->pCursor==0) ){
72984     /* The zero initialization above is all that is needed */
72985   }else{
72986     /* The next rowid or record number (different terms for the same
72987     ** thing) is obtained in a two-step algorithm.
72988     **
72989     ** First we attempt to find the largest existing rowid and add one
72990     ** to that.  But if the largest existing rowid is already the maximum
72991     ** positive integer, we have to fall through to the second
72992     ** probabilistic algorithm
72993     **
72994     ** The second algorithm is to select a rowid at random and see if
72995     ** it already exists in the table.  If it does not exist, we have
72996     ** succeeded.  If the random rowid does exist, we select a new one
72997     ** and try again, up to 100 times.
72998     */
72999     assert( pC->isTable );
73000 
73001 #ifdef SQLITE_32BIT_ROWID
73002 #   define MAX_ROWID 0x7fffffff
73003 #else
73004     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
73005     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
73006     ** to provide the constant while making all compilers happy.
73007     */
73008 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
73009 #endif
73010 
73011     if( !pC->useRandomRowid ){
73012       rc = sqlite3BtreeLast(pC->pCursor, &res);
73013       if( rc!=SQLITE_OK ){
73014         goto abort_due_to_error;
73015       }
73016       if( res ){
73017         v = 1;   /* IMP: R-61914-48074 */
73018       }else{
73019         assert( sqlite3BtreeCursorIsValid(pC->pCursor) );
73020         rc = sqlite3BtreeKeySize(pC->pCursor, &v);
73021         assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
73022         if( v>=MAX_ROWID ){
73023           pC->useRandomRowid = 1;
73024         }else{
73025           v++;   /* IMP: R-29538-34987 */
73026         }
73027       }
73028     }
73029 
73030 #ifndef SQLITE_OMIT_AUTOINCREMENT
73031     if( pOp->p3 ){
73032       /* Assert that P3 is a valid memory cell. */
73033       assert( pOp->p3>0 );
73034       if( p->pFrame ){
73035         for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
73036         /* Assert that P3 is a valid memory cell. */
73037         assert( pOp->p3<=pFrame->nMem );
73038         pMem = &pFrame->aMem[pOp->p3];
73039       }else{
73040         /* Assert that P3 is a valid memory cell. */
73041         assert( pOp->p3<=(p->nMem-p->nCursor) );
73042         pMem = &aMem[pOp->p3];
73043         memAboutToChange(p, pMem);
73044       }
73045       assert( memIsValid(pMem) );
73046 
73047       REGISTER_TRACE(pOp->p3, pMem);
73048       sqlite3VdbeMemIntegerify(pMem);
73049       assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
73050       if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
73051         rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
73052         goto abort_due_to_error;
73053       }
73054       if( v<pMem->u.i+1 ){
73055         v = pMem->u.i + 1;
73056       }
73057       pMem->u.i = v;
73058     }
73059 #endif
73060     if( pC->useRandomRowid ){
73061       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
73062       ** largest possible integer (9223372036854775807) then the database
73063       ** engine starts picking positive candidate ROWIDs at random until
73064       ** it finds one that is not previously used. */
73065       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
73066                              ** an AUTOINCREMENT table. */
73067       cnt = 0;
73068       do{
73069         sqlite3_randomness(sizeof(v), &v);
73070         v &= (MAX_ROWID>>1); v++;  /* Ensure that v is greater than zero */
73071       }while(  ((rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v,
73072                                                  0, &res))==SQLITE_OK)
73073             && (res==0)
73074             && (++cnt<100));
73075       if( rc==SQLITE_OK && res==0 ){
73076         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
73077         goto abort_due_to_error;
73078       }
73079       assert( v>0 );  /* EV: R-40812-03570 */
73080     }
73081     pC->deferredMoveto = 0;
73082     pC->cacheStatus = CACHE_STALE;
73083   }
73084   pOut->u.i = v;
73085   break;
73086 }
73087 
73088 /* Opcode: Insert P1 P2 P3 P4 P5
73089 ** Synopsis: intkey=r[P3] data=r[P2]
73090 **
73091 ** Write an entry into the table of cursor P1.  A new entry is
73092 ** created if it doesn't already exist or the data for an existing
73093 ** entry is overwritten.  The data is the value MEM_Blob stored in register
73094 ** number P2. The key is stored in register P3. The key must
73095 ** be a MEM_Int.
73096 **
73097 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
73098 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
73099 ** then rowid is stored for subsequent return by the
73100 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
73101 **
73102 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
73103 ** the last seek operation (OP_NotExists) was a success, then this
73104 ** operation will not attempt to find the appropriate row before doing
73105 ** the insert but will instead overwrite the row that the cursor is
73106 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
73107 ** has already positioned the cursor correctly.  This is an optimization
73108 ** that boosts performance by avoiding redundant seeks.
73109 **
73110 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
73111 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
73112 ** is part of an INSERT operation.  The difference is only important to
73113 ** the update hook.
73114 **
73115 ** Parameter P4 may point to a string containing the table-name, or
73116 ** may be NULL. If it is not NULL, then the update-hook
73117 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
73118 **
73119 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
73120 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
73121 ** and register P2 becomes ephemeral.  If the cursor is changed, the
73122 ** value of register P2 will then change.  Make sure this does not
73123 ** cause any problems.)
73124 **
73125 ** This instruction only works on tables.  The equivalent instruction
73126 ** for indices is OP_IdxInsert.
73127 */
73128 /* Opcode: InsertInt P1 P2 P3 P4 P5
73129 ** Synopsis:  intkey=P3 data=r[P2]
73130 **
73131 ** This works exactly like OP_Insert except that the key is the
73132 ** integer value P3, not the value of the integer stored in register P3.
73133 */
73134 case OP_Insert:
73135 case OP_InsertInt: {
73136   Mem *pData;       /* MEM cell holding data for the record to be inserted */
73137   Mem *pKey;        /* MEM cell holding key  for the record */
73138   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
73139   VdbeCursor *pC;   /* Cursor to table into which insert is written */
73140   int nZero;        /* Number of zero-bytes to append */
73141   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
73142   const char *zDb;  /* database name - used by the update hook */
73143   const char *zTbl; /* Table name - used by the opdate hook */
73144   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
73145 
73146   pData = &aMem[pOp->p2];
73147   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73148   assert( memIsValid(pData) );
73149   pC = p->apCsr[pOp->p1];
73150   assert( pC!=0 );
73151   assert( pC->pCursor!=0 );
73152   assert( pC->pseudoTableReg==0 );
73153   assert( pC->isTable );
73154   REGISTER_TRACE(pOp->p2, pData);
73155 
73156   if( pOp->opcode==OP_Insert ){
73157     pKey = &aMem[pOp->p3];
73158     assert( pKey->flags & MEM_Int );
73159     assert( memIsValid(pKey) );
73160     REGISTER_TRACE(pOp->p3, pKey);
73161     iKey = pKey->u.i;
73162   }else{
73163     assert( pOp->opcode==OP_InsertInt );
73164     iKey = pOp->p3;
73165   }
73166 
73167   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
73168   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
73169   if( pData->flags & MEM_Null ){
73170     pData->z = 0;
73171     pData->n = 0;
73172   }else{
73173     assert( pData->flags & (MEM_Blob|MEM_Str) );
73174   }
73175   seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
73176   if( pData->flags & MEM_Zero ){
73177     nZero = pData->u.nZero;
73178   }else{
73179     nZero = 0;
73180   }
73181   rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
73182                           pData->z, pData->n, nZero,
73183                           (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
73184   );
73185   pC->deferredMoveto = 0;
73186   pC->cacheStatus = CACHE_STALE;
73187 
73188   /* Invoke the update-hook if required. */
73189   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
73190     zDb = db->aDb[pC->iDb].zName;
73191     zTbl = pOp->p4.z;
73192     op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
73193     assert( pC->isTable );
73194     db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
73195     assert( pC->iDb>=0 );
73196   }
73197   break;
73198 }
73199 
73200 /* Opcode: Delete P1 P2 * P4 *
73201 **
73202 ** Delete the record at which the P1 cursor is currently pointing.
73203 **
73204 ** The cursor will be left pointing at either the next or the previous
73205 ** record in the table. If it is left pointing at the next record, then
73206 ** the next Next instruction will be a no-op.  Hence it is OK to delete
73207 ** a record from within a Next loop.
73208 **
73209 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
73210 ** incremented (otherwise not).
73211 **
73212 ** P1 must not be pseudo-table.  It has to be a real table with
73213 ** multiple rows.
73214 **
73215 ** If P4 is not NULL, then it is the name of the table that P1 is
73216 ** pointing to.  The update hook will be invoked, if it exists.
73217 ** If P4 is not NULL then the P1 cursor must have been positioned
73218 ** using OP_NotFound prior to invoking this opcode.
73219 */
73220 case OP_Delete: {
73221   VdbeCursor *pC;
73222 
73223   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73224   pC = p->apCsr[pOp->p1];
73225   assert( pC!=0 );
73226   assert( pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
73227   assert( pC->deferredMoveto==0 );
73228 
73229 #ifdef SQLITE_DEBUG
73230   /* The seek operation that positioned the cursor prior to OP_Delete will
73231   ** have also set the pC->movetoTarget field to the rowid of the row that
73232   ** is being deleted */
73233   if( pOp->p4.z && pC->isTable ){
73234     i64 iKey = 0;
73235     sqlite3BtreeKeySize(pC->pCursor, &iKey);
73236     assert( pC->movetoTarget==iKey );
73237   }
73238 #endif
73239 
73240   rc = sqlite3BtreeDelete(pC->pCursor);
73241   pC->cacheStatus = CACHE_STALE;
73242 
73243   /* Invoke the update-hook if required. */
73244   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z && pC->isTable ){
73245     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
73246                         db->aDb[pC->iDb].zName, pOp->p4.z, pC->movetoTarget);
73247     assert( pC->iDb>=0 );
73248   }
73249   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
73250   break;
73251 }
73252 /* Opcode: ResetCount * * * * *
73253 **
73254 ** The value of the change counter is copied to the database handle
73255 ** change counter (returned by subsequent calls to sqlite3_changes()).
73256 ** Then the VMs internal change counter resets to 0.
73257 ** This is used by trigger programs.
73258 */
73259 case OP_ResetCount: {
73260   sqlite3VdbeSetChanges(db, p->nChange);
73261   p->nChange = 0;
73262   break;
73263 }
73264 
73265 /* Opcode: SorterCompare P1 P2 P3 P4
73266 ** Synopsis:  if key(P1)!=trim(r[P3],P4) goto P2
73267 **
73268 ** P1 is a sorter cursor. This instruction compares a prefix of the
73269 ** record blob in register P3 against a prefix of the entry that
73270 ** the sorter cursor currently points to.  Only the first P4 fields
73271 ** of r[P3] and the sorter record are compared.
73272 **
73273 ** If either P3 or the sorter contains a NULL in one of their significant
73274 ** fields (not counting the P4 fields at the end which are ignored) then
73275 ** the comparison is assumed to be equal.
73276 **
73277 ** Fall through to next instruction if the two records compare equal to
73278 ** each other.  Jump to P2 if they are different.
73279 */
73280 case OP_SorterCompare: {
73281   VdbeCursor *pC;
73282   int res;
73283   int nKeyCol;
73284 
73285   pC = p->apCsr[pOp->p1];
73286   assert( isSorter(pC) );
73287   assert( pOp->p4type==P4_INT32 );
73288   pIn3 = &aMem[pOp->p3];
73289   nKeyCol = pOp->p4.i;
73290   res = 0;
73291   rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
73292   VdbeBranchTaken(res!=0,2);
73293   if( res ){
73294     pc = pOp->p2-1;
73295   }
73296   break;
73297 };
73298 
73299 /* Opcode: SorterData P1 P2 P3 * *
73300 ** Synopsis: r[P2]=data
73301 **
73302 ** Write into register P2 the current sorter data for sorter cursor P1.
73303 ** Then clear the column header cache on cursor P3.
73304 **
73305 ** This opcode is normally use to move a record out of the sorter and into
73306 ** a register that is the source for a pseudo-table cursor created using
73307 ** OpenPseudo.  That pseudo-table cursor is the one that is identified by
73308 ** parameter P3.  Clearing the P3 column cache as part of this opcode saves
73309 ** us from having to issue a separate NullRow instruction to clear that cache.
73310 */
73311 case OP_SorterData: {
73312   VdbeCursor *pC;
73313 
73314   pOut = &aMem[pOp->p2];
73315   pC = p->apCsr[pOp->p1];
73316   assert( isSorter(pC) );
73317   rc = sqlite3VdbeSorterRowkey(pC, pOut);
73318   assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
73319   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73320   p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
73321   break;
73322 }
73323 
73324 /* Opcode: RowData P1 P2 * * *
73325 ** Synopsis: r[P2]=data
73326 **
73327 ** Write into register P2 the complete row data for cursor P1.
73328 ** There is no interpretation of the data.
73329 ** It is just copied onto the P2 register exactly as
73330 ** it is found in the database file.
73331 **
73332 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
73333 ** of a real table, not a pseudo-table.
73334 */
73335 /* Opcode: RowKey P1 P2 * * *
73336 ** Synopsis: r[P2]=key
73337 **
73338 ** Write into register P2 the complete row key for cursor P1.
73339 ** There is no interpretation of the data.
73340 ** The key is copied onto the P2 register exactly as
73341 ** it is found in the database file.
73342 **
73343 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
73344 ** of a real table, not a pseudo-table.
73345 */
73346 case OP_RowKey:
73347 case OP_RowData: {
73348   VdbeCursor *pC;
73349   BtCursor *pCrsr;
73350   u32 n;
73351   i64 n64;
73352 
73353   pOut = &aMem[pOp->p2];
73354   memAboutToChange(p, pOut);
73355 
73356   /* Note that RowKey and RowData are really exactly the same instruction */
73357   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73358   pC = p->apCsr[pOp->p1];
73359   assert( isSorter(pC)==0 );
73360   assert( pC->isTable || pOp->opcode!=OP_RowData );
73361   assert( pC->isTable==0 || pOp->opcode==OP_RowData );
73362   assert( pC!=0 );
73363   assert( pC->nullRow==0 );
73364   assert( pC->pseudoTableReg==0 );
73365   assert( pC->pCursor!=0 );
73366   pCrsr = pC->pCursor;
73367 
73368   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
73369   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
73370   ** the cursor.  If this where not the case, on of the following assert()s
73371   ** would fail.  Should this ever change (because of changes in the code
73372   ** generator) then the fix would be to insert a call to
73373   ** sqlite3VdbeCursorMoveto().
73374   */
73375   assert( pC->deferredMoveto==0 );
73376   assert( sqlite3BtreeCursorIsValid(pCrsr) );
73377 #if 0  /* Not required due to the previous to assert() statements */
73378   rc = sqlite3VdbeCursorMoveto(pC);
73379   if( rc!=SQLITE_OK ) goto abort_due_to_error;
73380 #endif
73381 
73382   if( pC->isTable==0 ){
73383     assert( !pC->isTable );
73384     VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &n64);
73385     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
73386     if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
73387       goto too_big;
73388     }
73389     n = (u32)n64;
73390   }else{
73391     VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &n);
73392     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
73393     if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
73394       goto too_big;
73395     }
73396   }
73397   testcase( n==0 );
73398   if( sqlite3VdbeMemClearAndResize(pOut, MAX(n,32)) ){
73399     goto no_mem;
73400   }
73401   pOut->n = n;
73402   MemSetTypeFlag(pOut, MEM_Blob);
73403   if( pC->isTable==0 ){
73404     rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
73405   }else{
73406     rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
73407   }
73408   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
73409   UPDATE_MAX_BLOBSIZE(pOut);
73410   REGISTER_TRACE(pOp->p2, pOut);
73411   break;
73412 }
73413 
73414 /* Opcode: Rowid P1 P2 * * *
73415 ** Synopsis: r[P2]=rowid
73416 **
73417 ** Store in register P2 an integer which is the key of the table entry that
73418 ** P1 is currently point to.
73419 **
73420 ** P1 can be either an ordinary table or a virtual table.  There used to
73421 ** be a separate OP_VRowid opcode for use with virtual tables, but this
73422 ** one opcode now works for both table types.
73423 */
73424 case OP_Rowid: {                 /* out2-prerelease */
73425   VdbeCursor *pC;
73426   i64 v;
73427   sqlite3_vtab *pVtab;
73428   const sqlite3_module *pModule;
73429 
73430   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73431   pC = p->apCsr[pOp->p1];
73432   assert( pC!=0 );
73433   assert( pC->pseudoTableReg==0 || pC->nullRow );
73434   if( pC->nullRow ){
73435     pOut->flags = MEM_Null;
73436     break;
73437   }else if( pC->deferredMoveto ){
73438     v = pC->movetoTarget;
73439 #ifndef SQLITE_OMIT_VIRTUALTABLE
73440   }else if( pC->pVtabCursor ){
73441     pVtab = pC->pVtabCursor->pVtab;
73442     pModule = pVtab->pModule;
73443     assert( pModule->xRowid );
73444     rc = pModule->xRowid(pC->pVtabCursor, &v);
73445     sqlite3VtabImportErrmsg(p, pVtab);
73446 #endif /* SQLITE_OMIT_VIRTUALTABLE */
73447   }else{
73448     assert( pC->pCursor!=0 );
73449     rc = sqlite3VdbeCursorRestore(pC);
73450     if( rc ) goto abort_due_to_error;
73451     if( pC->nullRow ){
73452       pOut->flags = MEM_Null;
73453       break;
73454     }
73455     rc = sqlite3BtreeKeySize(pC->pCursor, &v);
73456     assert( rc==SQLITE_OK );  /* Always so because of CursorRestore() above */
73457   }
73458   pOut->u.i = v;
73459   break;
73460 }
73461 
73462 /* Opcode: NullRow P1 * * * *
73463 **
73464 ** Move the cursor P1 to a null row.  Any OP_Column operations
73465 ** that occur while the cursor is on the null row will always
73466 ** write a NULL.
73467 */
73468 case OP_NullRow: {
73469   VdbeCursor *pC;
73470 
73471   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73472   pC = p->apCsr[pOp->p1];
73473   assert( pC!=0 );
73474   pC->nullRow = 1;
73475   pC->cacheStatus = CACHE_STALE;
73476   if( pC->pCursor ){
73477     sqlite3BtreeClearCursor(pC->pCursor);
73478   }
73479   break;
73480 }
73481 
73482 /* Opcode: Last P1 P2 * * *
73483 **
73484 ** The next use of the Rowid or Column or Prev instruction for P1
73485 ** will refer to the last entry in the database table or index.
73486 ** If the table or index is empty and P2>0, then jump immediately to P2.
73487 ** If P2 is 0 or if the table or index is not empty, fall through
73488 ** to the following instruction.
73489 **
73490 ** This opcode leaves the cursor configured to move in reverse order,
73491 ** from the end toward the beginning.  In other words, the cursor is
73492 ** configured to use Prev, not Next.
73493 */
73494 case OP_Last: {        /* jump */
73495   VdbeCursor *pC;
73496   BtCursor *pCrsr;
73497   int res;
73498 
73499   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73500   pC = p->apCsr[pOp->p1];
73501   assert( pC!=0 );
73502   pCrsr = pC->pCursor;
73503   res = 0;
73504   assert( pCrsr!=0 );
73505   rc = sqlite3BtreeLast(pCrsr, &res);
73506   pC->nullRow = (u8)res;
73507   pC->deferredMoveto = 0;
73508   pC->cacheStatus = CACHE_STALE;
73509 #ifdef SQLITE_DEBUG
73510   pC->seekOp = OP_Last;
73511 #endif
73512   if( pOp->p2>0 ){
73513     VdbeBranchTaken(res!=0,2);
73514     if( res ) pc = pOp->p2 - 1;
73515   }
73516   break;
73517 }
73518 
73519 
73520 /* Opcode: Sort P1 P2 * * *
73521 **
73522 ** This opcode does exactly the same thing as OP_Rewind except that
73523 ** it increments an undocumented global variable used for testing.
73524 **
73525 ** Sorting is accomplished by writing records into a sorting index,
73526 ** then rewinding that index and playing it back from beginning to
73527 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
73528 ** rewinding so that the global variable will be incremented and
73529 ** regression tests can determine whether or not the optimizer is
73530 ** correctly optimizing out sorts.
73531 */
73532 case OP_SorterSort:    /* jump */
73533 case OP_Sort: {        /* jump */
73534 #ifdef SQLITE_TEST
73535   sqlite3_sort_count++;
73536   sqlite3_search_count--;
73537 #endif
73538   p->aCounter[SQLITE_STMTSTATUS_SORT]++;
73539   /* Fall through into OP_Rewind */
73540 }
73541 /* Opcode: Rewind P1 P2 * * *
73542 **
73543 ** The next use of the Rowid or Column or Next instruction for P1
73544 ** will refer to the first entry in the database table or index.
73545 ** If the table or index is empty and P2>0, then jump immediately to P2.
73546 ** If P2 is 0 or if the table or index is not empty, fall through
73547 ** to the following instruction.
73548 **
73549 ** This opcode leaves the cursor configured to move in forward order,
73550 ** from the beginning toward the end.  In other words, the cursor is
73551 ** configured to use Next, not Prev.
73552 */
73553 case OP_Rewind: {        /* jump */
73554   VdbeCursor *pC;
73555   BtCursor *pCrsr;
73556   int res;
73557 
73558   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73559   pC = p->apCsr[pOp->p1];
73560   assert( pC!=0 );
73561   assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
73562   res = 1;
73563 #ifdef SQLITE_DEBUG
73564   pC->seekOp = OP_Rewind;
73565 #endif
73566   if( isSorter(pC) ){
73567     rc = sqlite3VdbeSorterRewind(pC, &res);
73568   }else{
73569     pCrsr = pC->pCursor;
73570     assert( pCrsr );
73571     rc = sqlite3BtreeFirst(pCrsr, &res);
73572     pC->deferredMoveto = 0;
73573     pC->cacheStatus = CACHE_STALE;
73574   }
73575   pC->nullRow = (u8)res;
73576   assert( pOp->p2>0 && pOp->p2<p->nOp );
73577   VdbeBranchTaken(res!=0,2);
73578   if( res ){
73579     pc = pOp->p2 - 1;
73580   }
73581   break;
73582 }
73583 
73584 /* Opcode: Next P1 P2 P3 P4 P5
73585 **
73586 ** Advance cursor P1 so that it points to the next key/data pair in its
73587 ** table or index.  If there are no more key/value pairs then fall through
73588 ** to the following instruction.  But if the cursor advance was successful,
73589 ** jump immediately to P2.
73590 **
73591 ** The Next opcode is only valid following an SeekGT, SeekGE, or
73592 ** OP_Rewind opcode used to position the cursor.  Next is not allowed
73593 ** to follow SeekLT, SeekLE, or OP_Last.
73594 **
73595 ** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
73596 ** been opened prior to this opcode or the program will segfault.
73597 **
73598 ** The P3 value is a hint to the btree implementation. If P3==1, that
73599 ** means P1 is an SQL index and that this instruction could have been
73600 ** omitted if that index had been unique.  P3 is usually 0.  P3 is
73601 ** always either 0 or 1.
73602 **
73603 ** P4 is always of type P4_ADVANCE. The function pointer points to
73604 ** sqlite3BtreeNext().
73605 **
73606 ** If P5 is positive and the jump is taken, then event counter
73607 ** number P5-1 in the prepared statement is incremented.
73608 **
73609 ** See also: Prev, NextIfOpen
73610 */
73611 /* Opcode: NextIfOpen P1 P2 P3 P4 P5
73612 **
73613 ** This opcode works just like Next except that if cursor P1 is not
73614 ** open it behaves a no-op.
73615 */
73616 /* Opcode: Prev P1 P2 P3 P4 P5
73617 **
73618 ** Back up cursor P1 so that it points to the previous key/data pair in its
73619 ** table or index.  If there is no previous key/value pairs then fall through
73620 ** to the following instruction.  But if the cursor backup was successful,
73621 ** jump immediately to P2.
73622 **
73623 **
73624 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
73625 ** OP_Last opcode used to position the cursor.  Prev is not allowed
73626 ** to follow SeekGT, SeekGE, or OP_Rewind.
73627 **
73628 ** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
73629 ** not open then the behavior is undefined.
73630 **
73631 ** The P3 value is a hint to the btree implementation. If P3==1, that
73632 ** means P1 is an SQL index and that this instruction could have been
73633 ** omitted if that index had been unique.  P3 is usually 0.  P3 is
73634 ** always either 0 or 1.
73635 **
73636 ** P4 is always of type P4_ADVANCE. The function pointer points to
73637 ** sqlite3BtreePrevious().
73638 **
73639 ** If P5 is positive and the jump is taken, then event counter
73640 ** number P5-1 in the prepared statement is incremented.
73641 */
73642 /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
73643 **
73644 ** This opcode works just like Prev except that if cursor P1 is not
73645 ** open it behaves a no-op.
73646 */
73647 case OP_SorterNext: {  /* jump */
73648   VdbeCursor *pC;
73649   int res;
73650 
73651   pC = p->apCsr[pOp->p1];
73652   assert( isSorter(pC) );
73653   res = 0;
73654   rc = sqlite3VdbeSorterNext(db, pC, &res);
73655   goto next_tail;
73656 case OP_PrevIfOpen:    /* jump */
73657 case OP_NextIfOpen:    /* jump */
73658   if( p->apCsr[pOp->p1]==0 ) break;
73659   /* Fall through */
73660 case OP_Prev:          /* jump */
73661 case OP_Next:          /* jump */
73662   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73663   assert( pOp->p5<ArraySize(p->aCounter) );
73664   pC = p->apCsr[pOp->p1];
73665   res = pOp->p3;
73666   assert( pC!=0 );
73667   assert( pC->deferredMoveto==0 );
73668   assert( pC->pCursor );
73669   assert( res==0 || (res==1 && pC->isTable==0) );
73670   testcase( res==1 );
73671   assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
73672   assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
73673   assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
73674   assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
73675 
73676   /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
73677   ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
73678   assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
73679        || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
73680        || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
73681   assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
73682        || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
73683        || pC->seekOp==OP_Last );
73684 
73685   rc = pOp->p4.xAdvance(pC->pCursor, &res);
73686 next_tail:
73687   pC->cacheStatus = CACHE_STALE;
73688   VdbeBranchTaken(res==0,2);
73689   if( res==0 ){
73690     pC->nullRow = 0;
73691     pc = pOp->p2 - 1;
73692     p->aCounter[pOp->p5]++;
73693 #ifdef SQLITE_TEST
73694     sqlite3_search_count++;
73695 #endif
73696   }else{
73697     pC->nullRow = 1;
73698   }
73699   goto check_for_interrupt;
73700 }
73701 
73702 /* Opcode: IdxInsert P1 P2 P3 * P5
73703 ** Synopsis: key=r[P2]
73704 **
73705 ** Register P2 holds an SQL index key made using the
73706 ** MakeRecord instructions.  This opcode writes that key
73707 ** into the index P1.  Data for the entry is nil.
73708 **
73709 ** P3 is a flag that provides a hint to the b-tree layer that this
73710 ** insert is likely to be an append.
73711 **
73712 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
73713 ** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
73714 ** then the change counter is unchanged.
73715 **
73716 ** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
73717 ** just done a seek to the spot where the new entry is to be inserted.
73718 ** This flag avoids doing an extra seek.
73719 **
73720 ** This instruction only works for indices.  The equivalent instruction
73721 ** for tables is OP_Insert.
73722 */
73723 case OP_SorterInsert:       /* in2 */
73724 case OP_IdxInsert: {        /* in2 */
73725   VdbeCursor *pC;
73726   BtCursor *pCrsr;
73727   int nKey;
73728   const char *zKey;
73729 
73730   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73731   pC = p->apCsr[pOp->p1];
73732   assert( pC!=0 );
73733   assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
73734   pIn2 = &aMem[pOp->p2];
73735   assert( pIn2->flags & MEM_Blob );
73736   pCrsr = pC->pCursor;
73737   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
73738   assert( pCrsr!=0 );
73739   assert( pC->isTable==0 );
73740   rc = ExpandBlob(pIn2);
73741   if( rc==SQLITE_OK ){
73742     if( isSorter(pC) ){
73743       rc = sqlite3VdbeSorterWrite(pC, pIn2);
73744     }else{
73745       nKey = pIn2->n;
73746       zKey = pIn2->z;
73747       rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3,
73748           ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
73749           );
73750       assert( pC->deferredMoveto==0 );
73751       pC->cacheStatus = CACHE_STALE;
73752     }
73753   }
73754   break;
73755 }
73756 
73757 /* Opcode: IdxDelete P1 P2 P3 * *
73758 ** Synopsis: key=r[P2@P3]
73759 **
73760 ** The content of P3 registers starting at register P2 form
73761 ** an unpacked index key. This opcode removes that entry from the
73762 ** index opened by cursor P1.
73763 */
73764 case OP_IdxDelete: {
73765   VdbeCursor *pC;
73766   BtCursor *pCrsr;
73767   int res;
73768   UnpackedRecord r;
73769 
73770   assert( pOp->p3>0 );
73771   assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
73772   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73773   pC = p->apCsr[pOp->p1];
73774   assert( pC!=0 );
73775   pCrsr = pC->pCursor;
73776   assert( pCrsr!=0 );
73777   assert( pOp->p5==0 );
73778   r.pKeyInfo = pC->pKeyInfo;
73779   r.nField = (u16)pOp->p3;
73780   r.default_rc = 0;
73781   r.aMem = &aMem[pOp->p2];
73782 #ifdef SQLITE_DEBUG
73783   { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
73784 #endif
73785   rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
73786   if( rc==SQLITE_OK && res==0 ){
73787     rc = sqlite3BtreeDelete(pCrsr);
73788   }
73789   assert( pC->deferredMoveto==0 );
73790   pC->cacheStatus = CACHE_STALE;
73791   break;
73792 }
73793 
73794 /* Opcode: IdxRowid P1 P2 * * *
73795 ** Synopsis: r[P2]=rowid
73796 **
73797 ** Write into register P2 an integer which is the last entry in the record at
73798 ** the end of the index key pointed to by cursor P1.  This integer should be
73799 ** the rowid of the table entry to which this index entry points.
73800 **
73801 ** See also: Rowid, MakeRecord.
73802 */
73803 case OP_IdxRowid: {              /* out2-prerelease */
73804   BtCursor *pCrsr;
73805   VdbeCursor *pC;
73806   i64 rowid;
73807 
73808   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73809   pC = p->apCsr[pOp->p1];
73810   assert( pC!=0 );
73811   pCrsr = pC->pCursor;
73812   assert( pCrsr!=0 );
73813   pOut->flags = MEM_Null;
73814   assert( pC->isTable==0 );
73815   assert( pC->deferredMoveto==0 );
73816 
73817   /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
73818   ** out from under the cursor.  That will never happend for an IdxRowid
73819   ** opcode, hence the NEVER() arround the check of the return value.
73820   */
73821   rc = sqlite3VdbeCursorRestore(pC);
73822   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
73823 
73824   if( !pC->nullRow ){
73825     rowid = 0;  /* Not needed.  Only used to silence a warning. */
73826     rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid);
73827     if( rc!=SQLITE_OK ){
73828       goto abort_due_to_error;
73829     }
73830     pOut->u.i = rowid;
73831     pOut->flags = MEM_Int;
73832   }
73833   break;
73834 }
73835 
73836 /* Opcode: IdxGE P1 P2 P3 P4 P5
73837 ** Synopsis: key=r[P3@P4]
73838 **
73839 ** The P4 register values beginning with P3 form an unpacked index
73840 ** key that omits the PRIMARY KEY.  Compare this key value against the index
73841 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
73842 ** fields at the end.
73843 **
73844 ** If the P1 index entry is greater than or equal to the key value
73845 ** then jump to P2.  Otherwise fall through to the next instruction.
73846 */
73847 /* Opcode: IdxGT P1 P2 P3 P4 P5
73848 ** Synopsis: key=r[P3@P4]
73849 **
73850 ** The P4 register values beginning with P3 form an unpacked index
73851 ** key that omits the PRIMARY KEY.  Compare this key value against the index
73852 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
73853 ** fields at the end.
73854 **
73855 ** If the P1 index entry is greater than the key value
73856 ** then jump to P2.  Otherwise fall through to the next instruction.
73857 */
73858 /* Opcode: IdxLT P1 P2 P3 P4 P5
73859 ** Synopsis: key=r[P3@P4]
73860 **
73861 ** The P4 register values beginning with P3 form an unpacked index
73862 ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
73863 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
73864 ** ROWID on the P1 index.
73865 **
73866 ** If the P1 index entry is less than the key value then jump to P2.
73867 ** Otherwise fall through to the next instruction.
73868 */
73869 /* Opcode: IdxLE P1 P2 P3 P4 P5
73870 ** Synopsis: key=r[P3@P4]
73871 **
73872 ** The P4 register values beginning with P3 form an unpacked index
73873 ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
73874 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
73875 ** ROWID on the P1 index.
73876 **
73877 ** If the P1 index entry is less than or equal to the key value then jump
73878 ** to P2. Otherwise fall through to the next instruction.
73879 */
73880 case OP_IdxLE:          /* jump */
73881 case OP_IdxGT:          /* jump */
73882 case OP_IdxLT:          /* jump */
73883 case OP_IdxGE:  {       /* jump */
73884   VdbeCursor *pC;
73885   int res;
73886   UnpackedRecord r;
73887 
73888   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73889   pC = p->apCsr[pOp->p1];
73890   assert( pC!=0 );
73891   assert( pC->isOrdered );
73892   assert( pC->pCursor!=0);
73893   assert( pC->deferredMoveto==0 );
73894   assert( pOp->p5==0 || pOp->p5==1 );
73895   assert( pOp->p4type==P4_INT32 );
73896   r.pKeyInfo = pC->pKeyInfo;
73897   r.nField = (u16)pOp->p4.i;
73898   if( pOp->opcode<OP_IdxLT ){
73899     assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
73900     r.default_rc = -1;
73901   }else{
73902     assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
73903     r.default_rc = 0;
73904   }
73905   r.aMem = &aMem[pOp->p3];
73906 #ifdef SQLITE_DEBUG
73907   { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
73908 #endif
73909   res = 0;  /* Not needed.  Only used to silence a warning. */
73910   rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
73911   assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
73912   if( (pOp->opcode&1)==(OP_IdxLT&1) ){
73913     assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
73914     res = -res;
73915   }else{
73916     assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
73917     res++;
73918   }
73919   VdbeBranchTaken(res>0,2);
73920   if( res>0 ){
73921     pc = pOp->p2 - 1 ;
73922   }
73923   break;
73924 }
73925 
73926 /* Opcode: Destroy P1 P2 P3 * *
73927 **
73928 ** Delete an entire database table or index whose root page in the database
73929 ** file is given by P1.
73930 **
73931 ** The table being destroyed is in the main database file if P3==0.  If
73932 ** P3==1 then the table to be clear is in the auxiliary database file
73933 ** that is used to store tables create using CREATE TEMPORARY TABLE.
73934 **
73935 ** If AUTOVACUUM is enabled then it is possible that another root page
73936 ** might be moved into the newly deleted root page in order to keep all
73937 ** root pages contiguous at the beginning of the database.  The former
73938 ** value of the root page that moved - its value before the move occurred -
73939 ** is stored in register P2.  If no page
73940 ** movement was required (because the table being dropped was already
73941 ** the last one in the database) then a zero is stored in register P2.
73942 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
73943 **
73944 ** See also: Clear
73945 */
73946 case OP_Destroy: {     /* out2-prerelease */
73947   int iMoved;
73948   int iCnt;
73949   Vdbe *pVdbe;
73950   int iDb;
73951 
73952   assert( p->readOnly==0 );
73953 #ifndef SQLITE_OMIT_VIRTUALTABLE
73954   iCnt = 0;
73955   for(pVdbe=db->pVdbe; pVdbe; pVdbe = pVdbe->pNext){
73956     if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->bIsReader
73957      && pVdbe->inVtabMethod<2 && pVdbe->pc>=0
73958     ){
73959       iCnt++;
73960     }
73961   }
73962 #else
73963   iCnt = db->nVdbeRead;
73964 #endif
73965   pOut->flags = MEM_Null;
73966   if( iCnt>1 ){
73967     rc = SQLITE_LOCKED;
73968     p->errorAction = OE_Abort;
73969   }else{
73970     iDb = pOp->p3;
73971     assert( iCnt==1 );
73972     assert( DbMaskTest(p->btreeMask, iDb) );
73973     iMoved = 0;  /* Not needed.  Only to silence a warning. */
73974     rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
73975     pOut->flags = MEM_Int;
73976     pOut->u.i = iMoved;
73977 #ifndef SQLITE_OMIT_AUTOVACUUM
73978     if( rc==SQLITE_OK && iMoved!=0 ){
73979       sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
73980       /* All OP_Destroy operations occur on the same btree */
73981       assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
73982       resetSchemaOnFault = iDb+1;
73983     }
73984 #endif
73985   }
73986   break;
73987 }
73988 
73989 /* Opcode: Clear P1 P2 P3
73990 **
73991 ** Delete all contents of the database table or index whose root page
73992 ** in the database file is given by P1.  But, unlike Destroy, do not
73993 ** remove the table or index from the database file.
73994 **
73995 ** The table being clear is in the main database file if P2==0.  If
73996 ** P2==1 then the table to be clear is in the auxiliary database file
73997 ** that is used to store tables create using CREATE TEMPORARY TABLE.
73998 **
73999 ** If the P3 value is non-zero, then the table referred to must be an
74000 ** intkey table (an SQL table, not an index). In this case the row change
74001 ** count is incremented by the number of rows in the table being cleared.
74002 ** If P3 is greater than zero, then the value stored in register P3 is
74003 ** also incremented by the number of rows in the table being cleared.
74004 **
74005 ** See also: Destroy
74006 */
74007 case OP_Clear: {
74008   int nChange;
74009 
74010   nChange = 0;
74011   assert( p->readOnly==0 );
74012   assert( DbMaskTest(p->btreeMask, pOp->p2) );
74013   rc = sqlite3BtreeClearTable(
74014       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
74015   );
74016   if( pOp->p3 ){
74017     p->nChange += nChange;
74018     if( pOp->p3>0 ){
74019       assert( memIsValid(&aMem[pOp->p3]) );
74020       memAboutToChange(p, &aMem[pOp->p3]);
74021       aMem[pOp->p3].u.i += nChange;
74022     }
74023   }
74024   break;
74025 }
74026 
74027 /* Opcode: ResetSorter P1 * * * *
74028 **
74029 ** Delete all contents from the ephemeral table or sorter
74030 ** that is open on cursor P1.
74031 **
74032 ** This opcode only works for cursors used for sorting and
74033 ** opened with OP_OpenEphemeral or OP_SorterOpen.
74034 */
74035 case OP_ResetSorter: {
74036   VdbeCursor *pC;
74037 
74038   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
74039   pC = p->apCsr[pOp->p1];
74040   assert( pC!=0 );
74041   if( pC->pSorter ){
74042     sqlite3VdbeSorterReset(db, pC->pSorter);
74043   }else{
74044     assert( pC->isEphemeral );
74045     rc = sqlite3BtreeClearTableOfCursor(pC->pCursor);
74046   }
74047   break;
74048 }
74049 
74050 /* Opcode: CreateTable P1 P2 * * *
74051 ** Synopsis: r[P2]=root iDb=P1
74052 **
74053 ** Allocate a new table in the main database file if P1==0 or in the
74054 ** auxiliary database file if P1==1 or in an attached database if
74055 ** P1>1.  Write the root page number of the new table into
74056 ** register P2
74057 **
74058 ** The difference between a table and an index is this:  A table must
74059 ** have a 4-byte integer key and can have arbitrary data.  An index
74060 ** has an arbitrary key but no data.
74061 **
74062 ** See also: CreateIndex
74063 */
74064 /* Opcode: CreateIndex P1 P2 * * *
74065 ** Synopsis: r[P2]=root iDb=P1
74066 **
74067 ** Allocate a new index in the main database file if P1==0 or in the
74068 ** auxiliary database file if P1==1 or in an attached database if
74069 ** P1>1.  Write the root page number of the new table into
74070 ** register P2.
74071 **
74072 ** See documentation on OP_CreateTable for additional information.
74073 */
74074 case OP_CreateIndex:            /* out2-prerelease */
74075 case OP_CreateTable: {          /* out2-prerelease */
74076   int pgno;
74077   int flags;
74078   Db *pDb;
74079 
74080   pgno = 0;
74081   assert( pOp->p1>=0 && pOp->p1<db->nDb );
74082   assert( DbMaskTest(p->btreeMask, pOp->p1) );
74083   assert( p->readOnly==0 );
74084   pDb = &db->aDb[pOp->p1];
74085   assert( pDb->pBt!=0 );
74086   if( pOp->opcode==OP_CreateTable ){
74087     /* flags = BTREE_INTKEY; */
74088     flags = BTREE_INTKEY;
74089   }else{
74090     flags = BTREE_BLOBKEY;
74091   }
74092   rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
74093   pOut->u.i = pgno;
74094   break;
74095 }
74096 
74097 /* Opcode: ParseSchema P1 * * P4 *
74098 **
74099 ** Read and parse all entries from the SQLITE_MASTER table of database P1
74100 ** that match the WHERE clause P4.
74101 **
74102 ** This opcode invokes the parser to create a new virtual machine,
74103 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
74104 */
74105 case OP_ParseSchema: {
74106   int iDb;
74107   const char *zMaster;
74108   char *zSql;
74109   InitData initData;
74110 
74111   /* Any prepared statement that invokes this opcode will hold mutexes
74112   ** on every btree.  This is a prerequisite for invoking
74113   ** sqlite3InitCallback().
74114   */
74115 #ifdef SQLITE_DEBUG
74116   for(iDb=0; iDb<db->nDb; iDb++){
74117     assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
74118   }
74119 #endif
74120 
74121   iDb = pOp->p1;
74122   assert( iDb>=0 && iDb<db->nDb );
74123   assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
74124   /* Used to be a conditional */ {
74125     zMaster = SCHEMA_TABLE(iDb);
74126     initData.db = db;
74127     initData.iDb = pOp->p1;
74128     initData.pzErrMsg = &p->zErrMsg;
74129     zSql = sqlite3MPrintf(db,
74130        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
74131        db->aDb[iDb].zName, zMaster, pOp->p4.z);
74132     if( zSql==0 ){
74133       rc = SQLITE_NOMEM;
74134     }else{
74135       assert( db->init.busy==0 );
74136       db->init.busy = 1;
74137       initData.rc = SQLITE_OK;
74138       assert( !db->mallocFailed );
74139       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
74140       if( rc==SQLITE_OK ) rc = initData.rc;
74141       sqlite3DbFree(db, zSql);
74142       db->init.busy = 0;
74143     }
74144   }
74145   if( rc ) sqlite3ResetAllSchemasOfConnection(db);
74146   if( rc==SQLITE_NOMEM ){
74147     goto no_mem;
74148   }
74149   break;
74150 }
74151 
74152 #if !defined(SQLITE_OMIT_ANALYZE)
74153 /* Opcode: LoadAnalysis P1 * * * *
74154 **
74155 ** Read the sqlite_stat1 table for database P1 and load the content
74156 ** of that table into the internal index hash table.  This will cause
74157 ** the analysis to be used when preparing all subsequent queries.
74158 */
74159 case OP_LoadAnalysis: {
74160   assert( pOp->p1>=0 && pOp->p1<db->nDb );
74161   rc = sqlite3AnalysisLoad(db, pOp->p1);
74162   break;
74163 }
74164 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
74165 
74166 /* Opcode: DropTable P1 * * P4 *
74167 **
74168 ** Remove the internal (in-memory) data structures that describe
74169 ** the table named P4 in database P1.  This is called after a table
74170 ** is dropped from disk (using the Destroy opcode) in order to keep
74171 ** the internal representation of the
74172 ** schema consistent with what is on disk.
74173 */
74174 case OP_DropTable: {
74175   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
74176   break;
74177 }
74178 
74179 /* Opcode: DropIndex P1 * * P4 *
74180 **
74181 ** Remove the internal (in-memory) data structures that describe
74182 ** the index named P4 in database P1.  This is called after an index
74183 ** is dropped from disk (using the Destroy opcode)
74184 ** in order to keep the internal representation of the
74185 ** schema consistent with what is on disk.
74186 */
74187 case OP_DropIndex: {
74188   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
74189   break;
74190 }
74191 
74192 /* Opcode: DropTrigger P1 * * P4 *
74193 **
74194 ** Remove the internal (in-memory) data structures that describe
74195 ** the trigger named P4 in database P1.  This is called after a trigger
74196 ** is dropped from disk (using the Destroy opcode) in order to keep
74197 ** the internal representation of the
74198 ** schema consistent with what is on disk.
74199 */
74200 case OP_DropTrigger: {
74201   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
74202   break;
74203 }
74204 
74205 
74206 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
74207 /* Opcode: IntegrityCk P1 P2 P3 * P5
74208 **
74209 ** Do an analysis of the currently open database.  Store in
74210 ** register P1 the text of an error message describing any problems.
74211 ** If no problems are found, store a NULL in register P1.
74212 **
74213 ** The register P3 contains the maximum number of allowed errors.
74214 ** At most reg(P3) errors will be reported.
74215 ** In other words, the analysis stops as soon as reg(P1) errors are
74216 ** seen.  Reg(P1) is updated with the number of errors remaining.
74217 **
74218 ** The root page numbers of all tables in the database are integer
74219 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
74220 ** total.
74221 **
74222 ** If P5 is not zero, the check is done on the auxiliary database
74223 ** file, not the main database file.
74224 **
74225 ** This opcode is used to implement the integrity_check pragma.
74226 */
74227 case OP_IntegrityCk: {
74228   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
74229   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
74230   int j;          /* Loop counter */
74231   int nErr;       /* Number of errors reported */
74232   char *z;        /* Text of the error report */
74233   Mem *pnErr;     /* Register keeping track of errors remaining */
74234 
74235   assert( p->bIsReader );
74236   nRoot = pOp->p2;
74237   assert( nRoot>0 );
74238   aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
74239   if( aRoot==0 ) goto no_mem;
74240   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
74241   pnErr = &aMem[pOp->p3];
74242   assert( (pnErr->flags & MEM_Int)!=0 );
74243   assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
74244   pIn1 = &aMem[pOp->p1];
74245   for(j=0; j<nRoot; j++){
74246     aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
74247   }
74248   aRoot[j] = 0;
74249   assert( pOp->p5<db->nDb );
74250   assert( DbMaskTest(p->btreeMask, pOp->p5) );
74251   z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
74252                                  (int)pnErr->u.i, &nErr);
74253   sqlite3DbFree(db, aRoot);
74254   pnErr->u.i -= nErr;
74255   sqlite3VdbeMemSetNull(pIn1);
74256   if( nErr==0 ){
74257     assert( z==0 );
74258   }else if( z==0 ){
74259     goto no_mem;
74260   }else{
74261     sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
74262   }
74263   UPDATE_MAX_BLOBSIZE(pIn1);
74264   sqlite3VdbeChangeEncoding(pIn1, encoding);
74265   break;
74266 }
74267 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
74268 
74269 /* Opcode: RowSetAdd P1 P2 * * *
74270 ** Synopsis:  rowset(P1)=r[P2]
74271 **
74272 ** Insert the integer value held by register P2 into a boolean index
74273 ** held in register P1.
74274 **
74275 ** An assertion fails if P2 is not an integer.
74276 */
74277 case OP_RowSetAdd: {       /* in1, in2 */
74278   pIn1 = &aMem[pOp->p1];
74279   pIn2 = &aMem[pOp->p2];
74280   assert( (pIn2->flags & MEM_Int)!=0 );
74281   if( (pIn1->flags & MEM_RowSet)==0 ){
74282     sqlite3VdbeMemSetRowSet(pIn1);
74283     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
74284   }
74285   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
74286   break;
74287 }
74288 
74289 /* Opcode: RowSetRead P1 P2 P3 * *
74290 ** Synopsis:  r[P3]=rowset(P1)
74291 **
74292 ** Extract the smallest value from boolean index P1 and put that value into
74293 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
74294 ** unchanged and jump to instruction P2.
74295 */
74296 case OP_RowSetRead: {       /* jump, in1, out3 */
74297   i64 val;
74298 
74299   pIn1 = &aMem[pOp->p1];
74300   if( (pIn1->flags & MEM_RowSet)==0
74301    || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
74302   ){
74303     /* The boolean index is empty */
74304     sqlite3VdbeMemSetNull(pIn1);
74305     pc = pOp->p2 - 1;
74306     VdbeBranchTaken(1,2);
74307   }else{
74308     /* A value was pulled from the index */
74309     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
74310     VdbeBranchTaken(0,2);
74311   }
74312   goto check_for_interrupt;
74313 }
74314 
74315 /* Opcode: RowSetTest P1 P2 P3 P4
74316 ** Synopsis: if r[P3] in rowset(P1) goto P2
74317 **
74318 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
74319 ** contains a RowSet object and that RowSet object contains
74320 ** the value held in P3, jump to register P2. Otherwise, insert the
74321 ** integer in P3 into the RowSet and continue on to the
74322 ** next opcode.
74323 **
74324 ** The RowSet object is optimized for the case where successive sets
74325 ** of integers, where each set contains no duplicates. Each set
74326 ** of values is identified by a unique P4 value. The first set
74327 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
74328 ** non-negative.  For non-negative values of P4 only the lower 4
74329 ** bits are significant.
74330 **
74331 ** This allows optimizations: (a) when P4==0 there is no need to test
74332 ** the rowset object for P3, as it is guaranteed not to contain it,
74333 ** (b) when P4==-1 there is no need to insert the value, as it will
74334 ** never be tested for, and (c) when a value that is part of set X is
74335 ** inserted, there is no need to search to see if the same value was
74336 ** previously inserted as part of set X (only if it was previously
74337 ** inserted as part of some other set).
74338 */
74339 case OP_RowSetTest: {                     /* jump, in1, in3 */
74340   int iSet;
74341   int exists;
74342 
74343   pIn1 = &aMem[pOp->p1];
74344   pIn3 = &aMem[pOp->p3];
74345   iSet = pOp->p4.i;
74346   assert( pIn3->flags&MEM_Int );
74347 
74348   /* If there is anything other than a rowset object in memory cell P1,
74349   ** delete it now and initialize P1 with an empty rowset
74350   */
74351   if( (pIn1->flags & MEM_RowSet)==0 ){
74352     sqlite3VdbeMemSetRowSet(pIn1);
74353     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
74354   }
74355 
74356   assert( pOp->p4type==P4_INT32 );
74357   assert( iSet==-1 || iSet>=0 );
74358   if( iSet ){
74359     exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
74360     VdbeBranchTaken(exists!=0,2);
74361     if( exists ){
74362       pc = pOp->p2 - 1;
74363       break;
74364     }
74365   }
74366   if( iSet>=0 ){
74367     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
74368   }
74369   break;
74370 }
74371 
74372 
74373 #ifndef SQLITE_OMIT_TRIGGER
74374 
74375 /* Opcode: Program P1 P2 P3 P4 P5
74376 **
74377 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
74378 **
74379 ** P1 contains the address of the memory cell that contains the first memory
74380 ** cell in an array of values used as arguments to the sub-program. P2
74381 ** contains the address to jump to if the sub-program throws an IGNORE
74382 ** exception using the RAISE() function. Register P3 contains the address
74383 ** of a memory cell in this (the parent) VM that is used to allocate the
74384 ** memory required by the sub-vdbe at runtime.
74385 **
74386 ** P4 is a pointer to the VM containing the trigger program.
74387 **
74388 ** If P5 is non-zero, then recursive program invocation is enabled.
74389 */
74390 case OP_Program: {        /* jump */
74391   int nMem;               /* Number of memory registers for sub-program */
74392   int nByte;              /* Bytes of runtime space required for sub-program */
74393   Mem *pRt;               /* Register to allocate runtime space */
74394   Mem *pMem;              /* Used to iterate through memory cells */
74395   Mem *pEnd;              /* Last memory cell in new array */
74396   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
74397   SubProgram *pProgram;   /* Sub-program to execute */
74398   void *t;                /* Token identifying trigger */
74399 
74400   pProgram = pOp->p4.pProgram;
74401   pRt = &aMem[pOp->p3];
74402   assert( pProgram->nOp>0 );
74403 
74404   /* If the p5 flag is clear, then recursive invocation of triggers is
74405   ** disabled for backwards compatibility (p5 is set if this sub-program
74406   ** is really a trigger, not a foreign key action, and the flag set
74407   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
74408   **
74409   ** It is recursive invocation of triggers, at the SQL level, that is
74410   ** disabled. In some cases a single trigger may generate more than one
74411   ** SubProgram (if the trigger may be executed with more than one different
74412   ** ON CONFLICT algorithm). SubProgram structures associated with a
74413   ** single trigger all have the same value for the SubProgram.token
74414   ** variable.  */
74415   if( pOp->p5 ){
74416     t = pProgram->token;
74417     for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
74418     if( pFrame ) break;
74419   }
74420 
74421   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
74422     rc = SQLITE_ERROR;
74423     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
74424     break;
74425   }
74426 
74427   /* Register pRt is used to store the memory required to save the state
74428   ** of the current program, and the memory required at runtime to execute
74429   ** the trigger program. If this trigger has been fired before, then pRt
74430   ** is already allocated. Otherwise, it must be initialized.  */
74431   if( (pRt->flags&MEM_Frame)==0 ){
74432     /* SubProgram.nMem is set to the number of memory cells used by the
74433     ** program stored in SubProgram.aOp. As well as these, one memory
74434     ** cell is required for each cursor used by the program. Set local
74435     ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
74436     */
74437     nMem = pProgram->nMem + pProgram->nCsr;
74438     nByte = ROUND8(sizeof(VdbeFrame))
74439               + nMem * sizeof(Mem)
74440               + pProgram->nCsr * sizeof(VdbeCursor *)
74441               + pProgram->nOnce * sizeof(u8);
74442     pFrame = sqlite3DbMallocZero(db, nByte);
74443     if( !pFrame ){
74444       goto no_mem;
74445     }
74446     sqlite3VdbeMemRelease(pRt);
74447     pRt->flags = MEM_Frame;
74448     pRt->u.pFrame = pFrame;
74449 
74450     pFrame->v = p;
74451     pFrame->nChildMem = nMem;
74452     pFrame->nChildCsr = pProgram->nCsr;
74453     pFrame->pc = pc;
74454     pFrame->aMem = p->aMem;
74455     pFrame->nMem = p->nMem;
74456     pFrame->apCsr = p->apCsr;
74457     pFrame->nCursor = p->nCursor;
74458     pFrame->aOp = p->aOp;
74459     pFrame->nOp = p->nOp;
74460     pFrame->token = pProgram->token;
74461     pFrame->aOnceFlag = p->aOnceFlag;
74462     pFrame->nOnceFlag = p->nOnceFlag;
74463 
74464     pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
74465     for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
74466       pMem->flags = MEM_Undefined;
74467       pMem->db = db;
74468     }
74469   }else{
74470     pFrame = pRt->u.pFrame;
74471     assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem );
74472     assert( pProgram->nCsr==pFrame->nChildCsr );
74473     assert( pc==pFrame->pc );
74474   }
74475 
74476   p->nFrame++;
74477   pFrame->pParent = p->pFrame;
74478   pFrame->lastRowid = lastRowid;
74479   pFrame->nChange = p->nChange;
74480   p->nChange = 0;
74481   p->pFrame = pFrame;
74482   p->aMem = aMem = &VdbeFrameMem(pFrame)[-1];
74483   p->nMem = pFrame->nChildMem;
74484   p->nCursor = (u16)pFrame->nChildCsr;
74485   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
74486   p->aOp = aOp = pProgram->aOp;
74487   p->nOp = pProgram->nOp;
74488   p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
74489   p->nOnceFlag = pProgram->nOnce;
74490   pc = -1;
74491   memset(p->aOnceFlag, 0, p->nOnceFlag);
74492 
74493   break;
74494 }
74495 
74496 /* Opcode: Param P1 P2 * * *
74497 **
74498 ** This opcode is only ever present in sub-programs called via the
74499 ** OP_Program instruction. Copy a value currently stored in a memory
74500 ** cell of the calling (parent) frame to cell P2 in the current frames
74501 ** address space. This is used by trigger programs to access the new.*
74502 ** and old.* values.
74503 **
74504 ** The address of the cell in the parent frame is determined by adding
74505 ** the value of the P1 argument to the value of the P1 argument to the
74506 ** calling OP_Program instruction.
74507 */
74508 case OP_Param: {           /* out2-prerelease */
74509   VdbeFrame *pFrame;
74510   Mem *pIn;
74511   pFrame = p->pFrame;
74512   pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
74513   sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
74514   break;
74515 }
74516 
74517 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
74518 
74519 #ifndef SQLITE_OMIT_FOREIGN_KEY
74520 /* Opcode: FkCounter P1 P2 * * *
74521 ** Synopsis: fkctr[P1]+=P2
74522 **
74523 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
74524 ** If P1 is non-zero, the database constraint counter is incremented
74525 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
74526 ** statement counter is incremented (immediate foreign key constraints).
74527 */
74528 case OP_FkCounter: {
74529   if( db->flags & SQLITE_DeferFKs ){
74530     db->nDeferredImmCons += pOp->p2;
74531   }else if( pOp->p1 ){
74532     db->nDeferredCons += pOp->p2;
74533   }else{
74534     p->nFkConstraint += pOp->p2;
74535   }
74536   break;
74537 }
74538 
74539 /* Opcode: FkIfZero P1 P2 * * *
74540 ** Synopsis: if fkctr[P1]==0 goto P2
74541 **
74542 ** This opcode tests if a foreign key constraint-counter is currently zero.
74543 ** If so, jump to instruction P2. Otherwise, fall through to the next
74544 ** instruction.
74545 **
74546 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
74547 ** is zero (the one that counts deferred constraint violations). If P1 is
74548 ** zero, the jump is taken if the statement constraint-counter is zero
74549 ** (immediate foreign key constraint violations).
74550 */
74551 case OP_FkIfZero: {         /* jump */
74552   if( pOp->p1 ){
74553     VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
74554     if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
74555   }else{
74556     VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
74557     if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
74558   }
74559   break;
74560 }
74561 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
74562 
74563 #ifndef SQLITE_OMIT_AUTOINCREMENT
74564 /* Opcode: MemMax P1 P2 * * *
74565 ** Synopsis: r[P1]=max(r[P1],r[P2])
74566 **
74567 ** P1 is a register in the root frame of this VM (the root frame is
74568 ** different from the current frame if this instruction is being executed
74569 ** within a sub-program). Set the value of register P1 to the maximum of
74570 ** its current value and the value in register P2.
74571 **
74572 ** This instruction throws an error if the memory cell is not initially
74573 ** an integer.
74574 */
74575 case OP_MemMax: {        /* in2 */
74576   VdbeFrame *pFrame;
74577   if( p->pFrame ){
74578     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
74579     pIn1 = &pFrame->aMem[pOp->p1];
74580   }else{
74581     pIn1 = &aMem[pOp->p1];
74582   }
74583   assert( memIsValid(pIn1) );
74584   sqlite3VdbeMemIntegerify(pIn1);
74585   pIn2 = &aMem[pOp->p2];
74586   sqlite3VdbeMemIntegerify(pIn2);
74587   if( pIn1->u.i<pIn2->u.i){
74588     pIn1->u.i = pIn2->u.i;
74589   }
74590   break;
74591 }
74592 #endif /* SQLITE_OMIT_AUTOINCREMENT */
74593 
74594 /* Opcode: IfPos P1 P2 * * *
74595 ** Synopsis: if r[P1]>0 goto P2
74596 **
74597 ** If the value of register P1 is 1 or greater, jump to P2.
74598 **
74599 ** It is illegal to use this instruction on a register that does
74600 ** not contain an integer.  An assertion fault will result if you try.
74601 */
74602 case OP_IfPos: {        /* jump, in1 */
74603   pIn1 = &aMem[pOp->p1];
74604   assert( pIn1->flags&MEM_Int );
74605   VdbeBranchTaken( pIn1->u.i>0, 2);
74606   if( pIn1->u.i>0 ){
74607      pc = pOp->p2 - 1;
74608   }
74609   break;
74610 }
74611 
74612 /* Opcode: IfNeg P1 P2 P3 * *
74613 ** Synopsis: r[P1]+=P3, if r[P1]<0 goto P2
74614 **
74615 ** Register P1 must contain an integer.  Add literal P3 to the value in
74616 ** register P1 then if the value of register P1 is less than zero, jump to P2.
74617 */
74618 case OP_IfNeg: {        /* jump, in1 */
74619   pIn1 = &aMem[pOp->p1];
74620   assert( pIn1->flags&MEM_Int );
74621   pIn1->u.i += pOp->p3;
74622   VdbeBranchTaken(pIn1->u.i<0, 2);
74623   if( pIn1->u.i<0 ){
74624      pc = pOp->p2 - 1;
74625   }
74626   break;
74627 }
74628 
74629 /* Opcode: IfZero P1 P2 P3 * *
74630 ** Synopsis: r[P1]+=P3, if r[P1]==0 goto P2
74631 **
74632 ** The register P1 must contain an integer.  Add literal P3 to the
74633 ** value in register P1.  If the result is exactly 0, jump to P2.
74634 */
74635 case OP_IfZero: {        /* jump, in1 */
74636   pIn1 = &aMem[pOp->p1];
74637   assert( pIn1->flags&MEM_Int );
74638   pIn1->u.i += pOp->p3;
74639   VdbeBranchTaken(pIn1->u.i==0, 2);
74640   if( pIn1->u.i==0 ){
74641      pc = pOp->p2 - 1;
74642   }
74643   break;
74644 }
74645 
74646 /* Opcode: AggStep * P2 P3 P4 P5
74647 ** Synopsis: accum=r[P3] step(r[P2@P5])
74648 **
74649 ** Execute the step function for an aggregate.  The
74650 ** function has P5 arguments.   P4 is a pointer to the FuncDef
74651 ** structure that specifies the function.  Use register
74652 ** P3 as the accumulator.
74653 **
74654 ** The P5 arguments are taken from register P2 and its
74655 ** successors.
74656 */
74657 case OP_AggStep: {
74658   int n;
74659   int i;
74660   Mem *pMem;
74661   Mem *pRec;
74662   Mem t;
74663   sqlite3_context ctx;
74664   sqlite3_value **apVal;
74665 
74666   n = pOp->p5;
74667   assert( n>=0 );
74668   pRec = &aMem[pOp->p2];
74669   apVal = p->apArg;
74670   assert( apVal || n==0 );
74671   for(i=0; i<n; i++, pRec++){
74672     assert( memIsValid(pRec) );
74673     apVal[i] = pRec;
74674     memAboutToChange(p, pRec);
74675   }
74676   ctx.pFunc = pOp->p4.pFunc;
74677   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
74678   ctx.pMem = pMem = &aMem[pOp->p3];
74679   pMem->n++;
74680   sqlite3VdbeMemInit(&t, db, MEM_Null);
74681   ctx.pOut = &t;
74682   ctx.isError = 0;
74683   ctx.pVdbe = p;
74684   ctx.iOp = pc;
74685   ctx.skipFlag = 0;
74686   (ctx.pFunc->xStep)(&ctx, n, apVal); /* IMP: R-24505-23230 */
74687   if( ctx.isError ){
74688     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&t));
74689     rc = ctx.isError;
74690   }
74691   if( ctx.skipFlag ){
74692     assert( pOp[-1].opcode==OP_CollSeq );
74693     i = pOp[-1].p1;
74694     if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
74695   }
74696   sqlite3VdbeMemRelease(&t);
74697   break;
74698 }
74699 
74700 /* Opcode: AggFinal P1 P2 * P4 *
74701 ** Synopsis: accum=r[P1] N=P2
74702 **
74703 ** Execute the finalizer function for an aggregate.  P1 is
74704 ** the memory location that is the accumulator for the aggregate.
74705 **
74706 ** P2 is the number of arguments that the step function takes and
74707 ** P4 is a pointer to the FuncDef for this function.  The P2
74708 ** argument is not used by this opcode.  It is only there to disambiguate
74709 ** functions that can take varying numbers of arguments.  The
74710 ** P4 argument is only needed for the degenerate case where
74711 ** the step function was not previously called.
74712 */
74713 case OP_AggFinal: {
74714   Mem *pMem;
74715   assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
74716   pMem = &aMem[pOp->p1];
74717   assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
74718   rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
74719   if( rc ){
74720     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
74721   }
74722   sqlite3VdbeChangeEncoding(pMem, encoding);
74723   UPDATE_MAX_BLOBSIZE(pMem);
74724   if( sqlite3VdbeMemTooBig(pMem) ){
74725     goto too_big;
74726   }
74727   break;
74728 }
74729 
74730 #ifndef SQLITE_OMIT_WAL
74731 /* Opcode: Checkpoint P1 P2 P3 * *
74732 **
74733 ** Checkpoint database P1. This is a no-op if P1 is not currently in
74734 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
74735 ** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
74736 ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
74737 ** WAL after the checkpoint into mem[P3+1] and the number of pages
74738 ** in the WAL that have been checkpointed after the checkpoint
74739 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
74740 ** mem[P3+2] are initialized to -1.
74741 */
74742 case OP_Checkpoint: {
74743   int i;                          /* Loop counter */
74744   int aRes[3];                    /* Results */
74745   Mem *pMem;                      /* Write results here */
74746 
74747   assert( p->readOnly==0 );
74748   aRes[0] = 0;
74749   aRes[1] = aRes[2] = -1;
74750   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
74751        || pOp->p2==SQLITE_CHECKPOINT_FULL
74752        || pOp->p2==SQLITE_CHECKPOINT_RESTART
74753   );
74754   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
74755   if( rc==SQLITE_BUSY ){
74756     rc = SQLITE_OK;
74757     aRes[0] = 1;
74758   }
74759   for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
74760     sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
74761   }
74762   break;
74763 };
74764 #endif
74765 
74766 #ifndef SQLITE_OMIT_PRAGMA
74767 /* Opcode: JournalMode P1 P2 P3 * *
74768 **
74769 ** Change the journal mode of database P1 to P3. P3 must be one of the
74770 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
74771 ** modes (delete, truncate, persist, off and memory), this is a simple
74772 ** operation. No IO is required.
74773 **
74774 ** If changing into or out of WAL mode the procedure is more complicated.
74775 **
74776 ** Write a string containing the final journal-mode to register P2.
74777 */
74778 case OP_JournalMode: {    /* out2-prerelease */
74779   Btree *pBt;                     /* Btree to change journal mode of */
74780   Pager *pPager;                  /* Pager associated with pBt */
74781   int eNew;                       /* New journal mode */
74782   int eOld;                       /* The old journal mode */
74783 #ifndef SQLITE_OMIT_WAL
74784   const char *zFilename;          /* Name of database file for pPager */
74785 #endif
74786 
74787   eNew = pOp->p3;
74788   assert( eNew==PAGER_JOURNALMODE_DELETE
74789        || eNew==PAGER_JOURNALMODE_TRUNCATE
74790        || eNew==PAGER_JOURNALMODE_PERSIST
74791        || eNew==PAGER_JOURNALMODE_OFF
74792        || eNew==PAGER_JOURNALMODE_MEMORY
74793        || eNew==PAGER_JOURNALMODE_WAL
74794        || eNew==PAGER_JOURNALMODE_QUERY
74795   );
74796   assert( pOp->p1>=0 && pOp->p1<db->nDb );
74797   assert( p->readOnly==0 );
74798 
74799   pBt = db->aDb[pOp->p1].pBt;
74800   pPager = sqlite3BtreePager(pBt);
74801   eOld = sqlite3PagerGetJournalMode(pPager);
74802   if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
74803   if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
74804 
74805 #ifndef SQLITE_OMIT_WAL
74806   zFilename = sqlite3PagerFilename(pPager, 1);
74807 
74808   /* Do not allow a transition to journal_mode=WAL for a database
74809   ** in temporary storage or if the VFS does not support shared memory
74810   */
74811   if( eNew==PAGER_JOURNALMODE_WAL
74812    && (sqlite3Strlen30(zFilename)==0           /* Temp file */
74813        || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
74814   ){
74815     eNew = eOld;
74816   }
74817 
74818   if( (eNew!=eOld)
74819    && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
74820   ){
74821     if( !db->autoCommit || db->nVdbeRead>1 ){
74822       rc = SQLITE_ERROR;
74823       sqlite3SetString(&p->zErrMsg, db,
74824           "cannot change %s wal mode from within a transaction",
74825           (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
74826       );
74827       break;
74828     }else{
74829 
74830       if( eOld==PAGER_JOURNALMODE_WAL ){
74831         /* If leaving WAL mode, close the log file. If successful, the call
74832         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
74833         ** file. An EXCLUSIVE lock may still be held on the database file
74834         ** after a successful return.
74835         */
74836         rc = sqlite3PagerCloseWal(pPager);
74837         if( rc==SQLITE_OK ){
74838           sqlite3PagerSetJournalMode(pPager, eNew);
74839         }
74840       }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
74841         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
74842         ** as an intermediate */
74843         sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
74844       }
74845 
74846       /* Open a transaction on the database file. Regardless of the journal
74847       ** mode, this transaction always uses a rollback journal.
74848       */
74849       assert( sqlite3BtreeIsInTrans(pBt)==0 );
74850       if( rc==SQLITE_OK ){
74851         rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
74852       }
74853     }
74854   }
74855 #endif /* ifndef SQLITE_OMIT_WAL */
74856 
74857   if( rc ){
74858     eNew = eOld;
74859   }
74860   eNew = sqlite3PagerSetJournalMode(pPager, eNew);
74861 
74862   pOut = &aMem[pOp->p2];
74863   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
74864   pOut->z = (char *)sqlite3JournalModename(eNew);
74865   pOut->n = sqlite3Strlen30(pOut->z);
74866   pOut->enc = SQLITE_UTF8;
74867   sqlite3VdbeChangeEncoding(pOut, encoding);
74868   break;
74869 };
74870 #endif /* SQLITE_OMIT_PRAGMA */
74871 
74872 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
74873 /* Opcode: Vacuum * * * * *
74874 **
74875 ** Vacuum the entire database.  This opcode will cause other virtual
74876 ** machines to be created and run.  It may not be called from within
74877 ** a transaction.
74878 */
74879 case OP_Vacuum: {
74880   assert( p->readOnly==0 );
74881   rc = sqlite3RunVacuum(&p->zErrMsg, db);
74882   break;
74883 }
74884 #endif
74885 
74886 #if !defined(SQLITE_OMIT_AUTOVACUUM)
74887 /* Opcode: IncrVacuum P1 P2 * * *
74888 **
74889 ** Perform a single step of the incremental vacuum procedure on
74890 ** the P1 database. If the vacuum has finished, jump to instruction
74891 ** P2. Otherwise, fall through to the next instruction.
74892 */
74893 case OP_IncrVacuum: {        /* jump */
74894   Btree *pBt;
74895 
74896   assert( pOp->p1>=0 && pOp->p1<db->nDb );
74897   assert( DbMaskTest(p->btreeMask, pOp->p1) );
74898   assert( p->readOnly==0 );
74899   pBt = db->aDb[pOp->p1].pBt;
74900   rc = sqlite3BtreeIncrVacuum(pBt);
74901   VdbeBranchTaken(rc==SQLITE_DONE,2);
74902   if( rc==SQLITE_DONE ){
74903     pc = pOp->p2 - 1;
74904     rc = SQLITE_OK;
74905   }
74906   break;
74907 }
74908 #endif
74909 
74910 /* Opcode: Expire P1 * * * *
74911 **
74912 ** Cause precompiled statements to expire.  When an expired statement
74913 ** is executed using sqlite3_step() it will either automatically
74914 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
74915 ** or it will fail with SQLITE_SCHEMA.
74916 **
74917 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
74918 ** then only the currently executing statement is expired.
74919 */
74920 case OP_Expire: {
74921   if( !pOp->p1 ){
74922     sqlite3ExpirePreparedStatements(db);
74923   }else{
74924     p->expired = 1;
74925   }
74926   break;
74927 }
74928 
74929 #ifndef SQLITE_OMIT_SHARED_CACHE
74930 /* Opcode: TableLock P1 P2 P3 P4 *
74931 ** Synopsis: iDb=P1 root=P2 write=P3
74932 **
74933 ** Obtain a lock on a particular table. This instruction is only used when
74934 ** the shared-cache feature is enabled.
74935 **
74936 ** P1 is the index of the database in sqlite3.aDb[] of the database
74937 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
74938 ** a write lock if P3==1.
74939 **
74940 ** P2 contains the root-page of the table to lock.
74941 **
74942 ** P4 contains a pointer to the name of the table being locked. This is only
74943 ** used to generate an error message if the lock cannot be obtained.
74944 */
74945 case OP_TableLock: {
74946   u8 isWriteLock = (u8)pOp->p3;
74947   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
74948     int p1 = pOp->p1;
74949     assert( p1>=0 && p1<db->nDb );
74950     assert( DbMaskTest(p->btreeMask, p1) );
74951     assert( isWriteLock==0 || isWriteLock==1 );
74952     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
74953     if( (rc&0xFF)==SQLITE_LOCKED ){
74954       const char *z = pOp->p4.z;
74955       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
74956     }
74957   }
74958   break;
74959 }
74960 #endif /* SQLITE_OMIT_SHARED_CACHE */
74961 
74962 #ifndef SQLITE_OMIT_VIRTUALTABLE
74963 /* Opcode: VBegin * * * P4 *
74964 **
74965 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
74966 ** xBegin method for that table.
74967 **
74968 ** Also, whether or not P4 is set, check that this is not being called from
74969 ** within a callback to a virtual table xSync() method. If it is, the error
74970 ** code will be set to SQLITE_LOCKED.
74971 */
74972 case OP_VBegin: {
74973   VTable *pVTab;
74974   pVTab = pOp->p4.pVtab;
74975   rc = sqlite3VtabBegin(db, pVTab);
74976   if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
74977   break;
74978 }
74979 #endif /* SQLITE_OMIT_VIRTUALTABLE */
74980 
74981 #ifndef SQLITE_OMIT_VIRTUALTABLE
74982 /* Opcode: VCreate P1 * * P4 *
74983 **
74984 ** P4 is the name of a virtual table in database P1. Call the xCreate method
74985 ** for that table.
74986 */
74987 case OP_VCreate: {
74988   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
74989   break;
74990 }
74991 #endif /* SQLITE_OMIT_VIRTUALTABLE */
74992 
74993 #ifndef SQLITE_OMIT_VIRTUALTABLE
74994 /* Opcode: VDestroy P1 * * P4 *
74995 **
74996 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
74997 ** of that table.
74998 */
74999 case OP_VDestroy: {
75000   p->inVtabMethod = 2;
75001   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
75002   p->inVtabMethod = 0;
75003   break;
75004 }
75005 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75006 
75007 #ifndef SQLITE_OMIT_VIRTUALTABLE
75008 /* Opcode: VOpen P1 * * P4 *
75009 **
75010 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
75011 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
75012 ** table and stores that cursor in P1.
75013 */
75014 case OP_VOpen: {
75015   VdbeCursor *pCur;
75016   sqlite3_vtab_cursor *pVtabCursor;
75017   sqlite3_vtab *pVtab;
75018   sqlite3_module *pModule;
75019 
75020   assert( p->bIsReader );
75021   pCur = 0;
75022   pVtabCursor = 0;
75023   pVtab = pOp->p4.pVtab->pVtab;
75024   pModule = (sqlite3_module *)pVtab->pModule;
75025   assert(pVtab && pModule);
75026   rc = pModule->xOpen(pVtab, &pVtabCursor);
75027   sqlite3VtabImportErrmsg(p, pVtab);
75028   if( SQLITE_OK==rc ){
75029     /* Initialize sqlite3_vtab_cursor base class */
75030     pVtabCursor->pVtab = pVtab;
75031 
75032     /* Initialize vdbe cursor object */
75033     pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
75034     if( pCur ){
75035       pCur->pVtabCursor = pVtabCursor;
75036     }else{
75037       db->mallocFailed = 1;
75038       pModule->xClose(pVtabCursor);
75039     }
75040   }
75041   break;
75042 }
75043 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75044 
75045 #ifndef SQLITE_OMIT_VIRTUALTABLE
75046 /* Opcode: VFilter P1 P2 P3 P4 *
75047 ** Synopsis: iplan=r[P3] zplan='P4'
75048 **
75049 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
75050 ** the filtered result set is empty.
75051 **
75052 ** P4 is either NULL or a string that was generated by the xBestIndex
75053 ** method of the module.  The interpretation of the P4 string is left
75054 ** to the module implementation.
75055 **
75056 ** This opcode invokes the xFilter method on the virtual table specified
75057 ** by P1.  The integer query plan parameter to xFilter is stored in register
75058 ** P3. Register P3+1 stores the argc parameter to be passed to the
75059 ** xFilter method. Registers P3+2..P3+1+argc are the argc
75060 ** additional parameters which are passed to
75061 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
75062 **
75063 ** A jump is made to P2 if the result set after filtering would be empty.
75064 */
75065 case OP_VFilter: {   /* jump */
75066   int nArg;
75067   int iQuery;
75068   const sqlite3_module *pModule;
75069   Mem *pQuery;
75070   Mem *pArgc;
75071   sqlite3_vtab_cursor *pVtabCursor;
75072   sqlite3_vtab *pVtab;
75073   VdbeCursor *pCur;
75074   int res;
75075   int i;
75076   Mem **apArg;
75077 
75078   pQuery = &aMem[pOp->p3];
75079   pArgc = &pQuery[1];
75080   pCur = p->apCsr[pOp->p1];
75081   assert( memIsValid(pQuery) );
75082   REGISTER_TRACE(pOp->p3, pQuery);
75083   assert( pCur->pVtabCursor );
75084   pVtabCursor = pCur->pVtabCursor;
75085   pVtab = pVtabCursor->pVtab;
75086   pModule = pVtab->pModule;
75087 
75088   /* Grab the index number and argc parameters */
75089   assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
75090   nArg = (int)pArgc->u.i;
75091   iQuery = (int)pQuery->u.i;
75092 
75093   /* Invoke the xFilter method */
75094   {
75095     res = 0;
75096     apArg = p->apArg;
75097     for(i = 0; i<nArg; i++){
75098       apArg[i] = &pArgc[i+1];
75099     }
75100 
75101     p->inVtabMethod = 1;
75102     rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
75103     p->inVtabMethod = 0;
75104     sqlite3VtabImportErrmsg(p, pVtab);
75105     if( rc==SQLITE_OK ){
75106       res = pModule->xEof(pVtabCursor);
75107     }
75108     VdbeBranchTaken(res!=0,2);
75109     if( res ){
75110       pc = pOp->p2 - 1;
75111     }
75112   }
75113   pCur->nullRow = 0;
75114 
75115   break;
75116 }
75117 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75118 
75119 #ifndef SQLITE_OMIT_VIRTUALTABLE
75120 /* Opcode: VColumn P1 P2 P3 * *
75121 ** Synopsis: r[P3]=vcolumn(P2)
75122 **
75123 ** Store the value of the P2-th column of
75124 ** the row of the virtual-table that the
75125 ** P1 cursor is pointing to into register P3.
75126 */
75127 case OP_VColumn: {
75128   sqlite3_vtab *pVtab;
75129   const sqlite3_module *pModule;
75130   Mem *pDest;
75131   sqlite3_context sContext;
75132 
75133   VdbeCursor *pCur = p->apCsr[pOp->p1];
75134   assert( pCur->pVtabCursor );
75135   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
75136   pDest = &aMem[pOp->p3];
75137   memAboutToChange(p, pDest);
75138   if( pCur->nullRow ){
75139     sqlite3VdbeMemSetNull(pDest);
75140     break;
75141   }
75142   pVtab = pCur->pVtabCursor->pVtab;
75143   pModule = pVtab->pModule;
75144   assert( pModule->xColumn );
75145   memset(&sContext, 0, sizeof(sContext));
75146   sContext.pOut = pDest;
75147   MemSetTypeFlag(pDest, MEM_Null);
75148   rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
75149   sqlite3VtabImportErrmsg(p, pVtab);
75150   if( sContext.isError ){
75151     rc = sContext.isError;
75152   }
75153   sqlite3VdbeChangeEncoding(pDest, encoding);
75154   REGISTER_TRACE(pOp->p3, pDest);
75155   UPDATE_MAX_BLOBSIZE(pDest);
75156 
75157   if( sqlite3VdbeMemTooBig(pDest) ){
75158     goto too_big;
75159   }
75160   break;
75161 }
75162 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75163 
75164 #ifndef SQLITE_OMIT_VIRTUALTABLE
75165 /* Opcode: VNext P1 P2 * * *
75166 **
75167 ** Advance virtual table P1 to the next row in its result set and
75168 ** jump to instruction P2.  Or, if the virtual table has reached
75169 ** the end of its result set, then fall through to the next instruction.
75170 */
75171 case OP_VNext: {   /* jump */
75172   sqlite3_vtab *pVtab;
75173   const sqlite3_module *pModule;
75174   int res;
75175   VdbeCursor *pCur;
75176 
75177   res = 0;
75178   pCur = p->apCsr[pOp->p1];
75179   assert( pCur->pVtabCursor );
75180   if( pCur->nullRow ){
75181     break;
75182   }
75183   pVtab = pCur->pVtabCursor->pVtab;
75184   pModule = pVtab->pModule;
75185   assert( pModule->xNext );
75186 
75187   /* Invoke the xNext() method of the module. There is no way for the
75188   ** underlying implementation to return an error if one occurs during
75189   ** xNext(). Instead, if an error occurs, true is returned (indicating that
75190   ** data is available) and the error code returned when xColumn or
75191   ** some other method is next invoked on the save virtual table cursor.
75192   */
75193   p->inVtabMethod = 1;
75194   rc = pModule->xNext(pCur->pVtabCursor);
75195   p->inVtabMethod = 0;
75196   sqlite3VtabImportErrmsg(p, pVtab);
75197   if( rc==SQLITE_OK ){
75198     res = pModule->xEof(pCur->pVtabCursor);
75199   }
75200   VdbeBranchTaken(!res,2);
75201   if( !res ){
75202     /* If there is data, jump to P2 */
75203     pc = pOp->p2 - 1;
75204   }
75205   goto check_for_interrupt;
75206 }
75207 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75208 
75209 #ifndef SQLITE_OMIT_VIRTUALTABLE
75210 /* Opcode: VRename P1 * * P4 *
75211 **
75212 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
75213 ** This opcode invokes the corresponding xRename method. The value
75214 ** in register P1 is passed as the zName argument to the xRename method.
75215 */
75216 case OP_VRename: {
75217   sqlite3_vtab *pVtab;
75218   Mem *pName;
75219 
75220   pVtab = pOp->p4.pVtab->pVtab;
75221   pName = &aMem[pOp->p1];
75222   assert( pVtab->pModule->xRename );
75223   assert( memIsValid(pName) );
75224   assert( p->readOnly==0 );
75225   REGISTER_TRACE(pOp->p1, pName);
75226   assert( pName->flags & MEM_Str );
75227   testcase( pName->enc==SQLITE_UTF8 );
75228   testcase( pName->enc==SQLITE_UTF16BE );
75229   testcase( pName->enc==SQLITE_UTF16LE );
75230   rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
75231   if( rc==SQLITE_OK ){
75232     rc = pVtab->pModule->xRename(pVtab, pName->z);
75233     sqlite3VtabImportErrmsg(p, pVtab);
75234     p->expired = 0;
75235   }
75236   break;
75237 }
75238 #endif
75239 
75240 #ifndef SQLITE_OMIT_VIRTUALTABLE
75241 /* Opcode: VUpdate P1 P2 P3 P4 P5
75242 ** Synopsis: data=r[P3@P2]
75243 **
75244 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
75245 ** This opcode invokes the corresponding xUpdate method. P2 values
75246 ** are contiguous memory cells starting at P3 to pass to the xUpdate
75247 ** invocation. The value in register (P3+P2-1) corresponds to the
75248 ** p2th element of the argv array passed to xUpdate.
75249 **
75250 ** The xUpdate method will do a DELETE or an INSERT or both.
75251 ** The argv[0] element (which corresponds to memory cell P3)
75252 ** is the rowid of a row to delete.  If argv[0] is NULL then no
75253 ** deletion occurs.  The argv[1] element is the rowid of the new
75254 ** row.  This can be NULL to have the virtual table select the new
75255 ** rowid for itself.  The subsequent elements in the array are
75256 ** the values of columns in the new row.
75257 **
75258 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
75259 ** a row to delete.
75260 **
75261 ** P1 is a boolean flag. If it is set to true and the xUpdate call
75262 ** is successful, then the value returned by sqlite3_last_insert_rowid()
75263 ** is set to the value of the rowid for the row just inserted.
75264 **
75265 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
75266 ** apply in the case of a constraint failure on an insert or update.
75267 */
75268 case OP_VUpdate: {
75269   sqlite3_vtab *pVtab;
75270   sqlite3_module *pModule;
75271   int nArg;
75272   int i;
75273   sqlite_int64 rowid;
75274   Mem **apArg;
75275   Mem *pX;
75276 
75277   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
75278        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
75279   );
75280   assert( p->readOnly==0 );
75281   pVtab = pOp->p4.pVtab->pVtab;
75282   pModule = (sqlite3_module *)pVtab->pModule;
75283   nArg = pOp->p2;
75284   assert( pOp->p4type==P4_VTAB );
75285   if( ALWAYS(pModule->xUpdate) ){
75286     u8 vtabOnConflict = db->vtabOnConflict;
75287     apArg = p->apArg;
75288     pX = &aMem[pOp->p3];
75289     for(i=0; i<nArg; i++){
75290       assert( memIsValid(pX) );
75291       memAboutToChange(p, pX);
75292       apArg[i] = pX;
75293       pX++;
75294     }
75295     db->vtabOnConflict = pOp->p5;
75296     rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
75297     db->vtabOnConflict = vtabOnConflict;
75298     sqlite3VtabImportErrmsg(p, pVtab);
75299     if( rc==SQLITE_OK && pOp->p1 ){
75300       assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
75301       db->lastRowid = lastRowid = rowid;
75302     }
75303     if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
75304       if( pOp->p5==OE_Ignore ){
75305         rc = SQLITE_OK;
75306       }else{
75307         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
75308       }
75309     }else{
75310       p->nChange++;
75311     }
75312   }
75313   break;
75314 }
75315 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75316 
75317 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
75318 /* Opcode: Pagecount P1 P2 * * *
75319 **
75320 ** Write the current number of pages in database P1 to memory cell P2.
75321 */
75322 case OP_Pagecount: {            /* out2-prerelease */
75323   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
75324   break;
75325 }
75326 #endif
75327 
75328 
75329 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
75330 /* Opcode: MaxPgcnt P1 P2 P3 * *
75331 **
75332 ** Try to set the maximum page count for database P1 to the value in P3.
75333 ** Do not let the maximum page count fall below the current page count and
75334 ** do not change the maximum page count value if P3==0.
75335 **
75336 ** Store the maximum page count after the change in register P2.
75337 */
75338 case OP_MaxPgcnt: {            /* out2-prerelease */
75339   unsigned int newMax;
75340   Btree *pBt;
75341 
75342   pBt = db->aDb[pOp->p1].pBt;
75343   newMax = 0;
75344   if( pOp->p3 ){
75345     newMax = sqlite3BtreeLastPage(pBt);
75346     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
75347   }
75348   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
75349   break;
75350 }
75351 #endif
75352 
75353 
75354 /* Opcode: Init * P2 * P4 *
75355 ** Synopsis:  Start at P2
75356 **
75357 ** Programs contain a single instance of this opcode as the very first
75358 ** opcode.
75359 **
75360 ** If tracing is enabled (by the sqlite3_trace()) interface, then
75361 ** the UTF-8 string contained in P4 is emitted on the trace callback.
75362 ** Or if P4 is blank, use the string returned by sqlite3_sql().
75363 **
75364 ** If P2 is not zero, jump to instruction P2.
75365 */
75366 case OP_Init: {          /* jump */
75367   char *zTrace;
75368   char *z;
75369 
75370   if( pOp->p2 ){
75371     pc = pOp->p2 - 1;
75372   }
75373 #ifndef SQLITE_OMIT_TRACE
75374   if( db->xTrace
75375    && !p->doingRerun
75376    && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
75377   ){
75378     z = sqlite3VdbeExpandSql(p, zTrace);
75379     db->xTrace(db->pTraceArg, z);
75380     sqlite3DbFree(db, z);
75381   }
75382 #ifdef SQLITE_USE_FCNTL_TRACE
75383   zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
75384   if( zTrace ){
75385     int i;
75386     for(i=0; i<db->nDb; i++){
75387       if( DbMaskTest(p->btreeMask, i)==0 ) continue;
75388       sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
75389     }
75390   }
75391 #endif /* SQLITE_USE_FCNTL_TRACE */
75392 #ifdef SQLITE_DEBUG
75393   if( (db->flags & SQLITE_SqlTrace)!=0
75394    && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
75395   ){
75396     sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
75397   }
75398 #endif /* SQLITE_DEBUG */
75399 #endif /* SQLITE_OMIT_TRACE */
75400   break;
75401 }
75402 
75403 
75404 /* Opcode: Noop * * * * *
75405 **
75406 ** Do nothing.  This instruction is often useful as a jump
75407 ** destination.
75408 */
75409 /*
75410 ** The magic Explain opcode are only inserted when explain==2 (which
75411 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
75412 ** This opcode records information from the optimizer.  It is the
75413 ** the same as a no-op.  This opcodesnever appears in a real VM program.
75414 */
75415 default: {          /* This is really OP_Noop and OP_Explain */
75416   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
75417   break;
75418 }
75419 
75420 /*****************************************************************************
75421 ** The cases of the switch statement above this line should all be indented
75422 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
75423 ** readability.  From this point on down, the normal indentation rules are
75424 ** restored.
75425 *****************************************************************************/
75426     }
75427 
75428 #ifdef VDBE_PROFILE
75429     {
75430       u64 endTime = sqlite3Hwtime();
75431       if( endTime>start ) pOp->cycles += endTime - start;
75432       pOp->cnt++;
75433     }
75434 #endif
75435 
75436     /* The following code adds nothing to the actual functionality
75437     ** of the program.  It is only here for testing and debugging.
75438     ** On the other hand, it does burn CPU cycles every time through
75439     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
75440     */
75441 #ifndef NDEBUG
75442     assert( pc>=-1 && pc<p->nOp );
75443 
75444 #ifdef SQLITE_DEBUG
75445     if( db->flags & SQLITE_VdbeTrace ){
75446       if( rc!=0 ) printf("rc=%d\n",rc);
75447       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
75448         registerTrace(pOp->p2, &aMem[pOp->p2]);
75449       }
75450       if( pOp->opflags & OPFLG_OUT3 ){
75451         registerTrace(pOp->p3, &aMem[pOp->p3]);
75452       }
75453     }
75454 #endif  /* SQLITE_DEBUG */
75455 #endif  /* NDEBUG */
75456   }  /* The end of the for(;;) loop the loops through opcodes */
75457 
75458   /* If we reach this point, it means that execution is finished with
75459   ** an error of some kind.
75460   */
75461 vdbe_error_halt:
75462   assert( rc );
75463   p->rc = rc;
75464   testcase( sqlite3GlobalConfig.xLog!=0 );
75465   sqlite3_log(rc, "statement aborts at %d: [%s] %s",
75466                    pc, p->zSql, p->zErrMsg);
75467   sqlite3VdbeHalt(p);
75468   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
75469   rc = SQLITE_ERROR;
75470   if( resetSchemaOnFault>0 ){
75471     sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
75472   }
75473 
75474   /* This is the only way out of this procedure.  We have to
75475   ** release the mutexes on btrees that were acquired at the
75476   ** top. */
75477 vdbe_return:
75478   db->lastRowid = lastRowid;
75479   testcase( nVmStep>0 );
75480   p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
75481   sqlite3VdbeLeave(p);
75482   return rc;
75483 
75484   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
75485   ** is encountered.
75486   */
75487 too_big:
75488   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
75489   rc = SQLITE_TOOBIG;
75490   goto vdbe_error_halt;
75491 
75492   /* Jump to here if a malloc() fails.
75493   */
75494 no_mem:
75495   db->mallocFailed = 1;
75496   sqlite3SetString(&p->zErrMsg, db, "out of memory");
75497   rc = SQLITE_NOMEM;
75498   goto vdbe_error_halt;
75499 
75500   /* Jump to here for any other kind of fatal error.  The "rc" variable
75501   ** should hold the error number.
75502   */
75503 abort_due_to_error:
75504   assert( p->zErrMsg==0 );
75505   if( db->mallocFailed ) rc = SQLITE_NOMEM;
75506   if( rc!=SQLITE_IOERR_NOMEM ){
75507     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
75508   }
75509   goto vdbe_error_halt;
75510 
75511   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
75512   ** flag.
75513   */
75514 abort_due_to_interrupt:
75515   assert( db->u1.isInterrupted );
75516   rc = SQLITE_INTERRUPT;
75517   p->rc = rc;
75518   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
75519   goto vdbe_error_halt;
75520 }
75521 
75522 
75523 /************** End of vdbe.c ************************************************/
75524 /************** Begin file vdbeblob.c ****************************************/
75525 /*
75526 ** 2007 May 1
75527 **
75528 ** The author disclaims copyright to this source code.  In place of
75529 ** a legal notice, here is a blessing:
75530 **
75531 **    May you do good and not evil.
75532 **    May you find forgiveness for yourself and forgive others.
75533 **    May you share freely, never taking more than you give.
75534 **
75535 *************************************************************************
75536 **
75537 ** This file contains code used to implement incremental BLOB I/O.
75538 */
75539 
75540 
75541 #ifndef SQLITE_OMIT_INCRBLOB
75542 
75543 /*
75544 ** Valid sqlite3_blob* handles point to Incrblob structures.
75545 */
75546 typedef struct Incrblob Incrblob;
75547 struct Incrblob {
75548   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
75549   int nByte;              /* Size of open blob, in bytes */
75550   int iOffset;            /* Byte offset of blob in cursor data */
75551   int iCol;               /* Table column this handle is open on */
75552   BtCursor *pCsr;         /* Cursor pointing at blob row */
75553   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
75554   sqlite3 *db;            /* The associated database */
75555 };
75556 
75557 
75558 /*
75559 ** This function is used by both blob_open() and blob_reopen(). It seeks
75560 ** the b-tree cursor associated with blob handle p to point to row iRow.
75561 ** If successful, SQLITE_OK is returned and subsequent calls to
75562 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
75563 **
75564 ** If an error occurs, or if the specified row does not exist or does not
75565 ** contain a value of type TEXT or BLOB in the column nominated when the
75566 ** blob handle was opened, then an error code is returned and *pzErr may
75567 ** be set to point to a buffer containing an error message. It is the
75568 ** responsibility of the caller to free the error message buffer using
75569 ** sqlite3DbFree().
75570 **
75571 ** If an error does occur, then the b-tree cursor is closed. All subsequent
75572 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
75573 ** immediately return SQLITE_ABORT.
75574 */
75575 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
75576   int rc;                         /* Error code */
75577   char *zErr = 0;                 /* Error message */
75578   Vdbe *v = (Vdbe *)p->pStmt;
75579 
75580   /* Set the value of the SQL statements only variable to integer iRow.
75581   ** This is done directly instead of using sqlite3_bind_int64() to avoid
75582   ** triggering asserts related to mutexes.
75583   */
75584   assert( v->aVar[0].flags&MEM_Int );
75585   v->aVar[0].u.i = iRow;
75586 
75587   rc = sqlite3_step(p->pStmt);
75588   if( rc==SQLITE_ROW ){
75589     VdbeCursor *pC = v->apCsr[0];
75590     u32 type = pC->aType[p->iCol];
75591     if( type<12 ){
75592       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
75593           type==0?"null": type==7?"real": "integer"
75594       );
75595       rc = SQLITE_ERROR;
75596       sqlite3_finalize(p->pStmt);
75597       p->pStmt = 0;
75598     }else{
75599       p->iOffset = pC->aType[p->iCol + pC->nField];
75600       p->nByte = sqlite3VdbeSerialTypeLen(type);
75601       p->pCsr =  pC->pCursor;
75602       sqlite3BtreeIncrblobCursor(p->pCsr);
75603     }
75604   }
75605 
75606   if( rc==SQLITE_ROW ){
75607     rc = SQLITE_OK;
75608   }else if( p->pStmt ){
75609     rc = sqlite3_finalize(p->pStmt);
75610     p->pStmt = 0;
75611     if( rc==SQLITE_OK ){
75612       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
75613       rc = SQLITE_ERROR;
75614     }else{
75615       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
75616     }
75617   }
75618 
75619   assert( rc!=SQLITE_OK || zErr==0 );
75620   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
75621 
75622   *pzErr = zErr;
75623   return rc;
75624 }
75625 
75626 /*
75627 ** Open a blob handle.
75628 */
75629 SQLITE_API int sqlite3_blob_open(
75630   sqlite3* db,            /* The database connection */
75631   const char *zDb,        /* The attached database containing the blob */
75632   const char *zTable,     /* The table containing the blob */
75633   const char *zColumn,    /* The column containing the blob */
75634   sqlite_int64 iRow,      /* The row containing the glob */
75635   int flags,              /* True -> read/write access, false -> read-only */
75636   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
75637 ){
75638   int nAttempt = 0;
75639   int iCol;               /* Index of zColumn in row-record */
75640 
75641   /* This VDBE program seeks a btree cursor to the identified
75642   ** db/table/row entry. The reason for using a vdbe program instead
75643   ** of writing code to use the b-tree layer directly is that the
75644   ** vdbe program will take advantage of the various transaction,
75645   ** locking and error handling infrastructure built into the vdbe.
75646   **
75647   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
75648   ** Code external to the Vdbe then "borrows" the b-tree cursor and
75649   ** uses it to implement the blob_read(), blob_write() and
75650   ** blob_bytes() functions.
75651   **
75652   ** The sqlite3_blob_close() function finalizes the vdbe program,
75653   ** which closes the b-tree cursor and (possibly) commits the
75654   ** transaction.
75655   */
75656   static const int iLn = VDBE_OFFSET_LINENO(4);
75657   static const VdbeOpList openBlob[] = {
75658     /* {OP_Transaction, 0, 0, 0},  // 0: Inserted separately */
75659     {OP_TableLock, 0, 0, 0},       /* 1: Acquire a read or write lock */
75660     /* One of the following two instructions is replaced by an OP_Noop. */
75661     {OP_OpenRead, 0, 0, 0},        /* 2: Open cursor 0 for reading */
75662     {OP_OpenWrite, 0, 0, 0},       /* 3: Open cursor 0 for read/write */
75663     {OP_Variable, 1, 1, 1},        /* 4: Push the rowid to the stack */
75664     {OP_NotExists, 0, 10, 1},      /* 5: Seek the cursor */
75665     {OP_Column, 0, 0, 1},          /* 6  */
75666     {OP_ResultRow, 1, 0, 0},       /* 7  */
75667     {OP_Goto, 0, 4, 0},            /* 8  */
75668     {OP_Close, 0, 0, 0},           /* 9  */
75669     {OP_Halt, 0, 0, 0},            /* 10 */
75670   };
75671 
75672   int rc = SQLITE_OK;
75673   char *zErr = 0;
75674   Table *pTab;
75675   Parse *pParse = 0;
75676   Incrblob *pBlob = 0;
75677 
75678   flags = !!flags;                /* flags = (flags ? 1 : 0); */
75679   *ppBlob = 0;
75680 
75681   sqlite3_mutex_enter(db->mutex);
75682 
75683   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
75684   if( !pBlob ) goto blob_open_out;
75685   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
75686   if( !pParse ) goto blob_open_out;
75687 
75688   do {
75689     memset(pParse, 0, sizeof(Parse));
75690     pParse->db = db;
75691     sqlite3DbFree(db, zErr);
75692     zErr = 0;
75693 
75694     sqlite3BtreeEnterAll(db);
75695     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
75696     if( pTab && IsVirtual(pTab) ){
75697       pTab = 0;
75698       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
75699     }
75700     if( pTab && !HasRowid(pTab) ){
75701       pTab = 0;
75702       sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
75703     }
75704 #ifndef SQLITE_OMIT_VIEW
75705     if( pTab && pTab->pSelect ){
75706       pTab = 0;
75707       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
75708     }
75709 #endif
75710     if( !pTab ){
75711       if( pParse->zErrMsg ){
75712         sqlite3DbFree(db, zErr);
75713         zErr = pParse->zErrMsg;
75714         pParse->zErrMsg = 0;
75715       }
75716       rc = SQLITE_ERROR;
75717       sqlite3BtreeLeaveAll(db);
75718       goto blob_open_out;
75719     }
75720 
75721     /* Now search pTab for the exact column. */
75722     for(iCol=0; iCol<pTab->nCol; iCol++) {
75723       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
75724         break;
75725       }
75726     }
75727     if( iCol==pTab->nCol ){
75728       sqlite3DbFree(db, zErr);
75729       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
75730       rc = SQLITE_ERROR;
75731       sqlite3BtreeLeaveAll(db);
75732       goto blob_open_out;
75733     }
75734 
75735     /* If the value is being opened for writing, check that the
75736     ** column is not indexed, and that it is not part of a foreign key.
75737     ** It is against the rules to open a column to which either of these
75738     ** descriptions applies for writing.  */
75739     if( flags ){
75740       const char *zFault = 0;
75741       Index *pIdx;
75742 #ifndef SQLITE_OMIT_FOREIGN_KEY
75743       if( db->flags&SQLITE_ForeignKeys ){
75744         /* Check that the column is not part of an FK child key definition. It
75745         ** is not necessary to check if it is part of a parent key, as parent
75746         ** key columns must be indexed. The check below will pick up this
75747         ** case.  */
75748         FKey *pFKey;
75749         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
75750           int j;
75751           for(j=0; j<pFKey->nCol; j++){
75752             if( pFKey->aCol[j].iFrom==iCol ){
75753               zFault = "foreign key";
75754             }
75755           }
75756         }
75757       }
75758 #endif
75759       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
75760         int j;
75761         for(j=0; j<pIdx->nKeyCol; j++){
75762           if( pIdx->aiColumn[j]==iCol ){
75763             zFault = "indexed";
75764           }
75765         }
75766       }
75767       if( zFault ){
75768         sqlite3DbFree(db, zErr);
75769         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
75770         rc = SQLITE_ERROR;
75771         sqlite3BtreeLeaveAll(db);
75772         goto blob_open_out;
75773       }
75774     }
75775 
75776     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
75777     assert( pBlob->pStmt || db->mallocFailed );
75778     if( pBlob->pStmt ){
75779       Vdbe *v = (Vdbe *)pBlob->pStmt;
75780       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75781 
75782 
75783       sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags,
75784                            pTab->pSchema->schema_cookie,
75785                            pTab->pSchema->iGeneration);
75786       sqlite3VdbeChangeP5(v, 1);
75787       sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
75788 
75789       /* Make sure a mutex is held on the table to be accessed */
75790       sqlite3VdbeUsesBtree(v, iDb);
75791 
75792       /* Configure the OP_TableLock instruction */
75793 #ifdef SQLITE_OMIT_SHARED_CACHE
75794       sqlite3VdbeChangeToNoop(v, 1);
75795 #else
75796       sqlite3VdbeChangeP1(v, 1, iDb);
75797       sqlite3VdbeChangeP2(v, 1, pTab->tnum);
75798       sqlite3VdbeChangeP3(v, 1, flags);
75799       sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
75800 #endif
75801 
75802       /* Remove either the OP_OpenWrite or OpenRead. Set the P2
75803       ** parameter of the other to pTab->tnum.  */
75804       sqlite3VdbeChangeToNoop(v, 3 - flags);
75805       sqlite3VdbeChangeP2(v, 2 + flags, pTab->tnum);
75806       sqlite3VdbeChangeP3(v, 2 + flags, iDb);
75807 
75808       /* Configure the number of columns. Configure the cursor to
75809       ** think that the table has one more column than it really
75810       ** does. An OP_Column to retrieve this imaginary column will
75811       ** always return an SQL NULL. This is useful because it means
75812       ** we can invoke OP_Column to fill in the vdbe cursors type
75813       ** and offset cache without causing any IO.
75814       */
75815       sqlite3VdbeChangeP4(v, 2+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
75816       sqlite3VdbeChangeP2(v, 6, pTab->nCol);
75817       if( !db->mallocFailed ){
75818         pParse->nVar = 1;
75819         pParse->nMem = 1;
75820         pParse->nTab = 1;
75821         sqlite3VdbeMakeReady(v, pParse);
75822       }
75823     }
75824 
75825     pBlob->flags = flags;
75826     pBlob->iCol = iCol;
75827     pBlob->db = db;
75828     sqlite3BtreeLeaveAll(db);
75829     if( db->mallocFailed ){
75830       goto blob_open_out;
75831     }
75832     sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
75833     rc = blobSeekToRow(pBlob, iRow, &zErr);
75834   } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
75835 
75836 blob_open_out:
75837   if( rc==SQLITE_OK && db->mallocFailed==0 ){
75838     *ppBlob = (sqlite3_blob *)pBlob;
75839   }else{
75840     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
75841     sqlite3DbFree(db, pBlob);
75842   }
75843   sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
75844   sqlite3DbFree(db, zErr);
75845   sqlite3ParserReset(pParse);
75846   sqlite3StackFree(db, pParse);
75847   rc = sqlite3ApiExit(db, rc);
75848   sqlite3_mutex_leave(db->mutex);
75849   return rc;
75850 }
75851 
75852 /*
75853 ** Close a blob handle that was previously created using
75854 ** sqlite3_blob_open().
75855 */
75856 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
75857   Incrblob *p = (Incrblob *)pBlob;
75858   int rc;
75859   sqlite3 *db;
75860 
75861   if( p ){
75862     db = p->db;
75863     sqlite3_mutex_enter(db->mutex);
75864     rc = sqlite3_finalize(p->pStmt);
75865     sqlite3DbFree(db, p);
75866     sqlite3_mutex_leave(db->mutex);
75867   }else{
75868     rc = SQLITE_OK;
75869   }
75870   return rc;
75871 }
75872 
75873 /*
75874 ** Perform a read or write operation on a blob
75875 */
75876 static int blobReadWrite(
75877   sqlite3_blob *pBlob,
75878   void *z,
75879   int n,
75880   int iOffset,
75881   int (*xCall)(BtCursor*, u32, u32, void*)
75882 ){
75883   int rc;
75884   Incrblob *p = (Incrblob *)pBlob;
75885   Vdbe *v;
75886   sqlite3 *db;
75887 
75888   if( p==0 ) return SQLITE_MISUSE_BKPT;
75889   db = p->db;
75890   sqlite3_mutex_enter(db->mutex);
75891   v = (Vdbe*)p->pStmt;
75892 
75893   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
75894     /* Request is out of range. Return a transient error. */
75895     rc = SQLITE_ERROR;
75896     sqlite3Error(db, SQLITE_ERROR);
75897   }else if( v==0 ){
75898     /* If there is no statement handle, then the blob-handle has
75899     ** already been invalidated. Return SQLITE_ABORT in this case.
75900     */
75901     rc = SQLITE_ABORT;
75902   }else{
75903     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
75904     ** returned, clean-up the statement handle.
75905     */
75906     assert( db == v->db );
75907     sqlite3BtreeEnterCursor(p->pCsr);
75908     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
75909     sqlite3BtreeLeaveCursor(p->pCsr);
75910     if( rc==SQLITE_ABORT ){
75911       sqlite3VdbeFinalize(v);
75912       p->pStmt = 0;
75913     }else{
75914       db->errCode = rc;
75915       v->rc = rc;
75916     }
75917   }
75918   rc = sqlite3ApiExit(db, rc);
75919   sqlite3_mutex_leave(db->mutex);
75920   return rc;
75921 }
75922 
75923 /*
75924 ** Read data from a blob handle.
75925 */
75926 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
75927   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
75928 }
75929 
75930 /*
75931 ** Write data to a blob handle.
75932 */
75933 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
75934   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
75935 }
75936 
75937 /*
75938 ** Query a blob handle for the size of the data.
75939 **
75940 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
75941 ** so no mutex is required for access.
75942 */
75943 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
75944   Incrblob *p = (Incrblob *)pBlob;
75945   return (p && p->pStmt) ? p->nByte : 0;
75946 }
75947 
75948 /*
75949 ** Move an existing blob handle to point to a different row of the same
75950 ** database table.
75951 **
75952 ** If an error occurs, or if the specified row does not exist or does not
75953 ** contain a blob or text value, then an error code is returned and the
75954 ** database handle error code and message set. If this happens, then all
75955 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
75956 ** immediately return SQLITE_ABORT.
75957 */
75958 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
75959   int rc;
75960   Incrblob *p = (Incrblob *)pBlob;
75961   sqlite3 *db;
75962 
75963   if( p==0 ) return SQLITE_MISUSE_BKPT;
75964   db = p->db;
75965   sqlite3_mutex_enter(db->mutex);
75966 
75967   if( p->pStmt==0 ){
75968     /* If there is no statement handle, then the blob-handle has
75969     ** already been invalidated. Return SQLITE_ABORT in this case.
75970     */
75971     rc = SQLITE_ABORT;
75972   }else{
75973     char *zErr;
75974     rc = blobSeekToRow(p, iRow, &zErr);
75975     if( rc!=SQLITE_OK ){
75976       sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
75977       sqlite3DbFree(db, zErr);
75978     }
75979     assert( rc!=SQLITE_SCHEMA );
75980   }
75981 
75982   rc = sqlite3ApiExit(db, rc);
75983   assert( rc==SQLITE_OK || p->pStmt==0 );
75984   sqlite3_mutex_leave(db->mutex);
75985   return rc;
75986 }
75987 
75988 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
75989 
75990 /************** End of vdbeblob.c ********************************************/
75991 /************** Begin file vdbesort.c ****************************************/
75992 /*
75993 ** 2011-07-09
75994 **
75995 ** The author disclaims copyright to this source code.  In place of
75996 ** a legal notice, here is a blessing:
75997 **
75998 **    May you do good and not evil.
75999 **    May you find forgiveness for yourself and forgive others.
76000 **    May you share freely, never taking more than you give.
76001 **
76002 *************************************************************************
76003 ** This file contains code for the VdbeSorter object, used in concert with
76004 ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
76005 ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
76006 ** using indexes and without LIMIT clauses.
76007 **
76008 ** The VdbeSorter object implements a multi-threaded external merge sort
76009 ** algorithm that is efficient even if the number of elements being sorted
76010 ** exceeds the available memory.
76011 **
76012 ** Here is the (internal, non-API) interface between this module and the
76013 ** rest of the SQLite system:
76014 **
76015 **    sqlite3VdbeSorterInit()       Create a new VdbeSorter object.
76016 **
76017 **    sqlite3VdbeSorterWrite()      Add a single new row to the VdbeSorter
76018 **                                  object.  The row is a binary blob in the
76019 **                                  OP_MakeRecord format that contains both
76020 **                                  the ORDER BY key columns and result columns
76021 **                                  in the case of a SELECT w/ ORDER BY, or
76022 **                                  the complete record for an index entry
76023 **                                  in the case of a CREATE INDEX.
76024 **
76025 **    sqlite3VdbeSorterRewind()     Sort all content previously added.
76026 **                                  Position the read cursor on the
76027 **                                  first sorted element.
76028 **
76029 **    sqlite3VdbeSorterNext()       Advance the read cursor to the next sorted
76030 **                                  element.
76031 **
76032 **    sqlite3VdbeSorterRowkey()     Return the complete binary blob for the
76033 **                                  row currently under the read cursor.
76034 **
76035 **    sqlite3VdbeSorterCompare()    Compare the binary blob for the row
76036 **                                  currently under the read cursor against
76037 **                                  another binary blob X and report if
76038 **                                  X is strictly less than the read cursor.
76039 **                                  Used to enforce uniqueness in a
76040 **                                  CREATE UNIQUE INDEX statement.
76041 **
76042 **    sqlite3VdbeSorterClose()      Close the VdbeSorter object and reclaim
76043 **                                  all resources.
76044 **
76045 **    sqlite3VdbeSorterReset()      Refurbish the VdbeSorter for reuse.  This
76046 **                                  is like Close() followed by Init() only
76047 **                                  much faster.
76048 **
76049 ** The interfaces above must be called in a particular order.  Write() can
76050 ** only occur in between Init()/Reset() and Rewind().  Next(), Rowkey(), and
76051 ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
76052 **
76053 **   Init()
76054 **   for each record: Write()
76055 **   Rewind()
76056 **     Rowkey()/Compare()
76057 **   Next()
76058 **   Close()
76059 **
76060 ** Algorithm:
76061 **
76062 ** Records passed to the sorter via calls to Write() are initially held
76063 ** unsorted in main memory. Assuming the amount of memory used never exceeds
76064 ** a threshold, when Rewind() is called the set of records is sorted using
76065 ** an in-memory merge sort. In this case, no temporary files are required
76066 ** and subsequent calls to Rowkey(), Next() and Compare() read records
76067 ** directly from main memory.
76068 **
76069 ** If the amount of space used to store records in main memory exceeds the
76070 ** threshold, then the set of records currently in memory are sorted and
76071 ** written to a temporary file in "Packed Memory Array" (PMA) format.
76072 ** A PMA created at this point is known as a "level-0 PMA". Higher levels
76073 ** of PMAs may be created by merging existing PMAs together - for example
76074 ** merging two or more level-0 PMAs together creates a level-1 PMA.
76075 **
76076 ** The threshold for the amount of main memory to use before flushing
76077 ** records to a PMA is roughly the same as the limit configured for the
76078 ** page-cache of the main database. Specifically, the threshold is set to
76079 ** the value returned by "PRAGMA main.page_size" multipled by
76080 ** that returned by "PRAGMA main.cache_size", in bytes.
76081 **
76082 ** If the sorter is running in single-threaded mode, then all PMAs generated
76083 ** are appended to a single temporary file. Or, if the sorter is running in
76084 ** multi-threaded mode then up to (N+1) temporary files may be opened, where
76085 ** N is the configured number of worker threads. In this case, instead of
76086 ** sorting the records and writing the PMA to a temporary file itself, the
76087 ** calling thread usually launches a worker thread to do so. Except, if
76088 ** there are already N worker threads running, the main thread does the work
76089 ** itself.
76090 **
76091 ** The sorter is running in multi-threaded mode if (a) the library was built
76092 ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
76093 ** than zero, and (b) worker threads have been enabled at runtime by calling
76094 ** sqlite3_config(SQLITE_CONFIG_WORKER_THREADS, ...).
76095 **
76096 ** When Rewind() is called, any data remaining in memory is flushed to a
76097 ** final PMA. So at this point the data is stored in some number of sorted
76098 ** PMAs within temporary files on disk.
76099 **
76100 ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
76101 ** sorter is running in single-threaded mode, then these PMAs are merged
76102 ** incrementally as keys are retreived from the sorter by the VDBE.  The
76103 ** MergeEngine object, described in further detail below, performs this
76104 ** merge.
76105 **
76106 ** Or, if running in multi-threaded mode, then a background thread is
76107 ** launched to merge the existing PMAs. Once the background thread has
76108 ** merged T bytes of data into a single sorted PMA, the main thread
76109 ** begins reading keys from that PMA while the background thread proceeds
76110 ** with merging the next T bytes of data. And so on.
76111 **
76112 ** Parameter T is set to half the value of the memory threshold used
76113 ** by Write() above to determine when to create a new PMA.
76114 **
76115 ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
76116 ** Rewind() is called, then a hierarchy of incremental-merges is used.
76117 ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
76118 ** disk are merged together. Then T bytes of data from the second set, and
76119 ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
76120 ** PMAs at a time. This done is to improve locality.
76121 **
76122 ** If running in multi-threaded mode and there are more than
76123 ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
76124 ** than one background thread may be created. Specifically, there may be
76125 ** one background thread for each temporary file on disk, and one background
76126 ** thread to merge the output of each of the others to a single PMA for
76127 ** the main thread to read from.
76128 */
76129 
76130 /*
76131 ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
76132 ** messages to stderr that may be helpful in understanding the performance
76133 ** characteristics of the sorter in multi-threaded mode.
76134 */
76135 #if 0
76136 # define SQLITE_DEBUG_SORTER_THREADS 1
76137 #endif
76138 
76139 /*
76140 ** Private objects used by the sorter
76141 */
76142 typedef struct MergeEngine MergeEngine;     /* Merge PMAs together */
76143 typedef struct PmaReader PmaReader;         /* Incrementally read one PMA */
76144 typedef struct PmaWriter PmaWriter;         /* Incrementally write one PMA */
76145 typedef struct SorterRecord SorterRecord;   /* A record being sorted */
76146 typedef struct SortSubtask SortSubtask;     /* A sub-task in the sort process */
76147 typedef struct SorterFile SorterFile;       /* Temporary file object wrapper */
76148 typedef struct SorterList SorterList;       /* In-memory list of records */
76149 typedef struct IncrMerger IncrMerger;       /* Read & merge multiple PMAs */
76150 
76151 /*
76152 ** A container for a temp file handle and the current amount of data
76153 ** stored in the file.
76154 */
76155 struct SorterFile {
76156   sqlite3_file *pFd;              /* File handle */
76157   i64 iEof;                       /* Bytes of data stored in pFd */
76158 };
76159 
76160 /*
76161 ** An in-memory list of objects to be sorted.
76162 **
76163 ** If aMemory==0 then each object is allocated separately and the objects
76164 ** are connected using SorterRecord.u.pNext.  If aMemory!=0 then all objects
76165 ** are stored in the aMemory[] bulk memory, one right after the other, and
76166 ** are connected using SorterRecord.u.iNext.
76167 */
76168 struct SorterList {
76169   SorterRecord *pList;            /* Linked list of records */
76170   u8 *aMemory;                    /* If non-NULL, bulk memory to hold pList */
76171   int szPMA;                      /* Size of pList as PMA in bytes */
76172 };
76173 
76174 /*
76175 ** The MergeEngine object is used to combine two or more smaller PMAs into
76176 ** one big PMA using a merge operation.  Separate PMAs all need to be
76177 ** combined into one big PMA in order to be able to step through the sorted
76178 ** records in order.
76179 **
76180 ** The aReadr[] array contains a PmaReader object for each of the PMAs being
76181 ** merged.  An aReadr[] object either points to a valid key or else is at EOF.
76182 ** ("EOF" means "End Of File".  When aReadr[] is at EOF there is no more data.)
76183 ** For the purposes of the paragraphs below, we assume that the array is
76184 ** actually N elements in size, where N is the smallest power of 2 greater
76185 ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
76186 ** are treated as if they are empty (always at EOF).
76187 **
76188 ** The aTree[] array is also N elements in size. The value of N is stored in
76189 ** the MergeEngine.nTree variable.
76190 **
76191 ** The final (N/2) elements of aTree[] contain the results of comparing
76192 ** pairs of PMA keys together. Element i contains the result of
76193 ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
76194 ** aTree element is set to the index of it.
76195 **
76196 ** For the purposes of this comparison, EOF is considered greater than any
76197 ** other key value. If the keys are equal (only possible with two EOF
76198 ** values), it doesn't matter which index is stored.
76199 **
76200 ** The (N/4) elements of aTree[] that precede the final (N/2) described
76201 ** above contains the index of the smallest of each block of 4 PmaReaders
76202 ** And so on. So that aTree[1] contains the index of the PmaReader that
76203 ** currently points to the smallest key value. aTree[0] is unused.
76204 **
76205 ** Example:
76206 **
76207 **     aReadr[0] -> Banana
76208 **     aReadr[1] -> Feijoa
76209 **     aReadr[2] -> Elderberry
76210 **     aReadr[3] -> Currant
76211 **     aReadr[4] -> Grapefruit
76212 **     aReadr[5] -> Apple
76213 **     aReadr[6] -> Durian
76214 **     aReadr[7] -> EOF
76215 **
76216 **     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
76217 **
76218 ** The current element is "Apple" (the value of the key indicated by
76219 ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
76220 ** be advanced to the next key in its segment. Say the next key is
76221 ** "Eggplant":
76222 **
76223 **     aReadr[5] -> Eggplant
76224 **
76225 ** The contents of aTree[] are updated first by comparing the new PmaReader
76226 ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
76227 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
76228 ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
76229 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
76230 ** so the value written into element 1 of the array is 0. As follows:
76231 **
76232 **     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
76233 **
76234 ** In other words, each time we advance to the next sorter element, log2(N)
76235 ** key comparison operations are required, where N is the number of segments
76236 ** being merged (rounded up to the next power of 2).
76237 */
76238 struct MergeEngine {
76239   int nTree;                 /* Used size of aTree/aReadr (power of 2) */
76240   SortSubtask *pTask;        /* Used by this thread only */
76241   int *aTree;                /* Current state of incremental merge */
76242   PmaReader *aReadr;         /* Array of PmaReaders to merge data from */
76243 };
76244 
76245 /*
76246 ** This object represents a single thread of control in a sort operation.
76247 ** Exactly VdbeSorter.nTask instances of this object are allocated
76248 ** as part of each VdbeSorter object. Instances are never allocated any
76249 ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
76250 ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread).  Thus for
76251 ** single-threaded operation, there is exactly one instance of this object
76252 ** and for multi-threaded operation there are two or more instances.
76253 **
76254 ** Essentially, this structure contains all those fields of the VdbeSorter
76255 ** structure for which each thread requires a separate instance. For example,
76256 ** each thread requries its own UnpackedRecord object to unpack records in
76257 ** as part of comparison operations.
76258 **
76259 ** Before a background thread is launched, variable bDone is set to 0. Then,
76260 ** right before it exits, the thread itself sets bDone to 1. This is used for
76261 ** two purposes:
76262 **
76263 **   1. When flushing the contents of memory to a level-0 PMA on disk, to
76264 **      attempt to select a SortSubtask for which there is not already an
76265 **      active background thread (since doing so causes the main thread
76266 **      to block until it finishes).
76267 **
76268 **   2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
76269 **      to sqlite3ThreadJoin() is likely to block. Cases that are likely to
76270 **      block provoke debugging output.
76271 **
76272 ** In both cases, the effects of the main thread seeing (bDone==0) even
76273 ** after the thread has finished are not dire. So we don't worry about
76274 ** memory barriers and such here.
76275 */
76276 struct SortSubtask {
76277   SQLiteThread *pThread;          /* Background thread, if any */
76278   int bDone;                      /* Set if thread is finished but not joined */
76279   VdbeSorter *pSorter;            /* Sorter that owns this sub-task */
76280   UnpackedRecord *pUnpacked;      /* Space to unpack a record */
76281   SorterList list;                /* List for thread to write to a PMA */
76282   int nPMA;                       /* Number of PMAs currently in file */
76283   SorterFile file;                /* Temp file for level-0 PMAs */
76284   SorterFile file2;               /* Space for other PMAs */
76285 };
76286 
76287 /*
76288 ** Main sorter structure. A single instance of this is allocated for each
76289 ** sorter cursor created by the VDBE.
76290 **
76291 ** mxKeysize:
76292 **   As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
76293 **   this variable is updated so as to be set to the size on disk of the
76294 **   largest record in the sorter.
76295 */
76296 struct VdbeSorter {
76297   int mnPmaSize;                  /* Minimum PMA size, in bytes */
76298   int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
76299   int mxKeysize;                  /* Largest serialized key seen so far */
76300   int pgsz;                       /* Main database page size */
76301   PmaReader *pReader;             /* Readr data from here after Rewind() */
76302   MergeEngine *pMerger;           /* Or here, if bUseThreads==0 */
76303   sqlite3 *db;                    /* Database connection */
76304   KeyInfo *pKeyInfo;              /* How to compare records */
76305   UnpackedRecord *pUnpacked;      /* Used by VdbeSorterCompare() */
76306   SorterList list;                /* List of in-memory records */
76307   int iMemory;                    /* Offset of free space in list.aMemory */
76308   int nMemory;                    /* Size of list.aMemory allocation in bytes */
76309   u8 bUsePMA;                     /* True if one or more PMAs created */
76310   u8 bUseThreads;                 /* True to use background threads */
76311   u8 iPrev;                       /* Previous thread used to flush PMA */
76312   u8 nTask;                       /* Size of aTask[] array */
76313   SortSubtask aTask[1];           /* One or more subtasks */
76314 };
76315 
76316 /*
76317 ** An instance of the following object is used to read records out of a
76318 ** PMA, in sorted order.  The next key to be read is cached in nKey/aKey.
76319 ** aKey might point into aMap or into aBuffer.  If neither of those locations
76320 ** contain a contiguous representation of the key, then aAlloc is allocated
76321 ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
76322 **
76323 ** pFd==0 at EOF.
76324 */
76325 struct PmaReader {
76326   i64 iReadOff;               /* Current read offset */
76327   i64 iEof;                   /* 1 byte past EOF for this PmaReader */
76328   int nAlloc;                 /* Bytes of space at aAlloc */
76329   int nKey;                   /* Number of bytes in key */
76330   sqlite3_file *pFd;          /* File handle we are reading from */
76331   u8 *aAlloc;                 /* Space for aKey if aBuffer and pMap wont work */
76332   u8 *aKey;                   /* Pointer to current key */
76333   u8 *aBuffer;                /* Current read buffer */
76334   int nBuffer;                /* Size of read buffer in bytes */
76335   u8 *aMap;                   /* Pointer to mapping of entire file */
76336   IncrMerger *pIncr;          /* Incremental merger */
76337 };
76338 
76339 /*
76340 ** Normally, a PmaReader object iterates through an existing PMA stored
76341 ** within a temp file. However, if the PmaReader.pIncr variable points to
76342 ** an object of the following type, it may be used to iterate/merge through
76343 ** multiple PMAs simultaneously.
76344 **
76345 ** There are two types of IncrMerger object - single (bUseThread==0) and
76346 ** multi-threaded (bUseThread==1).
76347 **
76348 ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
76349 ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
76350 ** size. When the IncrMerger is initialized, it reads enough data from
76351 ** pMerger to populate aFile[0]. It then sets variables within the
76352 ** corresponding PmaReader object to read from that file and kicks off
76353 ** a background thread to populate aFile[1] with the next mxSz bytes of
76354 ** sorted record data from pMerger.
76355 **
76356 ** When the PmaReader reaches the end of aFile[0], it blocks until the
76357 ** background thread has finished populating aFile[1]. It then exchanges
76358 ** the contents of the aFile[0] and aFile[1] variables within this structure,
76359 ** sets the PmaReader fields to read from the new aFile[0] and kicks off
76360 ** another background thread to populate the new aFile[1]. And so on, until
76361 ** the contents of pMerger are exhausted.
76362 **
76363 ** A single-threaded IncrMerger does not open any temporary files of its
76364 ** own. Instead, it has exclusive access to mxSz bytes of space beginning
76365 ** at offset iStartOff of file pTask->file2. And instead of using a
76366 ** background thread to prepare data for the PmaReader, with a single
76367 ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
76368 ** keys from pMerger by the calling thread whenever the PmaReader runs out
76369 ** of data.
76370 */
76371 struct IncrMerger {
76372   SortSubtask *pTask;             /* Task that owns this merger */
76373   MergeEngine *pMerger;           /* Merge engine thread reads data from */
76374   i64 iStartOff;                  /* Offset to start writing file at */
76375   int mxSz;                       /* Maximum bytes of data to store */
76376   int bEof;                       /* Set to true when merge is finished */
76377   int bUseThread;                 /* True to use a bg thread for this object */
76378   SorterFile aFile[2];            /* aFile[0] for reading, [1] for writing */
76379 };
76380 
76381 /*
76382 ** An instance of this object is used for writing a PMA.
76383 **
76384 ** The PMA is written one record at a time.  Each record is of an arbitrary
76385 ** size.  But I/O is more efficient if it occurs in page-sized blocks where
76386 ** each block is aligned on a page boundary.  This object caches writes to
76387 ** the PMA so that aligned, page-size blocks are written.
76388 */
76389 struct PmaWriter {
76390   int eFWErr;                     /* Non-zero if in an error state */
76391   u8 *aBuffer;                    /* Pointer to write buffer */
76392   int nBuffer;                    /* Size of write buffer in bytes */
76393   int iBufStart;                  /* First byte of buffer to write */
76394   int iBufEnd;                    /* Last byte of buffer to write */
76395   i64 iWriteOff;                  /* Offset of start of buffer in file */
76396   sqlite3_file *pFd;              /* File handle to write to */
76397 };
76398 
76399 /*
76400 ** This object is the header on a single record while that record is being
76401 ** held in memory and prior to being written out as part of a PMA.
76402 **
76403 ** How the linked list is connected depends on how memory is being managed
76404 ** by this module. If using a separate allocation for each in-memory record
76405 ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
76406 ** SorterRecord.u.pNext pointers.
76407 **
76408 ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
76409 ** then while records are being accumulated the list is linked using the
76410 ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
76411 ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
76412 ** has finished passing records to the sorter, or when the in-memory buffer
76413 ** is full, the list is sorted. As part of the sorting process, it is
76414 ** converted to use the SorterRecord.u.pNext pointers. See function
76415 ** vdbeSorterSort() for details.
76416 */
76417 struct SorterRecord {
76418   int nVal;                       /* Size of the record in bytes */
76419   union {
76420     SorterRecord *pNext;          /* Pointer to next record in list */
76421     int iNext;                    /* Offset within aMemory of next record */
76422   } u;
76423   /* The data for the record immediately follows this header */
76424 };
76425 
76426 /* Return a pointer to the buffer containing the record data for SorterRecord
76427 ** object p. Should be used as if:
76428 **
76429 **   void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
76430 */
76431 #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
76432 
76433 /* The minimum PMA size is set to this value multiplied by the database
76434 ** page size in bytes.  */
76435 #define SORTER_MIN_WORKING 10
76436 
76437 /* Maximum number of PMAs that a single MergeEngine can merge */
76438 #define SORTER_MAX_MERGE_COUNT 16
76439 
76440 static int vdbeIncrSwap(IncrMerger*);
76441 static void vdbeIncrFree(IncrMerger *);
76442 
76443 /*
76444 ** Free all memory belonging to the PmaReader object passed as the
76445 ** argument. All structure fields are set to zero before returning.
76446 */
76447 static void vdbePmaReaderClear(PmaReader *pReadr){
76448   sqlite3_free(pReadr->aAlloc);
76449   sqlite3_free(pReadr->aBuffer);
76450   if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
76451   vdbeIncrFree(pReadr->pIncr);
76452   memset(pReadr, 0, sizeof(PmaReader));
76453 }
76454 
76455 /*
76456 ** Read the next nByte bytes of data from the PMA p.
76457 ** If successful, set *ppOut to point to a buffer containing the data
76458 ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
76459 ** error code.
76460 **
76461 ** The buffer returned in *ppOut is only valid until the
76462 ** next call to this function.
76463 */
76464 static int vdbePmaReadBlob(
76465   PmaReader *p,                   /* PmaReader from which to take the blob */
76466   int nByte,                      /* Bytes of data to read */
76467   u8 **ppOut                      /* OUT: Pointer to buffer containing data */
76468 ){
76469   int iBuf;                       /* Offset within buffer to read from */
76470   int nAvail;                     /* Bytes of data available in buffer */
76471 
76472   if( p->aMap ){
76473     *ppOut = &p->aMap[p->iReadOff];
76474     p->iReadOff += nByte;
76475     return SQLITE_OK;
76476   }
76477 
76478   assert( p->aBuffer );
76479 
76480   /* If there is no more data to be read from the buffer, read the next
76481   ** p->nBuffer bytes of data from the file into it. Or, if there are less
76482   ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
76483   iBuf = p->iReadOff % p->nBuffer;
76484   if( iBuf==0 ){
76485     int nRead;                    /* Bytes to read from disk */
76486     int rc;                       /* sqlite3OsRead() return code */
76487 
76488     /* Determine how many bytes of data to read. */
76489     if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
76490       nRead = p->nBuffer;
76491     }else{
76492       nRead = (int)(p->iEof - p->iReadOff);
76493     }
76494     assert( nRead>0 );
76495 
76496     /* Readr data from the file. Return early if an error occurs. */
76497     rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
76498     assert( rc!=SQLITE_IOERR_SHORT_READ );
76499     if( rc!=SQLITE_OK ) return rc;
76500   }
76501   nAvail = p->nBuffer - iBuf;
76502 
76503   if( nByte<=nAvail ){
76504     /* The requested data is available in the in-memory buffer. In this
76505     ** case there is no need to make a copy of the data, just return a
76506     ** pointer into the buffer to the caller.  */
76507     *ppOut = &p->aBuffer[iBuf];
76508     p->iReadOff += nByte;
76509   }else{
76510     /* The requested data is not all available in the in-memory buffer.
76511     ** In this case, allocate space at p->aAlloc[] to copy the requested
76512     ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
76513     int nRem;                     /* Bytes remaining to copy */
76514 
76515     /* Extend the p->aAlloc[] allocation if required. */
76516     if( p->nAlloc<nByte ){
76517       u8 *aNew;
76518       int nNew = MAX(128, p->nAlloc*2);
76519       while( nByte>nNew ) nNew = nNew*2;
76520       aNew = sqlite3Realloc(p->aAlloc, nNew);
76521       if( !aNew ) return SQLITE_NOMEM;
76522       p->nAlloc = nNew;
76523       p->aAlloc = aNew;
76524     }
76525 
76526     /* Copy as much data as is available in the buffer into the start of
76527     ** p->aAlloc[].  */
76528     memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
76529     p->iReadOff += nAvail;
76530     nRem = nByte - nAvail;
76531 
76532     /* The following loop copies up to p->nBuffer bytes per iteration into
76533     ** the p->aAlloc[] buffer.  */
76534     while( nRem>0 ){
76535       int rc;                     /* vdbePmaReadBlob() return code */
76536       int nCopy;                  /* Number of bytes to copy */
76537       u8 *aNext;                  /* Pointer to buffer to copy data from */
76538 
76539       nCopy = nRem;
76540       if( nRem>p->nBuffer ) nCopy = p->nBuffer;
76541       rc = vdbePmaReadBlob(p, nCopy, &aNext);
76542       if( rc!=SQLITE_OK ) return rc;
76543       assert( aNext!=p->aAlloc );
76544       memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
76545       nRem -= nCopy;
76546     }
76547 
76548     *ppOut = p->aAlloc;
76549   }
76550 
76551   return SQLITE_OK;
76552 }
76553 
76554 /*
76555 ** Read a varint from the stream of data accessed by p. Set *pnOut to
76556 ** the value read.
76557 */
76558 static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
76559   int iBuf;
76560 
76561   if( p->aMap ){
76562     p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
76563   }else{
76564     iBuf = p->iReadOff % p->nBuffer;
76565     if( iBuf && (p->nBuffer-iBuf)>=9 ){
76566       p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
76567     }else{
76568       u8 aVarint[16], *a;
76569       int i = 0, rc;
76570       do{
76571         rc = vdbePmaReadBlob(p, 1, &a);
76572         if( rc ) return rc;
76573         aVarint[(i++)&0xf] = a[0];
76574       }while( (a[0]&0x80)!=0 );
76575       sqlite3GetVarint(aVarint, pnOut);
76576     }
76577   }
76578 
76579   return SQLITE_OK;
76580 }
76581 
76582 /*
76583 ** Attempt to memory map file pFile. If successful, set *pp to point to the
76584 ** new mapping and return SQLITE_OK. If the mapping is not attempted
76585 ** (because the file is too large or the VFS layer is configured not to use
76586 ** mmap), return SQLITE_OK and set *pp to NULL.
76587 **
76588 ** Or, if an error occurs, return an SQLite error code. The final value of
76589 ** *pp is undefined in this case.
76590 */
76591 static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
76592   int rc = SQLITE_OK;
76593   if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
76594     sqlite3_file *pFd = pFile->pFd;
76595     if( pFd->pMethods->iVersion>=3 ){
76596       rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
76597       testcase( rc!=SQLITE_OK );
76598     }
76599   }
76600   return rc;
76601 }
76602 
76603 /*
76604 ** Attach PmaReader pReadr to file pFile (if it is not already attached to
76605 ** that file) and seek it to offset iOff within the file.  Return SQLITE_OK
76606 ** if successful, or an SQLite error code if an error occurs.
76607 */
76608 static int vdbePmaReaderSeek(
76609   SortSubtask *pTask,             /* Task context */
76610   PmaReader *pReadr,              /* Reader whose cursor is to be moved */
76611   SorterFile *pFile,              /* Sorter file to read from */
76612   i64 iOff                        /* Offset in pFile */
76613 ){
76614   int rc = SQLITE_OK;
76615 
76616   assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
76617 
76618   if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
76619   if( pReadr->aMap ){
76620     sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
76621     pReadr->aMap = 0;
76622   }
76623   pReadr->iReadOff = iOff;
76624   pReadr->iEof = pFile->iEof;
76625   pReadr->pFd = pFile->pFd;
76626 
76627   rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
76628   if( rc==SQLITE_OK && pReadr->aMap==0 ){
76629     int pgsz = pTask->pSorter->pgsz;
76630     int iBuf = pReadr->iReadOff % pgsz;
76631     if( pReadr->aBuffer==0 ){
76632       pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
76633       if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM;
76634       pReadr->nBuffer = pgsz;
76635     }
76636     if( rc==SQLITE_OK && iBuf ){
76637       int nRead = pgsz - iBuf;
76638       if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
76639         nRead = (int)(pReadr->iEof - pReadr->iReadOff);
76640       }
76641       rc = sqlite3OsRead(
76642           pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
76643       );
76644       testcase( rc!=SQLITE_OK );
76645     }
76646   }
76647 
76648   return rc;
76649 }
76650 
76651 /*
76652 ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
76653 ** no error occurs, or an SQLite error code if one does.
76654 */
76655 static int vdbePmaReaderNext(PmaReader *pReadr){
76656   int rc = SQLITE_OK;             /* Return Code */
76657   u64 nRec = 0;                   /* Size of record in bytes */
76658 
76659 
76660   if( pReadr->iReadOff>=pReadr->iEof ){
76661     IncrMerger *pIncr = pReadr->pIncr;
76662     int bEof = 1;
76663     if( pIncr ){
76664       rc = vdbeIncrSwap(pIncr);
76665       if( rc==SQLITE_OK && pIncr->bEof==0 ){
76666         rc = vdbePmaReaderSeek(
76667             pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
76668         );
76669         bEof = 0;
76670       }
76671     }
76672 
76673     if( bEof ){
76674       /* This is an EOF condition */
76675       vdbePmaReaderClear(pReadr);
76676       testcase( rc!=SQLITE_OK );
76677       return rc;
76678     }
76679   }
76680 
76681   if( rc==SQLITE_OK ){
76682     rc = vdbePmaReadVarint(pReadr, &nRec);
76683   }
76684   if( rc==SQLITE_OK ){
76685     pReadr->nKey = (int)nRec;
76686     rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
76687     testcase( rc!=SQLITE_OK );
76688   }
76689 
76690   return rc;
76691 }
76692 
76693 /*
76694 ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
76695 ** starting at offset iStart and ending at offset iEof-1. This function
76696 ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
76697 ** PMA is empty).
76698 **
76699 ** If the pnByte parameter is NULL, then it is assumed that the file
76700 ** contains a single PMA, and that that PMA omits the initial length varint.
76701 */
76702 static int vdbePmaReaderInit(
76703   SortSubtask *pTask,             /* Task context */
76704   SorterFile *pFile,              /* Sorter file to read from */
76705   i64 iStart,                     /* Start offset in pFile */
76706   PmaReader *pReadr,              /* PmaReader to populate */
76707   i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
76708 ){
76709   int rc;
76710 
76711   assert( pFile->iEof>iStart );
76712   assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
76713   assert( pReadr->aBuffer==0 );
76714   assert( pReadr->aMap==0 );
76715 
76716   rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
76717   if( rc==SQLITE_OK ){
76718     u64 nByte;                    /* Size of PMA in bytes */
76719     rc = vdbePmaReadVarint(pReadr, &nByte);
76720     pReadr->iEof = pReadr->iReadOff + nByte;
76721     *pnByte += nByte;
76722   }
76723 
76724   if( rc==SQLITE_OK ){
76725     rc = vdbePmaReaderNext(pReadr);
76726   }
76727   return rc;
76728 }
76729 
76730 
76731 /*
76732 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
76733 ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
76734 ** used by the comparison. Return the result of the comparison.
76735 **
76736 ** Before returning, object (pTask->pUnpacked) is populated with the
76737 ** unpacked version of key2. Or, if pKey2 is passed a NULL pointer, then it
76738 ** is assumed that the (pTask->pUnpacked) structure already contains the
76739 ** unpacked key to use as key2.
76740 **
76741 ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
76742 ** to SQLITE_NOMEM.
76743 */
76744 static int vdbeSorterCompare(
76745   SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
76746   const void *pKey1, int nKey1,   /* Left side of comparison */
76747   const void *pKey2, int nKey2    /* Right side of comparison */
76748 ){
76749   UnpackedRecord *r2 = pTask->pUnpacked;
76750   if( pKey2 ){
76751     sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
76752   }
76753   return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
76754 }
76755 
76756 /*
76757 ** Initialize the temporary index cursor just opened as a sorter cursor.
76758 **
76759 ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
76760 ** to determine the number of fields that should be compared from the
76761 ** records being sorted. However, if the value passed as argument nField
76762 ** is non-zero and the sorter is able to guarantee a stable sort, nField
76763 ** is used instead. This is used when sorting records for a CREATE INDEX
76764 ** statement. In this case, keys are always delivered to the sorter in
76765 ** order of the primary key, which happens to be make up the final part
76766 ** of the records being sorted. So if the sort is stable, there is never
76767 ** any reason to compare PK fields and they can be ignored for a small
76768 ** performance boost.
76769 **
76770 ** The sorter can guarantee a stable sort when running in single-threaded
76771 ** mode, but not in multi-threaded mode.
76772 **
76773 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
76774 */
76775 SQLITE_PRIVATE int sqlite3VdbeSorterInit(
76776   sqlite3 *db,                    /* Database connection (for malloc()) */
76777   int nField,                     /* Number of key fields in each record */
76778   VdbeCursor *pCsr                /* Cursor that holds the new sorter */
76779 ){
76780   int pgsz;                       /* Page size of main database */
76781   int i;                          /* Used to iterate through aTask[] */
76782   int mxCache;                    /* Cache size */
76783   VdbeSorter *pSorter;            /* The new sorter */
76784   KeyInfo *pKeyInfo;              /* Copy of pCsr->pKeyInfo with db==0 */
76785   int szKeyInfo;                  /* Size of pCsr->pKeyInfo in bytes */
76786   int sz;                         /* Size of pSorter in bytes */
76787   int rc = SQLITE_OK;
76788 #if SQLITE_MAX_WORKER_THREADS==0
76789 # define nWorker 0
76790 #else
76791   int nWorker;
76792 #endif
76793 
76794   /* Initialize the upper limit on the number of worker threads */
76795 #if SQLITE_MAX_WORKER_THREADS>0
76796   if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
76797     nWorker = 0;
76798   }else{
76799     nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
76800   }
76801 #endif
76802 
76803   /* Do not allow the total number of threads (main thread + all workers)
76804   ** to exceed the maximum merge count */
76805 #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
76806   if( nWorker>=SORTER_MAX_MERGE_COUNT ){
76807     nWorker = SORTER_MAX_MERGE_COUNT-1;
76808   }
76809 #endif
76810 
76811   assert( pCsr->pKeyInfo && pCsr->pBt==0 );
76812   szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
76813   sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
76814 
76815   pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
76816   pCsr->pSorter = pSorter;
76817   if( pSorter==0 ){
76818     rc = SQLITE_NOMEM;
76819   }else{
76820     pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
76821     memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
76822     pKeyInfo->db = 0;
76823     if( nField && nWorker==0 ) pKeyInfo->nField = nField;
76824     pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
76825     pSorter->nTask = nWorker + 1;
76826     pSorter->bUseThreads = (pSorter->nTask>1);
76827     pSorter->db = db;
76828     for(i=0; i<pSorter->nTask; i++){
76829       SortSubtask *pTask = &pSorter->aTask[i];
76830       pTask->pSorter = pSorter;
76831     }
76832 
76833     if( !sqlite3TempInMemory(db) ){
76834       pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
76835       mxCache = db->aDb[0].pSchema->cache_size;
76836       if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
76837       pSorter->mxPmaSize = mxCache * pgsz;
76838 
76839       /* If the application has not configure scratch memory using
76840       ** SQLITE_CONFIG_SCRATCH then we assume it is OK to do large memory
76841       ** allocations.  If scratch memory has been configured, then assume
76842       ** large memory allocations should be avoided to prevent heap
76843       ** fragmentation.
76844       */
76845       if( sqlite3GlobalConfig.pScratch==0 ){
76846         assert( pSorter->iMemory==0 );
76847         pSorter->nMemory = pgsz;
76848         pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
76849         if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM;
76850       }
76851     }
76852   }
76853 
76854   return rc;
76855 }
76856 #undef nWorker   /* Defined at the top of this function */
76857 
76858 /*
76859 ** Free the list of sorted records starting at pRecord.
76860 */
76861 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
76862   SorterRecord *p;
76863   SorterRecord *pNext;
76864   for(p=pRecord; p; p=pNext){
76865     pNext = p->u.pNext;
76866     sqlite3DbFree(db, p);
76867   }
76868 }
76869 
76870 /*
76871 ** Free all resources owned by the object indicated by argument pTask. All
76872 ** fields of *pTask are zeroed before returning.
76873 */
76874 static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
76875   sqlite3DbFree(db, pTask->pUnpacked);
76876   pTask->pUnpacked = 0;
76877 #if SQLITE_MAX_WORKER_THREADS>0
76878   /* pTask->list.aMemory can only be non-zero if it was handed memory
76879   ** from the main thread.  That only occurs SQLITE_MAX_WORKER_THREADS>0 */
76880   if( pTask->list.aMemory ){
76881     sqlite3_free(pTask->list.aMemory);
76882     pTask->list.aMemory = 0;
76883   }else
76884 #endif
76885   {
76886     assert( pTask->list.aMemory==0 );
76887     vdbeSorterRecordFree(0, pTask->list.pList);
76888   }
76889   pTask->list.pList = 0;
76890   if( pTask->file.pFd ){
76891     sqlite3OsCloseFree(pTask->file.pFd);
76892     pTask->file.pFd = 0;
76893     pTask->file.iEof = 0;
76894   }
76895   if( pTask->file2.pFd ){
76896     sqlite3OsCloseFree(pTask->file2.pFd);
76897     pTask->file2.pFd = 0;
76898     pTask->file2.iEof = 0;
76899   }
76900 }
76901 
76902 #ifdef SQLITE_DEBUG_SORTER_THREADS
76903 static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
76904   i64 t;
76905   int iTask = (pTask - pTask->pSorter->aTask);
76906   sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
76907   fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
76908 }
76909 static void vdbeSorterRewindDebug(const char *zEvent){
76910   i64 t;
76911   sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
76912   fprintf(stderr, "%lld:X %s\n", t, zEvent);
76913 }
76914 static void vdbeSorterPopulateDebug(
76915   SortSubtask *pTask,
76916   const char *zEvent
76917 ){
76918   i64 t;
76919   int iTask = (pTask - pTask->pSorter->aTask);
76920   sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
76921   fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
76922 }
76923 static void vdbeSorterBlockDebug(
76924   SortSubtask *pTask,
76925   int bBlocked,
76926   const char *zEvent
76927 ){
76928   if( bBlocked ){
76929     i64 t;
76930     sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
76931     fprintf(stderr, "%lld:main %s\n", t, zEvent);
76932   }
76933 }
76934 #else
76935 # define vdbeSorterWorkDebug(x,y)
76936 # define vdbeSorterRewindDebug(y)
76937 # define vdbeSorterPopulateDebug(x,y)
76938 # define vdbeSorterBlockDebug(x,y,z)
76939 #endif
76940 
76941 #if SQLITE_MAX_WORKER_THREADS>0
76942 /*
76943 ** Join thread pTask->thread.
76944 */
76945 static int vdbeSorterJoinThread(SortSubtask *pTask){
76946   int rc = SQLITE_OK;
76947   if( pTask->pThread ){
76948 #ifdef SQLITE_DEBUG_SORTER_THREADS
76949     int bDone = pTask->bDone;
76950 #endif
76951     void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
76952     vdbeSorterBlockDebug(pTask, !bDone, "enter");
76953     (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
76954     vdbeSorterBlockDebug(pTask, !bDone, "exit");
76955     rc = SQLITE_PTR_TO_INT(pRet);
76956     assert( pTask->bDone==1 );
76957     pTask->bDone = 0;
76958     pTask->pThread = 0;
76959   }
76960   return rc;
76961 }
76962 
76963 /*
76964 ** Launch a background thread to run xTask(pIn).
76965 */
76966 static int vdbeSorterCreateThread(
76967   SortSubtask *pTask,             /* Thread will use this task object */
76968   void *(*xTask)(void*),          /* Routine to run in a separate thread */
76969   void *pIn                       /* Argument passed into xTask() */
76970 ){
76971   assert( pTask->pThread==0 && pTask->bDone==0 );
76972   return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
76973 }
76974 
76975 /*
76976 ** Join all outstanding threads launched by SorterWrite() to create
76977 ** level-0 PMAs.
76978 */
76979 static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
76980   int rc = rcin;
76981   int i;
76982 
76983   /* This function is always called by the main user thread.
76984   **
76985   ** If this function is being called after SorterRewind() has been called,
76986   ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
76987   ** is currently attempt to join one of the other threads. To avoid a race
76988   ** condition where this thread also attempts to join the same object, join
76989   ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
76990   for(i=pSorter->nTask-1; i>=0; i--){
76991     SortSubtask *pTask = &pSorter->aTask[i];
76992     int rc2 = vdbeSorterJoinThread(pTask);
76993     if( rc==SQLITE_OK ) rc = rc2;
76994   }
76995   return rc;
76996 }
76997 #else
76998 # define vdbeSorterJoinAll(x,rcin) (rcin)
76999 # define vdbeSorterJoinThread(pTask) SQLITE_OK
77000 #endif
77001 
77002 /*
77003 ** Allocate a new MergeEngine object capable of handling up to
77004 ** nReader PmaReader inputs.
77005 **
77006 ** nReader is automatically rounded up to the next power of two.
77007 ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
77008 */
77009 static MergeEngine *vdbeMergeEngineNew(int nReader){
77010   int N = 2;                      /* Smallest power of two >= nReader */
77011   int nByte;                      /* Total bytes of space to allocate */
77012   MergeEngine *pNew;              /* Pointer to allocated object to return */
77013 
77014   assert( nReader<=SORTER_MAX_MERGE_COUNT );
77015 
77016   while( N<nReader ) N += N;
77017   nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
77018 
77019   pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
77020   if( pNew ){
77021     pNew->nTree = N;
77022     pNew->pTask = 0;
77023     pNew->aReadr = (PmaReader*)&pNew[1];
77024     pNew->aTree = (int*)&pNew->aReadr[N];
77025   }
77026   return pNew;
77027 }
77028 
77029 /*
77030 ** Free the MergeEngine object passed as the only argument.
77031 */
77032 static void vdbeMergeEngineFree(MergeEngine *pMerger){
77033   int i;
77034   if( pMerger ){
77035     for(i=0; i<pMerger->nTree; i++){
77036       vdbePmaReaderClear(&pMerger->aReadr[i]);
77037     }
77038   }
77039   sqlite3_free(pMerger);
77040 }
77041 
77042 /*
77043 ** Free all resources associated with the IncrMerger object indicated by
77044 ** the first argument.
77045 */
77046 static void vdbeIncrFree(IncrMerger *pIncr){
77047   if( pIncr ){
77048 #if SQLITE_MAX_WORKER_THREADS>0
77049     if( pIncr->bUseThread ){
77050       vdbeSorterJoinThread(pIncr->pTask);
77051       if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
77052       if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
77053     }
77054 #endif
77055     vdbeMergeEngineFree(pIncr->pMerger);
77056     sqlite3_free(pIncr);
77057   }
77058 }
77059 
77060 /*
77061 ** Reset a sorting cursor back to its original empty state.
77062 */
77063 SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
77064   int i;
77065   (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
77066   assert( pSorter->bUseThreads || pSorter->pReader==0 );
77067 #if SQLITE_MAX_WORKER_THREADS>0
77068   if( pSorter->pReader ){
77069     vdbePmaReaderClear(pSorter->pReader);
77070     sqlite3DbFree(db, pSorter->pReader);
77071     pSorter->pReader = 0;
77072   }
77073 #endif
77074   vdbeMergeEngineFree(pSorter->pMerger);
77075   pSorter->pMerger = 0;
77076   for(i=0; i<pSorter->nTask; i++){
77077     SortSubtask *pTask = &pSorter->aTask[i];
77078     vdbeSortSubtaskCleanup(db, pTask);
77079   }
77080   if( pSorter->list.aMemory==0 ){
77081     vdbeSorterRecordFree(0, pSorter->list.pList);
77082   }
77083   pSorter->list.pList = 0;
77084   pSorter->list.szPMA = 0;
77085   pSorter->bUsePMA = 0;
77086   pSorter->iMemory = 0;
77087   pSorter->mxKeysize = 0;
77088   sqlite3DbFree(db, pSorter->pUnpacked);
77089   pSorter->pUnpacked = 0;
77090 }
77091 
77092 /*
77093 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
77094 */
77095 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
77096   VdbeSorter *pSorter = pCsr->pSorter;
77097   if( pSorter ){
77098     sqlite3VdbeSorterReset(db, pSorter);
77099     sqlite3_free(pSorter->list.aMemory);
77100     sqlite3DbFree(db, pSorter);
77101     pCsr->pSorter = 0;
77102   }
77103 }
77104 
77105 #if SQLITE_MAX_MMAP_SIZE>0
77106 /*
77107 ** The first argument is a file-handle open on a temporary file. The file
77108 ** is guaranteed to be nByte bytes or smaller in size. This function
77109 ** attempts to extend the file to nByte bytes in size and to ensure that
77110 ** the VFS has memory mapped it.
77111 **
77112 ** Whether or not the file does end up memory mapped of course depends on
77113 ** the specific VFS implementation.
77114 */
77115 static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
77116   if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
77117     int rc = sqlite3OsTruncate(pFd, nByte);
77118     if( rc==SQLITE_OK ){
77119       void *p = 0;
77120       sqlite3OsFetch(pFd, 0, (int)nByte, &p);
77121       sqlite3OsUnfetch(pFd, 0, p);
77122     }
77123   }
77124 }
77125 #else
77126 # define vdbeSorterExtendFile(x,y,z)
77127 #endif
77128 
77129 /*
77130 ** Allocate space for a file-handle and open a temporary file. If successful,
77131 ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
77132 ** Otherwise, set *ppFd to 0 and return an SQLite error code.
77133 */
77134 static int vdbeSorterOpenTempFile(
77135   sqlite3 *db,                    /* Database handle doing sort */
77136   i64 nExtend,                    /* Attempt to extend file to this size */
77137   sqlite3_file **ppFd
77138 ){
77139   int rc;
77140   rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
77141       SQLITE_OPEN_TEMP_JOURNAL |
77142       SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
77143       SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &rc
77144   );
77145   if( rc==SQLITE_OK ){
77146     i64 max = SQLITE_MAX_MMAP_SIZE;
77147     sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
77148     if( nExtend>0 ){
77149       vdbeSorterExtendFile(db, *ppFd, nExtend);
77150     }
77151   }
77152   return rc;
77153 }
77154 
77155 /*
77156 ** If it has not already been allocated, allocate the UnpackedRecord
77157 ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
77158 ** if no allocation was required), or SQLITE_NOMEM otherwise.
77159 */
77160 static int vdbeSortAllocUnpacked(SortSubtask *pTask){
77161   if( pTask->pUnpacked==0 ){
77162     char *pFree;
77163     pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(
77164         pTask->pSorter->pKeyInfo, 0, 0, &pFree
77165     );
77166     assert( pTask->pUnpacked==(UnpackedRecord*)pFree );
77167     if( pFree==0 ) return SQLITE_NOMEM;
77168     pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
77169     pTask->pUnpacked->errCode = 0;
77170   }
77171   return SQLITE_OK;
77172 }
77173 
77174 
77175 /*
77176 ** Merge the two sorted lists p1 and p2 into a single list.
77177 ** Set *ppOut to the head of the new list.
77178 */
77179 static void vdbeSorterMerge(
77180   SortSubtask *pTask,             /* Calling thread context */
77181   SorterRecord *p1,               /* First list to merge */
77182   SorterRecord *p2,               /* Second list to merge */
77183   SorterRecord **ppOut            /* OUT: Head of merged list */
77184 ){
77185   SorterRecord *pFinal = 0;
77186   SorterRecord **pp = &pFinal;
77187   void *pVal2 = p2 ? SRVAL(p2) : 0;
77188 
77189   while( p1 && p2 ){
77190     int res;
77191     res = vdbeSorterCompare(pTask, SRVAL(p1), p1->nVal, pVal2, p2->nVal);
77192     if( res<=0 ){
77193       *pp = p1;
77194       pp = &p1->u.pNext;
77195       p1 = p1->u.pNext;
77196       pVal2 = 0;
77197     }else{
77198       *pp = p2;
77199        pp = &p2->u.pNext;
77200       p2 = p2->u.pNext;
77201       if( p2==0 ) break;
77202       pVal2 = SRVAL(p2);
77203     }
77204   }
77205   *pp = p1 ? p1 : p2;
77206   *ppOut = pFinal;
77207 }
77208 
77209 /*
77210 ** Sort the linked list of records headed at pTask->pList. Return
77211 ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
77212 ** an error occurs.
77213 */
77214 static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
77215   int i;
77216   SorterRecord **aSlot;
77217   SorterRecord *p;
77218   int rc;
77219 
77220   rc = vdbeSortAllocUnpacked(pTask);
77221   if( rc!=SQLITE_OK ) return rc;
77222 
77223   aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
77224   if( !aSlot ){
77225     return SQLITE_NOMEM;
77226   }
77227 
77228   p = pList->pList;
77229   while( p ){
77230     SorterRecord *pNext;
77231     if( pList->aMemory ){
77232       if( (u8*)p==pList->aMemory ){
77233         pNext = 0;
77234       }else{
77235         assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
77236         pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
77237       }
77238     }else{
77239       pNext = p->u.pNext;
77240     }
77241 
77242     p->u.pNext = 0;
77243     for(i=0; aSlot[i]; i++){
77244       vdbeSorterMerge(pTask, p, aSlot[i], &p);
77245       aSlot[i] = 0;
77246     }
77247     aSlot[i] = p;
77248     p = pNext;
77249   }
77250 
77251   p = 0;
77252   for(i=0; i<64; i++){
77253     vdbeSorterMerge(pTask, p, aSlot[i], &p);
77254   }
77255   pList->pList = p;
77256 
77257   sqlite3_free(aSlot);
77258   assert( pTask->pUnpacked->errCode==SQLITE_OK
77259        || pTask->pUnpacked->errCode==SQLITE_NOMEM
77260   );
77261   return pTask->pUnpacked->errCode;
77262 }
77263 
77264 /*
77265 ** Initialize a PMA-writer object.
77266 */
77267 static void vdbePmaWriterInit(
77268   sqlite3_file *pFd,              /* File handle to write to */
77269   PmaWriter *p,                   /* Object to populate */
77270   int nBuf,                       /* Buffer size */
77271   i64 iStart                      /* Offset of pFd to begin writing at */
77272 ){
77273   memset(p, 0, sizeof(PmaWriter));
77274   p->aBuffer = (u8*)sqlite3Malloc(nBuf);
77275   if( !p->aBuffer ){
77276     p->eFWErr = SQLITE_NOMEM;
77277   }else{
77278     p->iBufEnd = p->iBufStart = (iStart % nBuf);
77279     p->iWriteOff = iStart - p->iBufStart;
77280     p->nBuffer = nBuf;
77281     p->pFd = pFd;
77282   }
77283 }
77284 
77285 /*
77286 ** Write nData bytes of data to the PMA. Return SQLITE_OK
77287 ** if successful, or an SQLite error code if an error occurs.
77288 */
77289 static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
77290   int nRem = nData;
77291   while( nRem>0 && p->eFWErr==0 ){
77292     int nCopy = nRem;
77293     if( nCopy>(p->nBuffer - p->iBufEnd) ){
77294       nCopy = p->nBuffer - p->iBufEnd;
77295     }
77296 
77297     memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
77298     p->iBufEnd += nCopy;
77299     if( p->iBufEnd==p->nBuffer ){
77300       p->eFWErr = sqlite3OsWrite(p->pFd,
77301           &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
77302           p->iWriteOff + p->iBufStart
77303       );
77304       p->iBufStart = p->iBufEnd = 0;
77305       p->iWriteOff += p->nBuffer;
77306     }
77307     assert( p->iBufEnd<p->nBuffer );
77308 
77309     nRem -= nCopy;
77310   }
77311 }
77312 
77313 /*
77314 ** Flush any buffered data to disk and clean up the PMA-writer object.
77315 ** The results of using the PMA-writer after this call are undefined.
77316 ** Return SQLITE_OK if flushing the buffered data succeeds or is not
77317 ** required. Otherwise, return an SQLite error code.
77318 **
77319 ** Before returning, set *piEof to the offset immediately following the
77320 ** last byte written to the file.
77321 */
77322 static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
77323   int rc;
77324   if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
77325     p->eFWErr = sqlite3OsWrite(p->pFd,
77326         &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
77327         p->iWriteOff + p->iBufStart
77328     );
77329   }
77330   *piEof = (p->iWriteOff + p->iBufEnd);
77331   sqlite3_free(p->aBuffer);
77332   rc = p->eFWErr;
77333   memset(p, 0, sizeof(PmaWriter));
77334   return rc;
77335 }
77336 
77337 /*
77338 ** Write value iVal encoded as a varint to the PMA. Return
77339 ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
77340 */
77341 static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
77342   int nByte;
77343   u8 aByte[10];
77344   nByte = sqlite3PutVarint(aByte, iVal);
77345   vdbePmaWriteBlob(p, aByte, nByte);
77346 }
77347 
77348 /*
77349 ** Write the current contents of in-memory linked-list pList to a level-0
77350 ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
77351 ** successful, or an SQLite error code otherwise.
77352 **
77353 ** The format of a PMA is:
77354 **
77355 **     * A varint. This varint contains the total number of bytes of content
77356 **       in the PMA (not including the varint itself).
77357 **
77358 **     * One or more records packed end-to-end in order of ascending keys.
77359 **       Each record consists of a varint followed by a blob of data (the
77360 **       key). The varint is the number of bytes in the blob of data.
77361 */
77362 static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
77363   sqlite3 *db = pTask->pSorter->db;
77364   int rc = SQLITE_OK;             /* Return code */
77365   PmaWriter writer;               /* Object used to write to the file */
77366 
77367 #ifdef SQLITE_DEBUG
77368   /* Set iSz to the expected size of file pTask->file after writing the PMA.
77369   ** This is used by an assert() statement at the end of this function.  */
77370   i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
77371 #endif
77372 
77373   vdbeSorterWorkDebug(pTask, "enter");
77374   memset(&writer, 0, sizeof(PmaWriter));
77375   assert( pList->szPMA>0 );
77376 
77377   /* If the first temporary PMA file has not been opened, open it now. */
77378   if( pTask->file.pFd==0 ){
77379     rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
77380     assert( rc!=SQLITE_OK || pTask->file.pFd );
77381     assert( pTask->file.iEof==0 );
77382     assert( pTask->nPMA==0 );
77383   }
77384 
77385   /* Try to get the file to memory map */
77386   if( rc==SQLITE_OK ){
77387     vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
77388   }
77389 
77390   /* Sort the list */
77391   if( rc==SQLITE_OK ){
77392     rc = vdbeSorterSort(pTask, pList);
77393   }
77394 
77395   if( rc==SQLITE_OK ){
77396     SorterRecord *p;
77397     SorterRecord *pNext = 0;
77398 
77399     vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
77400                       pTask->file.iEof);
77401     pTask->nPMA++;
77402     vdbePmaWriteVarint(&writer, pList->szPMA);
77403     for(p=pList->pList; p; p=pNext){
77404       pNext = p->u.pNext;
77405       vdbePmaWriteVarint(&writer, p->nVal);
77406       vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
77407       if( pList->aMemory==0 ) sqlite3_free(p);
77408     }
77409     pList->pList = p;
77410     rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
77411   }
77412 
77413   vdbeSorterWorkDebug(pTask, "exit");
77414   assert( rc!=SQLITE_OK || pList->pList==0 );
77415   assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
77416   return rc;
77417 }
77418 
77419 /*
77420 ** Advance the MergeEngine to its next entry.
77421 ** Set *pbEof to true there is no next entry because
77422 ** the MergeEngine has reached the end of all its inputs.
77423 **
77424 ** Return SQLITE_OK if successful or an error code if an error occurs.
77425 */
77426 static int vdbeMergeEngineStep(
77427   MergeEngine *pMerger,      /* The merge engine to advance to the next row */
77428   int *pbEof                 /* Set TRUE at EOF.  Set false for more content */
77429 ){
77430   int rc;
77431   int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
77432   SortSubtask *pTask = pMerger->pTask;
77433 
77434   /* Advance the current PmaReader */
77435   rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
77436 
77437   /* Update contents of aTree[] */
77438   if( rc==SQLITE_OK ){
77439     int i;                      /* Index of aTree[] to recalculate */
77440     PmaReader *pReadr1;         /* First PmaReader to compare */
77441     PmaReader *pReadr2;         /* Second PmaReader to compare */
77442     u8 *pKey2;                  /* To pReadr2->aKey, or 0 if record cached */
77443 
77444     /* Find the first two PmaReaders to compare. The one that was just
77445     ** advanced (iPrev) and the one next to it in the array.  */
77446     pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
77447     pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
77448     pKey2 = pReadr2->aKey;
77449 
77450     for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
77451       /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
77452       int iRes;
77453       if( pReadr1->pFd==0 ){
77454         iRes = +1;
77455       }else if( pReadr2->pFd==0 ){
77456         iRes = -1;
77457       }else{
77458         iRes = vdbeSorterCompare(pTask,
77459             pReadr1->aKey, pReadr1->nKey, pKey2, pReadr2->nKey
77460         );
77461       }
77462 
77463       /* If pReadr1 contained the smaller value, set aTree[i] to its index.
77464       ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
77465       ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
77466       ** pKey2 to point to the record belonging to pReadr2.
77467       **
77468       ** Alternatively, if pReadr2 contains the smaller of the two values,
77469       ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
77470       ** was actually called above, then pTask->pUnpacked now contains
77471       ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
77472       ** vdbeSorterCompare() from decoding pReadr2 again.
77473       **
77474       ** If the two values were equal, then the value from the oldest
77475       ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
77476       ** is sorted from oldest to newest, so pReadr1 contains older values
77477       ** than pReadr2 iff (pReadr1<pReadr2).  */
77478       if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
77479         pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
77480         pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
77481         pKey2 = pReadr2->aKey;
77482       }else{
77483         if( pReadr1->pFd ) pKey2 = 0;
77484         pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
77485         pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
77486       }
77487     }
77488     *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
77489   }
77490 
77491   return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
77492 }
77493 
77494 #if SQLITE_MAX_WORKER_THREADS>0
77495 /*
77496 ** The main routine for background threads that write level-0 PMAs.
77497 */
77498 static void *vdbeSorterFlushThread(void *pCtx){
77499   SortSubtask *pTask = (SortSubtask*)pCtx;
77500   int rc;                         /* Return code */
77501   assert( pTask->bDone==0 );
77502   rc = vdbeSorterListToPMA(pTask, &pTask->list);
77503   pTask->bDone = 1;
77504   return SQLITE_INT_TO_PTR(rc);
77505 }
77506 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
77507 
77508 /*
77509 ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
77510 ** using a background thread.
77511 */
77512 static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
77513 #if SQLITE_MAX_WORKER_THREADS==0
77514   pSorter->bUsePMA = 1;
77515   return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
77516 #else
77517   int rc = SQLITE_OK;
77518   int i;
77519   SortSubtask *pTask = 0;    /* Thread context used to create new PMA */
77520   int nWorker = (pSorter->nTask-1);
77521 
77522   /* Set the flag to indicate that at least one PMA has been written.
77523   ** Or will be, anyhow.  */
77524   pSorter->bUsePMA = 1;
77525 
77526   /* Select a sub-task to sort and flush the current list of in-memory
77527   ** records to disk. If the sorter is running in multi-threaded mode,
77528   ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
77529   ** the background thread from a sub-tasks previous turn is still running,
77530   ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
77531   ** fall back to using the final sub-task. The first (pSorter->nTask-1)
77532   ** sub-tasks are prefered as they use background threads - the final
77533   ** sub-task uses the main thread. */
77534   for(i=0; i<nWorker; i++){
77535     int iTest = (pSorter->iPrev + i + 1) % nWorker;
77536     pTask = &pSorter->aTask[iTest];
77537     if( pTask->bDone ){
77538       rc = vdbeSorterJoinThread(pTask);
77539     }
77540     if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
77541   }
77542 
77543   if( rc==SQLITE_OK ){
77544     if( i==nWorker ){
77545       /* Use the foreground thread for this operation */
77546       rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
77547     }else{
77548       /* Launch a background thread for this operation */
77549       u8 *aMem = pTask->list.aMemory;
77550       void *pCtx = (void*)pTask;
77551 
77552       assert( pTask->pThread==0 && pTask->bDone==0 );
77553       assert( pTask->list.pList==0 );
77554       assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
77555 
77556       pSorter->iPrev = (u8)(pTask - pSorter->aTask);
77557       pTask->list = pSorter->list;
77558       pSorter->list.pList = 0;
77559       pSorter->list.szPMA = 0;
77560       if( aMem ){
77561         pSorter->list.aMemory = aMem;
77562         pSorter->nMemory = sqlite3MallocSize(aMem);
77563       }else if( pSorter->list.aMemory ){
77564         pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
77565         if( !pSorter->list.aMemory ) return SQLITE_NOMEM;
77566       }
77567 
77568       rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
77569     }
77570   }
77571 
77572   return rc;
77573 #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
77574 }
77575 
77576 /*
77577 ** Add a record to the sorter.
77578 */
77579 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
77580   const VdbeCursor *pCsr,         /* Sorter cursor */
77581   Mem *pVal                       /* Memory cell containing record */
77582 ){
77583   VdbeSorter *pSorter = pCsr->pSorter;
77584   int rc = SQLITE_OK;             /* Return Code */
77585   SorterRecord *pNew;             /* New list element */
77586 
77587   int bFlush;                     /* True to flush contents of memory to PMA */
77588   int nReq;                       /* Bytes of memory required */
77589   int nPMA;                       /* Bytes of PMA space required */
77590 
77591   assert( pSorter );
77592 
77593   /* Figure out whether or not the current contents of memory should be
77594   ** flushed to a PMA before continuing. If so, do so.
77595   **
77596   ** If using the single large allocation mode (pSorter->aMemory!=0), then
77597   ** flush the contents of memory to a new PMA if (a) at least one value is
77598   ** already in memory and (b) the new value will not fit in memory.
77599   **
77600   ** Or, if using separate allocations for each record, flush the contents
77601   ** of memory to a PMA if either of the following are true:
77602   **
77603   **   * The total memory allocated for the in-memory list is greater
77604   **     than (page-size * cache-size), or
77605   **
77606   **   * The total memory allocated for the in-memory list is greater
77607   **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
77608   */
77609   nReq = pVal->n + sizeof(SorterRecord);
77610   nPMA = pVal->n + sqlite3VarintLen(pVal->n);
77611   if( pSorter->mxPmaSize ){
77612     if( pSorter->list.aMemory ){
77613       bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
77614     }else{
77615       bFlush = (
77616           (pSorter->list.szPMA > pSorter->mxPmaSize)
77617        || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
77618       );
77619     }
77620     if( bFlush ){
77621       rc = vdbeSorterFlushPMA(pSorter);
77622       pSorter->list.szPMA = 0;
77623       pSorter->iMemory = 0;
77624       assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
77625     }
77626   }
77627 
77628   pSorter->list.szPMA += nPMA;
77629   if( nPMA>pSorter->mxKeysize ){
77630     pSorter->mxKeysize = nPMA;
77631   }
77632 
77633   if( pSorter->list.aMemory ){
77634     int nMin = pSorter->iMemory + nReq;
77635 
77636     if( nMin>pSorter->nMemory ){
77637       u8 *aNew;
77638       int nNew = pSorter->nMemory * 2;
77639       while( nNew < nMin ) nNew = nNew*2;
77640       if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
77641       if( nNew < nMin ) nNew = nMin;
77642 
77643       aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
77644       if( !aNew ) return SQLITE_NOMEM;
77645       pSorter->list.pList = (SorterRecord*)(
77646           aNew + ((u8*)pSorter->list.pList - pSorter->list.aMemory)
77647       );
77648       pSorter->list.aMemory = aNew;
77649       pSorter->nMemory = nNew;
77650     }
77651 
77652     pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
77653     pSorter->iMemory += ROUND8(nReq);
77654     pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
77655   }else{
77656     pNew = (SorterRecord *)sqlite3Malloc(nReq);
77657     if( pNew==0 ){
77658       return SQLITE_NOMEM;
77659     }
77660     pNew->u.pNext = pSorter->list.pList;
77661   }
77662 
77663   memcpy(SRVAL(pNew), pVal->z, pVal->n);
77664   pNew->nVal = pVal->n;
77665   pSorter->list.pList = pNew;
77666 
77667   return rc;
77668 }
77669 
77670 /*
77671 ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
77672 ** of the data stored in aFile[1] is the same as that used by regular PMAs,
77673 ** except that the number-of-bytes varint is omitted from the start.
77674 */
77675 static int vdbeIncrPopulate(IncrMerger *pIncr){
77676   int rc = SQLITE_OK;
77677   int rc2;
77678   i64 iStart = pIncr->iStartOff;
77679   SorterFile *pOut = &pIncr->aFile[1];
77680   SortSubtask *pTask = pIncr->pTask;
77681   MergeEngine *pMerger = pIncr->pMerger;
77682   PmaWriter writer;
77683   assert( pIncr->bEof==0 );
77684 
77685   vdbeSorterPopulateDebug(pTask, "enter");
77686 
77687   vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
77688   while( rc==SQLITE_OK ){
77689     int dummy;
77690     PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
77691     int nKey = pReader->nKey;
77692     i64 iEof = writer.iWriteOff + writer.iBufEnd;
77693 
77694     /* Check if the output file is full or if the input has been exhausted.
77695     ** In either case exit the loop. */
77696     if( pReader->pFd==0 ) break;
77697     if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
77698 
77699     /* Write the next key to the output. */
77700     vdbePmaWriteVarint(&writer, nKey);
77701     vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
77702     assert( pIncr->pMerger->pTask==pTask );
77703     rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
77704   }
77705 
77706   rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
77707   if( rc==SQLITE_OK ) rc = rc2;
77708   vdbeSorterPopulateDebug(pTask, "exit");
77709   return rc;
77710 }
77711 
77712 #if SQLITE_MAX_WORKER_THREADS>0
77713 /*
77714 ** The main routine for background threads that populate aFile[1] of
77715 ** multi-threaded IncrMerger objects.
77716 */
77717 static void *vdbeIncrPopulateThread(void *pCtx){
77718   IncrMerger *pIncr = (IncrMerger*)pCtx;
77719   void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
77720   pIncr->pTask->bDone = 1;
77721   return pRet;
77722 }
77723 
77724 /*
77725 ** Launch a background thread to populate aFile[1] of pIncr.
77726 */
77727 static int vdbeIncrBgPopulate(IncrMerger *pIncr){
77728   void *p = (void*)pIncr;
77729   assert( pIncr->bUseThread );
77730   return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
77731 }
77732 #endif
77733 
77734 /*
77735 ** This function is called when the PmaReader corresponding to pIncr has
77736 ** finished reading the contents of aFile[0]. Its purpose is to "refill"
77737 ** aFile[0] such that the PmaReader should start rereading it from the
77738 ** beginning.
77739 **
77740 ** For single-threaded objects, this is accomplished by literally reading
77741 ** keys from pIncr->pMerger and repopulating aFile[0].
77742 **
77743 ** For multi-threaded objects, all that is required is to wait until the
77744 ** background thread is finished (if it is not already) and then swap
77745 ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
77746 ** been exhausted, this function also launches a new background thread
77747 ** to populate the new aFile[1].
77748 **
77749 ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
77750 */
77751 static int vdbeIncrSwap(IncrMerger *pIncr){
77752   int rc = SQLITE_OK;
77753 
77754 #if SQLITE_MAX_WORKER_THREADS>0
77755   if( pIncr->bUseThread ){
77756     rc = vdbeSorterJoinThread(pIncr->pTask);
77757 
77758     if( rc==SQLITE_OK ){
77759       SorterFile f0 = pIncr->aFile[0];
77760       pIncr->aFile[0] = pIncr->aFile[1];
77761       pIncr->aFile[1] = f0;
77762     }
77763 
77764     if( rc==SQLITE_OK ){
77765       if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
77766         pIncr->bEof = 1;
77767       }else{
77768         rc = vdbeIncrBgPopulate(pIncr);
77769       }
77770     }
77771   }else
77772 #endif
77773   {
77774     rc = vdbeIncrPopulate(pIncr);
77775     pIncr->aFile[0] = pIncr->aFile[1];
77776     if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
77777       pIncr->bEof = 1;
77778     }
77779   }
77780 
77781   return rc;
77782 }
77783 
77784 /*
77785 ** Allocate and return a new IncrMerger object to read data from pMerger.
77786 **
77787 ** If an OOM condition is encountered, return NULL. In this case free the
77788 ** pMerger argument before returning.
77789 */
77790 static int vdbeIncrMergerNew(
77791   SortSubtask *pTask,     /* The thread that will be using the new IncrMerger */
77792   MergeEngine *pMerger,   /* The MergeEngine that the IncrMerger will control */
77793   IncrMerger **ppOut      /* Write the new IncrMerger here */
77794 ){
77795   int rc = SQLITE_OK;
77796   IncrMerger *pIncr = *ppOut = (IncrMerger*)
77797        (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
77798   if( pIncr ){
77799     pIncr->pMerger = pMerger;
77800     pIncr->pTask = pTask;
77801     pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
77802     pTask->file2.iEof += pIncr->mxSz;
77803   }else{
77804     vdbeMergeEngineFree(pMerger);
77805     rc = SQLITE_NOMEM;
77806   }
77807   return rc;
77808 }
77809 
77810 #if SQLITE_MAX_WORKER_THREADS>0
77811 /*
77812 ** Set the "use-threads" flag on object pIncr.
77813 */
77814 static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
77815   pIncr->bUseThread = 1;
77816   pIncr->pTask->file2.iEof -= pIncr->mxSz;
77817 }
77818 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
77819 
77820 
77821 
77822 /*
77823 ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
77824 ** two PmaReaders that feed that entry.  Neither of the PmaReaders
77825 ** are advanced.  This routine merely does the comparison.
77826 */
77827 static void vdbeMergeEngineCompare(
77828   MergeEngine *pMerger,  /* Merge engine containing PmaReaders to compare */
77829   int iOut               /* Store the result in pMerger->aTree[iOut] */
77830 ){
77831   int i1;
77832   int i2;
77833   int iRes;
77834   PmaReader *p1;
77835   PmaReader *p2;
77836 
77837   assert( iOut<pMerger->nTree && iOut>0 );
77838 
77839   if( iOut>=(pMerger->nTree/2) ){
77840     i1 = (iOut - pMerger->nTree/2) * 2;
77841     i2 = i1 + 1;
77842   }else{
77843     i1 = pMerger->aTree[iOut*2];
77844     i2 = pMerger->aTree[iOut*2+1];
77845   }
77846 
77847   p1 = &pMerger->aReadr[i1];
77848   p2 = &pMerger->aReadr[i2];
77849 
77850   if( p1->pFd==0 ){
77851     iRes = i2;
77852   }else if( p2->pFd==0 ){
77853     iRes = i1;
77854   }else{
77855     int res;
77856     assert( pMerger->pTask->pUnpacked!=0 );  /* from vdbeSortSubtaskMain() */
77857     res = vdbeSorterCompare(
77858         pMerger->pTask, p1->aKey, p1->nKey, p2->aKey, p2->nKey
77859     );
77860     if( res<=0 ){
77861       iRes = i1;
77862     }else{
77863       iRes = i2;
77864     }
77865   }
77866 
77867   pMerger->aTree[iOut] = iRes;
77868 }
77869 
77870 /*
77871 ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
77872 ** and vdbePmaReaderIncrMergeInit().
77873 **
77874 ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
77875 ** SQLITE_MAX_WORKER_THREADS==0).  The other values are only used
77876 ** when there exists one or more separate worker threads.
77877 */
77878 #define INCRINIT_NORMAL 0
77879 #define INCRINIT_TASK   1
77880 #define INCRINIT_ROOT   2
77881 
77882 /* Forward reference.
77883 ** The vdbeIncrMergeInit() and vdbePmaReaderIncrMergeInit() routines call each
77884 ** other (when building a merge tree).
77885 */
77886 static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode);
77887 
77888 /*
77889 ** Initialize the MergeEngine object passed as the second argument. Once this
77890 ** function returns, the first key of merged data may be read from the
77891 ** MergeEngine object in the usual fashion.
77892 **
77893 ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
77894 ** objects attached to the PmaReader objects that the merger reads from have
77895 ** already been populated, but that they have not yet populated aFile[0] and
77896 ** set the PmaReader objects up to read from it. In this case all that is
77897 ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
77898 ** its first key.
77899 **
77900 ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
77901 ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
77902 ** to pMerger.
77903 **
77904 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
77905 */
77906 static int vdbeMergeEngineInit(
77907   SortSubtask *pTask,             /* Thread that will run pMerger */
77908   MergeEngine *pMerger,           /* MergeEngine to initialize */
77909   int eMode                       /* One of the INCRINIT_XXX constants */
77910 ){
77911   int rc = SQLITE_OK;             /* Return code */
77912   int i;                          /* For looping over PmaReader objects */
77913   int nTree = pMerger->nTree;
77914 
77915   /* eMode is always INCRINIT_NORMAL in single-threaded mode */
77916   assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
77917 
77918   /* Verify that the MergeEngine is assigned to a single thread */
77919   assert( pMerger->pTask==0 );
77920   pMerger->pTask = pTask;
77921 
77922   for(i=0; i<nTree; i++){
77923     if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
77924       /* PmaReaders should be normally initialized in order, as if they are
77925       ** reading from the same temp file this makes for more linear file IO.
77926       ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
77927       ** in use it will block the vdbePmaReaderNext() call while it uses
77928       ** the main thread to fill its buffer. So calling PmaReaderNext()
77929       ** on this PmaReader before any of the multi-threaded PmaReaders takes
77930       ** better advantage of multi-processor hardware. */
77931       rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
77932     }else{
77933       rc = vdbePmaReaderIncrMergeInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
77934     }
77935     if( rc!=SQLITE_OK ) return rc;
77936   }
77937 
77938   for(i=pMerger->nTree-1; i>0; i--){
77939     vdbeMergeEngineCompare(pMerger, i);
77940   }
77941   return pTask->pUnpacked->errCode;
77942 }
77943 
77944 /*
77945 ** Initialize the IncrMerge field of a PmaReader.
77946 **
77947 ** If the PmaReader passed as the first argument is not an incremental-reader
77948 ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it serves
77949 ** to open and/or initialize the temp file related fields of the IncrMerge
77950 ** object at (pReadr->pIncr).
77951 **
77952 ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
77953 ** in the sub-tree headed by pReadr are also initialized. Data is then loaded
77954 ** into the buffers belonging to pReadr and it is set to
77955 ** point to the first key in its range.
77956 **
77957 ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
77958 ** to be a multi-threaded PmaReader and this function is being called in a
77959 ** background thread. In this case all PmaReaders in the sub-tree are
77960 ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
77961 ** pReadr is populated. However, pReadr itself is not set up to point
77962 ** to its first key. A call to vdbePmaReaderNext() is still required to do
77963 ** that.
77964 **
77965 ** The reason this function does not call vdbePmaReaderNext() immediately
77966 ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
77967 ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
77968 ** this entire function is being run by thread (pTask->thread), that will
77969 ** lead to the current background thread attempting to join itself.
77970 **
77971 ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
77972 ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
77973 ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
77974 ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
77975 ** the current PmaReader set to point to the first key in its range.
77976 **
77977 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
77978 */
77979 static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
77980   int rc = SQLITE_OK;
77981   IncrMerger *pIncr = pReadr->pIncr;
77982 
77983   /* eMode is always INCRINIT_NORMAL in single-threaded mode */
77984   assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
77985 
77986   if( pIncr ){
77987     SortSubtask *pTask = pIncr->pTask;
77988     sqlite3 *db = pTask->pSorter->db;
77989 
77990     rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
77991 
77992     /* Set up the required files for pIncr. A multi-theaded IncrMerge object
77993     ** requires two temp files to itself, whereas a single-threaded object
77994     ** only requires a region of pTask->file2. */
77995     if( rc==SQLITE_OK ){
77996       int mxSz = pIncr->mxSz;
77997 #if SQLITE_MAX_WORKER_THREADS>0
77998       if( pIncr->bUseThread ){
77999         rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
78000         if( rc==SQLITE_OK ){
78001           rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
78002         }
78003       }else
78004 #endif
78005       /*if( !pIncr->bUseThread )*/{
78006         if( pTask->file2.pFd==0 ){
78007           assert( pTask->file2.iEof>0 );
78008           rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
78009           pTask->file2.iEof = 0;
78010         }
78011         if( rc==SQLITE_OK ){
78012           pIncr->aFile[1].pFd = pTask->file2.pFd;
78013           pIncr->iStartOff = pTask->file2.iEof;
78014           pTask->file2.iEof += mxSz;
78015         }
78016       }
78017     }
78018 
78019 #if SQLITE_MAX_WORKER_THREADS>0
78020     if( rc==SQLITE_OK && pIncr->bUseThread ){
78021       /* Use the current thread to populate aFile[1], even though this
78022       ** PmaReader is multi-threaded. The reason being that this function
78023       ** is already running in background thread pIncr->pTask->thread. */
78024       assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
78025       rc = vdbeIncrPopulate(pIncr);
78026     }
78027 #endif
78028 
78029     if( rc==SQLITE_OK
78030      && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK)
78031     ){
78032       rc = vdbePmaReaderNext(pReadr);
78033     }
78034   }
78035   return rc;
78036 }
78037 
78038 #if SQLITE_MAX_WORKER_THREADS>0
78039 /*
78040 ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
78041 ** background threads.
78042 */
78043 static void *vdbePmaReaderBgInit(void *pCtx){
78044   PmaReader *pReader = (PmaReader*)pCtx;
78045   void *pRet = SQLITE_INT_TO_PTR(
78046                   vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
78047                );
78048   pReader->pIncr->pTask->bDone = 1;
78049   return pRet;
78050 }
78051 
78052 /*
78053 ** Use a background thread to invoke vdbePmaReaderIncrMergeInit(INCRINIT_TASK)
78054 ** on the PmaReader object passed as the first argument.
78055 **
78056 ** This call will initialize the various fields of the pReadr->pIncr
78057 ** structure and, if it is a multi-threaded IncrMerger, launch a
78058 ** background thread to populate aFile[1].
78059 */
78060 static int vdbePmaReaderBgIncrInit(PmaReader *pReadr){
78061   void *pCtx = (void*)pReadr;
78062   return vdbeSorterCreateThread(pReadr->pIncr->pTask, vdbePmaReaderBgInit, pCtx);
78063 }
78064 #endif
78065 
78066 /*
78067 ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
78068 ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
78069 ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
78070 ** to NULL and return an SQLite error code.
78071 **
78072 ** When this function is called, *piOffset is set to the offset of the
78073 ** first PMA to read from pTask->file. Assuming no error occurs, it is
78074 ** set to the offset immediately following the last byte of the last
78075 ** PMA before returning. If an error does occur, then the final value of
78076 ** *piOffset is undefined.
78077 */
78078 static int vdbeMergeEngineLevel0(
78079   SortSubtask *pTask,             /* Sorter task to read from */
78080   int nPMA,                       /* Number of PMAs to read */
78081   i64 *piOffset,                  /* IN/OUT: Readr offset in pTask->file */
78082   MergeEngine **ppOut             /* OUT: New merge-engine */
78083 ){
78084   MergeEngine *pNew;              /* Merge engine to return */
78085   i64 iOff = *piOffset;
78086   int i;
78087   int rc = SQLITE_OK;
78088 
78089   *ppOut = pNew = vdbeMergeEngineNew(nPMA);
78090   if( pNew==0 ) rc = SQLITE_NOMEM;
78091 
78092   for(i=0; i<nPMA && rc==SQLITE_OK; i++){
78093     i64 nDummy;
78094     PmaReader *pReadr = &pNew->aReadr[i];
78095     rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
78096     iOff = pReadr->iEof;
78097   }
78098 
78099   if( rc!=SQLITE_OK ){
78100     vdbeMergeEngineFree(pNew);
78101     *ppOut = 0;
78102   }
78103   *piOffset = iOff;
78104   return rc;
78105 }
78106 
78107 /*
78108 ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
78109 ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
78110 **
78111 ** i.e.
78112 **
78113 **   nPMA<=16    -> TreeDepth() == 0
78114 **   nPMA<=256   -> TreeDepth() == 1
78115 **   nPMA<=65536 -> TreeDepth() == 2
78116 */
78117 static int vdbeSorterTreeDepth(int nPMA){
78118   int nDepth = 0;
78119   i64 nDiv = SORTER_MAX_MERGE_COUNT;
78120   while( nDiv < (i64)nPMA ){
78121     nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
78122     nDepth++;
78123   }
78124   return nDepth;
78125 }
78126 
78127 /*
78128 ** pRoot is the root of an incremental merge-tree with depth nDepth (according
78129 ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
78130 ** tree, counting from zero. This function adds pLeaf to the tree.
78131 **
78132 ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
78133 ** code is returned and pLeaf is freed.
78134 */
78135 static int vdbeSorterAddToTree(
78136   SortSubtask *pTask,             /* Task context */
78137   int nDepth,                     /* Depth of tree according to TreeDepth() */
78138   int iSeq,                       /* Sequence number of leaf within tree */
78139   MergeEngine *pRoot,             /* Root of tree */
78140   MergeEngine *pLeaf              /* Leaf to add to tree */
78141 ){
78142   int rc = SQLITE_OK;
78143   int nDiv = 1;
78144   int i;
78145   MergeEngine *p = pRoot;
78146   IncrMerger *pIncr;
78147 
78148   rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
78149 
78150   for(i=1; i<nDepth; i++){
78151     nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
78152   }
78153 
78154   for(i=1; i<nDepth && rc==SQLITE_OK; i++){
78155     int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
78156     PmaReader *pReadr = &p->aReadr[iIter];
78157 
78158     if( pReadr->pIncr==0 ){
78159       MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
78160       if( pNew==0 ){
78161         rc = SQLITE_NOMEM;
78162       }else{
78163         rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
78164       }
78165     }
78166     if( rc==SQLITE_OK ){
78167       p = pReadr->pIncr->pMerger;
78168       nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
78169     }
78170   }
78171 
78172   if( rc==SQLITE_OK ){
78173     p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
78174   }else{
78175     vdbeIncrFree(pIncr);
78176   }
78177   return rc;
78178 }
78179 
78180 /*
78181 ** This function is called as part of a SorterRewind() operation on a sorter
78182 ** that has already written two or more level-0 PMAs to one or more temp
78183 ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
78184 ** can be used to incrementally merge all PMAs on disk.
78185 **
78186 ** If successful, SQLITE_OK is returned and *ppOut set to point to the
78187 ** MergeEngine object at the root of the tree before returning. Or, if an
78188 ** error occurs, an SQLite error code is returned and the final value
78189 ** of *ppOut is undefined.
78190 */
78191 static int vdbeSorterMergeTreeBuild(
78192   VdbeSorter *pSorter,       /* The VDBE cursor that implements the sort */
78193   MergeEngine **ppOut        /* Write the MergeEngine here */
78194 ){
78195   MergeEngine *pMain = 0;
78196   int rc = SQLITE_OK;
78197   int iTask;
78198 
78199 #if SQLITE_MAX_WORKER_THREADS>0
78200   /* If the sorter uses more than one task, then create the top-level
78201   ** MergeEngine here. This MergeEngine will read data from exactly
78202   ** one PmaReader per sub-task.  */
78203   assert( pSorter->bUseThreads || pSorter->nTask==1 );
78204   if( pSorter->nTask>1 ){
78205     pMain = vdbeMergeEngineNew(pSorter->nTask);
78206     if( pMain==0 ) rc = SQLITE_NOMEM;
78207   }
78208 #endif
78209 
78210   for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
78211     SortSubtask *pTask = &pSorter->aTask[iTask];
78212     assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
78213     if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
78214       MergeEngine *pRoot = 0;     /* Root node of tree for this task */
78215       int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
78216       i64 iReadOff = 0;
78217 
78218       if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
78219         rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
78220       }else{
78221         int i;
78222         int iSeq = 0;
78223         pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
78224         if( pRoot==0 ) rc = SQLITE_NOMEM;
78225         for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
78226           MergeEngine *pMerger = 0; /* New level-0 PMA merger */
78227           int nReader;              /* Number of level-0 PMAs to merge */
78228 
78229           nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
78230           rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
78231           if( rc==SQLITE_OK ){
78232             rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
78233           }
78234         }
78235       }
78236 
78237       if( rc==SQLITE_OK ){
78238 #if SQLITE_MAX_WORKER_THREADS>0
78239         if( pMain!=0 ){
78240           rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
78241         }else
78242 #endif
78243         {
78244           assert( pMain==0 );
78245           pMain = pRoot;
78246         }
78247       }else{
78248         vdbeMergeEngineFree(pRoot);
78249       }
78250     }
78251   }
78252 
78253   if( rc!=SQLITE_OK ){
78254     vdbeMergeEngineFree(pMain);
78255     pMain = 0;
78256   }
78257   *ppOut = pMain;
78258   return rc;
78259 }
78260 
78261 /*
78262 ** This function is called as part of an sqlite3VdbeSorterRewind() operation
78263 ** on a sorter that has written two or more PMAs to temporary files. It sets
78264 ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
78265 ** (for multi-threaded sorters) so that it can be used to iterate through
78266 ** all records stored in the sorter.
78267 **
78268 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
78269 */
78270 static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
78271   int rc;                         /* Return code */
78272   SortSubtask *pTask0 = &pSorter->aTask[0];
78273   MergeEngine *pMain = 0;
78274 #if SQLITE_MAX_WORKER_THREADS
78275   sqlite3 *db = pTask0->pSorter->db;
78276 #endif
78277 
78278   rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
78279   if( rc==SQLITE_OK ){
78280 #if SQLITE_MAX_WORKER_THREADS
78281     assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
78282     if( pSorter->bUseThreads ){
78283       int iTask;
78284       PmaReader *pReadr = 0;
78285       SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
78286       rc = vdbeSortAllocUnpacked(pLast);
78287       if( rc==SQLITE_OK ){
78288         pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
78289         pSorter->pReader = pReadr;
78290         if( pReadr==0 ) rc = SQLITE_NOMEM;
78291       }
78292       if( rc==SQLITE_OK ){
78293         rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
78294         if( rc==SQLITE_OK ){
78295           vdbeIncrMergerSetThreads(pReadr->pIncr);
78296           for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
78297             IncrMerger *pIncr;
78298             if( (pIncr = pMain->aReadr[iTask].pIncr) ){
78299               vdbeIncrMergerSetThreads(pIncr);
78300               assert( pIncr->pTask!=pLast );
78301             }
78302           }
78303           for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
78304             PmaReader *p = &pMain->aReadr[iTask];
78305             assert( p->pIncr==0 || p->pIncr->pTask==&pSorter->aTask[iTask] );
78306             if( p->pIncr ){
78307               if( iTask==pSorter->nTask-1 ){
78308                 rc = vdbePmaReaderIncrMergeInit(p, INCRINIT_TASK);
78309               }else{
78310                 rc = vdbePmaReaderBgIncrInit(p);
78311               }
78312             }
78313           }
78314         }
78315         pMain = 0;
78316       }
78317       if( rc==SQLITE_OK ){
78318         rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
78319       }
78320     }else
78321 #endif
78322     {
78323       rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
78324       pSorter->pMerger = pMain;
78325       pMain = 0;
78326     }
78327   }
78328 
78329   if( rc!=SQLITE_OK ){
78330     vdbeMergeEngineFree(pMain);
78331   }
78332   return rc;
78333 }
78334 
78335 
78336 /*
78337 ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
78338 ** this function is called to prepare for iterating through the records
78339 ** in sorted order.
78340 */
78341 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
78342   VdbeSorter *pSorter = pCsr->pSorter;
78343   int rc = SQLITE_OK;             /* Return code */
78344 
78345   assert( pSorter );
78346 
78347   /* If no data has been written to disk, then do not do so now. Instead,
78348   ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
78349   ** from the in-memory list.  */
78350   if( pSorter->bUsePMA==0 ){
78351     if( pSorter->list.pList ){
78352       *pbEof = 0;
78353       rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
78354     }else{
78355       *pbEof = 1;
78356     }
78357     return rc;
78358   }
78359 
78360   /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
78361   ** function flushes the contents of memory to disk, it immediately always
78362   ** creates a new list consisting of a single key immediately afterwards.
78363   ** So the list is never empty at this point.  */
78364   assert( pSorter->list.pList );
78365   rc = vdbeSorterFlushPMA(pSorter);
78366 
78367   /* Join all threads */
78368   rc = vdbeSorterJoinAll(pSorter, rc);
78369 
78370   vdbeSorterRewindDebug("rewind");
78371 
78372   /* Assuming no errors have occurred, set up a merger structure to
78373   ** incrementally read and merge all remaining PMAs.  */
78374   assert( pSorter->pReader==0 );
78375   if( rc==SQLITE_OK ){
78376     rc = vdbeSorterSetupMerge(pSorter);
78377     *pbEof = 0;
78378   }
78379 
78380   vdbeSorterRewindDebug("rewinddone");
78381   return rc;
78382 }
78383 
78384 /*
78385 ** Advance to the next element in the sorter.
78386 */
78387 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
78388   VdbeSorter *pSorter = pCsr->pSorter;
78389   int rc;                         /* Return code */
78390 
78391   assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
78392   if( pSorter->bUsePMA ){
78393     assert( pSorter->pReader==0 || pSorter->pMerger==0 );
78394     assert( pSorter->bUseThreads==0 || pSorter->pReader );
78395     assert( pSorter->bUseThreads==1 || pSorter->pMerger );
78396 #if SQLITE_MAX_WORKER_THREADS>0
78397     if( pSorter->bUseThreads ){
78398       rc = vdbePmaReaderNext(pSorter->pReader);
78399       *pbEof = (pSorter->pReader->pFd==0);
78400     }else
78401 #endif
78402     /*if( !pSorter->bUseThreads )*/ {
78403       assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
78404       rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof);
78405     }
78406   }else{
78407     SorterRecord *pFree = pSorter->list.pList;
78408     pSorter->list.pList = pFree->u.pNext;
78409     pFree->u.pNext = 0;
78410     if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
78411     *pbEof = !pSorter->list.pList;
78412     rc = SQLITE_OK;
78413   }
78414   return rc;
78415 }
78416 
78417 /*
78418 ** Return a pointer to a buffer owned by the sorter that contains the
78419 ** current key.
78420 */
78421 static void *vdbeSorterRowkey(
78422   const VdbeSorter *pSorter,      /* Sorter object */
78423   int *pnKey                      /* OUT: Size of current key in bytes */
78424 ){
78425   void *pKey;
78426   if( pSorter->bUsePMA ){
78427     PmaReader *pReader;
78428 #if SQLITE_MAX_WORKER_THREADS>0
78429     if( pSorter->bUseThreads ){
78430       pReader = pSorter->pReader;
78431     }else
78432 #endif
78433     /*if( !pSorter->bUseThreads )*/{
78434       pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
78435     }
78436     *pnKey = pReader->nKey;
78437     pKey = pReader->aKey;
78438   }else{
78439     *pnKey = pSorter->list.pList->nVal;
78440     pKey = SRVAL(pSorter->list.pList);
78441   }
78442   return pKey;
78443 }
78444 
78445 /*
78446 ** Copy the current sorter key into the memory cell pOut.
78447 */
78448 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
78449   VdbeSorter *pSorter = pCsr->pSorter;
78450   void *pKey; int nKey;           /* Sorter key to copy into pOut */
78451 
78452   pKey = vdbeSorterRowkey(pSorter, &nKey);
78453   if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
78454     return SQLITE_NOMEM;
78455   }
78456   pOut->n = nKey;
78457   MemSetTypeFlag(pOut, MEM_Blob);
78458   memcpy(pOut->z, pKey, nKey);
78459 
78460   return SQLITE_OK;
78461 }
78462 
78463 /*
78464 ** Compare the key in memory cell pVal with the key that the sorter cursor
78465 ** passed as the first argument currently points to. For the purposes of
78466 ** the comparison, ignore the rowid field at the end of each record.
78467 **
78468 ** If the sorter cursor key contains any NULL values, consider it to be
78469 ** less than pVal. Even if pVal also contains NULL values.
78470 **
78471 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
78472 ** Otherwise, set *pRes to a negative, zero or positive value if the
78473 ** key in pVal is smaller than, equal to or larger than the current sorter
78474 ** key.
78475 **
78476 ** This routine forms the core of the OP_SorterCompare opcode, which in
78477 ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
78478 */
78479 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
78480   const VdbeCursor *pCsr,         /* Sorter cursor */
78481   Mem *pVal,                      /* Value to compare to current sorter key */
78482   int nKeyCol,                    /* Compare this many columns */
78483   int *pRes                       /* OUT: Result of comparison */
78484 ){
78485   VdbeSorter *pSorter = pCsr->pSorter;
78486   UnpackedRecord *r2 = pSorter->pUnpacked;
78487   KeyInfo *pKeyInfo = pCsr->pKeyInfo;
78488   int i;
78489   void *pKey; int nKey;           /* Sorter key to compare pVal with */
78490 
78491   if( r2==0 ){
78492     char *p;
78493     r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo,0,0,&p);
78494     assert( pSorter->pUnpacked==(UnpackedRecord*)p );
78495     if( r2==0 ) return SQLITE_NOMEM;
78496     r2->nField = nKeyCol;
78497   }
78498   assert( r2->nField==nKeyCol );
78499 
78500   pKey = vdbeSorterRowkey(pSorter, &nKey);
78501   sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
78502   for(i=0; i<nKeyCol; i++){
78503     if( r2->aMem[i].flags & MEM_Null ){
78504       *pRes = -1;
78505       return SQLITE_OK;
78506     }
78507   }
78508 
78509   *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
78510   return SQLITE_OK;
78511 }
78512 
78513 /************** End of vdbesort.c ********************************************/
78514 /************** Begin file journal.c *****************************************/
78515 /*
78516 ** 2007 August 22
78517 **
78518 ** The author disclaims copyright to this source code.  In place of
78519 ** a legal notice, here is a blessing:
78520 **
78521 **    May you do good and not evil.
78522 **    May you find forgiveness for yourself and forgive others.
78523 **    May you share freely, never taking more than you give.
78524 **
78525 *************************************************************************
78526 **
78527 ** This file implements a special kind of sqlite3_file object used
78528 ** by SQLite to create journal files if the atomic-write optimization
78529 ** is enabled.
78530 **
78531 ** The distinctive characteristic of this sqlite3_file is that the
78532 ** actual on disk file is created lazily. When the file is created,
78533 ** the caller specifies a buffer size for an in-memory buffer to
78534 ** be used to service read() and write() requests. The actual file
78535 ** on disk is not created or populated until either:
78536 **
78537 **   1) The in-memory representation grows too large for the allocated
78538 **      buffer, or
78539 **   2) The sqlite3JournalCreate() function is called.
78540 */
78541 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
78542 
78543 
78544 /*
78545 ** A JournalFile object is a subclass of sqlite3_file used by
78546 ** as an open file handle for journal files.
78547 */
78548 struct JournalFile {
78549   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
78550   int nBuf;                       /* Size of zBuf[] in bytes */
78551   char *zBuf;                     /* Space to buffer journal writes */
78552   int iSize;                      /* Amount of zBuf[] currently used */
78553   int flags;                      /* xOpen flags */
78554   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
78555   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
78556   const char *zJournal;           /* Name of the journal file */
78557 };
78558 typedef struct JournalFile JournalFile;
78559 
78560 /*
78561 ** If it does not already exists, create and populate the on-disk file
78562 ** for JournalFile p.
78563 */
78564 static int createFile(JournalFile *p){
78565   int rc = SQLITE_OK;
78566   if( !p->pReal ){
78567     sqlite3_file *pReal = (sqlite3_file *)&p[1];
78568     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
78569     if( rc==SQLITE_OK ){
78570       p->pReal = pReal;
78571       if( p->iSize>0 ){
78572         assert(p->iSize<=p->nBuf);
78573         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
78574       }
78575       if( rc!=SQLITE_OK ){
78576         /* If an error occurred while writing to the file, close it before
78577         ** returning. This way, SQLite uses the in-memory journal data to
78578         ** roll back changes made to the internal page-cache before this
78579         ** function was called.  */
78580         sqlite3OsClose(pReal);
78581         p->pReal = 0;
78582       }
78583     }
78584   }
78585   return rc;
78586 }
78587 
78588 /*
78589 ** Close the file.
78590 */
78591 static int jrnlClose(sqlite3_file *pJfd){
78592   JournalFile *p = (JournalFile *)pJfd;
78593   if( p->pReal ){
78594     sqlite3OsClose(p->pReal);
78595   }
78596   sqlite3_free(p->zBuf);
78597   return SQLITE_OK;
78598 }
78599 
78600 /*
78601 ** Read data from the file.
78602 */
78603 static int jrnlRead(
78604   sqlite3_file *pJfd,    /* The journal file from which to read */
78605   void *zBuf,            /* Put the results here */
78606   int iAmt,              /* Number of bytes to read */
78607   sqlite_int64 iOfst     /* Begin reading at this offset */
78608 ){
78609   int rc = SQLITE_OK;
78610   JournalFile *p = (JournalFile *)pJfd;
78611   if( p->pReal ){
78612     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
78613   }else if( (iAmt+iOfst)>p->iSize ){
78614     rc = SQLITE_IOERR_SHORT_READ;
78615   }else{
78616     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
78617   }
78618   return rc;
78619 }
78620 
78621 /*
78622 ** Write data to the file.
78623 */
78624 static int jrnlWrite(
78625   sqlite3_file *pJfd,    /* The journal file into which to write */
78626   const void *zBuf,      /* Take data to be written from here */
78627   int iAmt,              /* Number of bytes to write */
78628   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
78629 ){
78630   int rc = SQLITE_OK;
78631   JournalFile *p = (JournalFile *)pJfd;
78632   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
78633     rc = createFile(p);
78634   }
78635   if( rc==SQLITE_OK ){
78636     if( p->pReal ){
78637       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
78638     }else{
78639       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
78640       if( p->iSize<(iOfst+iAmt) ){
78641         p->iSize = (iOfst+iAmt);
78642       }
78643     }
78644   }
78645   return rc;
78646 }
78647 
78648 /*
78649 ** Truncate the file.
78650 */
78651 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
78652   int rc = SQLITE_OK;
78653   JournalFile *p = (JournalFile *)pJfd;
78654   if( p->pReal ){
78655     rc = sqlite3OsTruncate(p->pReal, size);
78656   }else if( size<p->iSize ){
78657     p->iSize = size;
78658   }
78659   return rc;
78660 }
78661 
78662 /*
78663 ** Sync the file.
78664 */
78665 static int jrnlSync(sqlite3_file *pJfd, int flags){
78666   int rc;
78667   JournalFile *p = (JournalFile *)pJfd;
78668   if( p->pReal ){
78669     rc = sqlite3OsSync(p->pReal, flags);
78670   }else{
78671     rc = SQLITE_OK;
78672   }
78673   return rc;
78674 }
78675 
78676 /*
78677 ** Query the size of the file in bytes.
78678 */
78679 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
78680   int rc = SQLITE_OK;
78681   JournalFile *p = (JournalFile *)pJfd;
78682   if( p->pReal ){
78683     rc = sqlite3OsFileSize(p->pReal, pSize);
78684   }else{
78685     *pSize = (sqlite_int64) p->iSize;
78686   }
78687   return rc;
78688 }
78689 
78690 /*
78691 ** Table of methods for JournalFile sqlite3_file object.
78692 */
78693 static struct sqlite3_io_methods JournalFileMethods = {
78694   1,             /* iVersion */
78695   jrnlClose,     /* xClose */
78696   jrnlRead,      /* xRead */
78697   jrnlWrite,     /* xWrite */
78698   jrnlTruncate,  /* xTruncate */
78699   jrnlSync,      /* xSync */
78700   jrnlFileSize,  /* xFileSize */
78701   0,             /* xLock */
78702   0,             /* xUnlock */
78703   0,             /* xCheckReservedLock */
78704   0,             /* xFileControl */
78705   0,             /* xSectorSize */
78706   0,             /* xDeviceCharacteristics */
78707   0,             /* xShmMap */
78708   0,             /* xShmLock */
78709   0,             /* xShmBarrier */
78710   0              /* xShmUnmap */
78711 };
78712 
78713 /*
78714 ** Open a journal file.
78715 */
78716 SQLITE_PRIVATE int sqlite3JournalOpen(
78717   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
78718   const char *zName,         /* Name of the journal file */
78719   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
78720   int flags,                 /* Opening flags */
78721   int nBuf                   /* Bytes buffered before opening the file */
78722 ){
78723   JournalFile *p = (JournalFile *)pJfd;
78724   memset(p, 0, sqlite3JournalSize(pVfs));
78725   if( nBuf>0 ){
78726     p->zBuf = sqlite3MallocZero(nBuf);
78727     if( !p->zBuf ){
78728       return SQLITE_NOMEM;
78729     }
78730   }else{
78731     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
78732   }
78733   p->pMethod = &JournalFileMethods;
78734   p->nBuf = nBuf;
78735   p->flags = flags;
78736   p->zJournal = zName;
78737   p->pVfs = pVfs;
78738   return SQLITE_OK;
78739 }
78740 
78741 /*
78742 ** If the argument p points to a JournalFile structure, and the underlying
78743 ** file has not yet been created, create it now.
78744 */
78745 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
78746   if( p->pMethods!=&JournalFileMethods ){
78747     return SQLITE_OK;
78748   }
78749   return createFile((JournalFile *)p);
78750 }
78751 
78752 /*
78753 ** The file-handle passed as the only argument is guaranteed to be an open
78754 ** file. It may or may not be of class JournalFile. If the file is a
78755 ** JournalFile, and the underlying file on disk has not yet been opened,
78756 ** return 0. Otherwise, return 1.
78757 */
78758 SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
78759   return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
78760 }
78761 
78762 /*
78763 ** Return the number of bytes required to store a JournalFile that uses vfs
78764 ** pVfs to create the underlying on-disk files.
78765 */
78766 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
78767   return (pVfs->szOsFile+sizeof(JournalFile));
78768 }
78769 #endif
78770 
78771 /************** End of journal.c *********************************************/
78772 /************** Begin file memjournal.c **************************************/
78773 /*
78774 ** 2008 October 7
78775 **
78776 ** The author disclaims copyright to this source code.  In place of
78777 ** a legal notice, here is a blessing:
78778 **
78779 **    May you do good and not evil.
78780 **    May you find forgiveness for yourself and forgive others.
78781 **    May you share freely, never taking more than you give.
78782 **
78783 *************************************************************************
78784 **
78785 ** This file contains code use to implement an in-memory rollback journal.
78786 ** The in-memory rollback journal is used to journal transactions for
78787 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
78788 */
78789 
78790 /* Forward references to internal structures */
78791 typedef struct MemJournal MemJournal;
78792 typedef struct FilePoint FilePoint;
78793 typedef struct FileChunk FileChunk;
78794 
78795 /* Space to hold the rollback journal is allocated in increments of
78796 ** this many bytes.
78797 **
78798 ** The size chosen is a little less than a power of two.  That way,
78799 ** the FileChunk object will have a size that almost exactly fills
78800 ** a power-of-two allocation.  This minimizes wasted space in power-of-two
78801 ** memory allocators.
78802 */
78803 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
78804 
78805 /*
78806 ** The rollback journal is composed of a linked list of these structures.
78807 */
78808 struct FileChunk {
78809   FileChunk *pNext;               /* Next chunk in the journal */
78810   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
78811 };
78812 
78813 /*
78814 ** An instance of this object serves as a cursor into the rollback journal.
78815 ** The cursor can be either for reading or writing.
78816 */
78817 struct FilePoint {
78818   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
78819   FileChunk *pChunk;              /* Specific chunk into which cursor points */
78820 };
78821 
78822 /*
78823 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
78824 ** is an instance of this class.
78825 */
78826 struct MemJournal {
78827   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
78828   FileChunk *pFirst;              /* Head of in-memory chunk-list */
78829   FilePoint endpoint;             /* Pointer to the end of the file */
78830   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
78831 };
78832 
78833 /*
78834 ** Read data from the in-memory journal file.  This is the implementation
78835 ** of the sqlite3_vfs.xRead method.
78836 */
78837 static int memjrnlRead(
78838   sqlite3_file *pJfd,    /* The journal file from which to read */
78839   void *zBuf,            /* Put the results here */
78840   int iAmt,              /* Number of bytes to read */
78841   sqlite_int64 iOfst     /* Begin reading at this offset */
78842 ){
78843   MemJournal *p = (MemJournal *)pJfd;
78844   u8 *zOut = zBuf;
78845   int nRead = iAmt;
78846   int iChunkOffset;
78847   FileChunk *pChunk;
78848 
78849   /* SQLite never tries to read past the end of a rollback journal file */
78850   assert( iOfst+iAmt<=p->endpoint.iOffset );
78851 
78852   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
78853     sqlite3_int64 iOff = 0;
78854     for(pChunk=p->pFirst;
78855         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
78856         pChunk=pChunk->pNext
78857     ){
78858       iOff += JOURNAL_CHUNKSIZE;
78859     }
78860   }else{
78861     pChunk = p->readpoint.pChunk;
78862   }
78863 
78864   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
78865   do {
78866     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
78867     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
78868     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
78869     zOut += nCopy;
78870     nRead -= iSpace;
78871     iChunkOffset = 0;
78872   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
78873   p->readpoint.iOffset = iOfst+iAmt;
78874   p->readpoint.pChunk = pChunk;
78875 
78876   return SQLITE_OK;
78877 }
78878 
78879 /*
78880 ** Write data to the file.
78881 */
78882 static int memjrnlWrite(
78883   sqlite3_file *pJfd,    /* The journal file into which to write */
78884   const void *zBuf,      /* Take data to be written from here */
78885   int iAmt,              /* Number of bytes to write */
78886   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
78887 ){
78888   MemJournal *p = (MemJournal *)pJfd;
78889   int nWrite = iAmt;
78890   u8 *zWrite = (u8 *)zBuf;
78891 
78892   /* An in-memory journal file should only ever be appended to. Random
78893   ** access writes are not required by sqlite.
78894   */
78895   assert( iOfst==p->endpoint.iOffset );
78896   UNUSED_PARAMETER(iOfst);
78897 
78898   while( nWrite>0 ){
78899     FileChunk *pChunk = p->endpoint.pChunk;
78900     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
78901     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
78902 
78903     if( iChunkOffset==0 ){
78904       /* New chunk is required to extend the file. */
78905       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
78906       if( !pNew ){
78907         return SQLITE_IOERR_NOMEM;
78908       }
78909       pNew->pNext = 0;
78910       if( pChunk ){
78911         assert( p->pFirst );
78912         pChunk->pNext = pNew;
78913       }else{
78914         assert( !p->pFirst );
78915         p->pFirst = pNew;
78916       }
78917       p->endpoint.pChunk = pNew;
78918     }
78919 
78920     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
78921     zWrite += iSpace;
78922     nWrite -= iSpace;
78923     p->endpoint.iOffset += iSpace;
78924   }
78925 
78926   return SQLITE_OK;
78927 }
78928 
78929 /*
78930 ** Truncate the file.
78931 */
78932 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
78933   MemJournal *p = (MemJournal *)pJfd;
78934   FileChunk *pChunk;
78935   assert(size==0);
78936   UNUSED_PARAMETER(size);
78937   pChunk = p->pFirst;
78938   while( pChunk ){
78939     FileChunk *pTmp = pChunk;
78940     pChunk = pChunk->pNext;
78941     sqlite3_free(pTmp);
78942   }
78943   sqlite3MemJournalOpen(pJfd);
78944   return SQLITE_OK;
78945 }
78946 
78947 /*
78948 ** Close the file.
78949 */
78950 static int memjrnlClose(sqlite3_file *pJfd){
78951   memjrnlTruncate(pJfd, 0);
78952   return SQLITE_OK;
78953 }
78954 
78955 
78956 /*
78957 ** Sync the file.
78958 **
78959 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
78960 ** is never called in a working implementation.  This implementation
78961 ** exists purely as a contingency, in case some malfunction in some other
78962 ** part of SQLite causes Sync to be called by mistake.
78963 */
78964 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
78965   UNUSED_PARAMETER2(NotUsed, NotUsed2);
78966   return SQLITE_OK;
78967 }
78968 
78969 /*
78970 ** Query the size of the file in bytes.
78971 */
78972 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
78973   MemJournal *p = (MemJournal *)pJfd;
78974   *pSize = (sqlite_int64) p->endpoint.iOffset;
78975   return SQLITE_OK;
78976 }
78977 
78978 /*
78979 ** Table of methods for MemJournal sqlite3_file object.
78980 */
78981 static const struct sqlite3_io_methods MemJournalMethods = {
78982   1,                /* iVersion */
78983   memjrnlClose,     /* xClose */
78984   memjrnlRead,      /* xRead */
78985   memjrnlWrite,     /* xWrite */
78986   memjrnlTruncate,  /* xTruncate */
78987   memjrnlSync,      /* xSync */
78988   memjrnlFileSize,  /* xFileSize */
78989   0,                /* xLock */
78990   0,                /* xUnlock */
78991   0,                /* xCheckReservedLock */
78992   0,                /* xFileControl */
78993   0,                /* xSectorSize */
78994   0,                /* xDeviceCharacteristics */
78995   0,                /* xShmMap */
78996   0,                /* xShmLock */
78997   0,                /* xShmBarrier */
78998   0,                /* xShmUnmap */
78999   0,                /* xFetch */
79000   0                 /* xUnfetch */
79001 };
79002 
79003 /*
79004 ** Open a journal file.
79005 */
79006 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
79007   MemJournal *p = (MemJournal *)pJfd;
79008   assert( EIGHT_BYTE_ALIGNMENT(p) );
79009   memset(p, 0, sqlite3MemJournalSize());
79010   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
79011 }
79012 
79013 /*
79014 ** Return true if the file-handle passed as an argument is
79015 ** an in-memory journal
79016 */
79017 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
79018   return pJfd->pMethods==&MemJournalMethods;
79019 }
79020 
79021 /*
79022 ** Return the number of bytes required to store a MemJournal file descriptor.
79023 */
79024 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
79025   return sizeof(MemJournal);
79026 }
79027 
79028 /************** End of memjournal.c ******************************************/
79029 /************** Begin file walker.c ******************************************/
79030 /*
79031 ** 2008 August 16
79032 **
79033 ** The author disclaims copyright to this source code.  In place of
79034 ** a legal notice, here is a blessing:
79035 **
79036 **    May you do good and not evil.
79037 **    May you find forgiveness for yourself and forgive others.
79038 **    May you share freely, never taking more than you give.
79039 **
79040 *************************************************************************
79041 ** This file contains routines used for walking the parser tree for
79042 ** an SQL statement.
79043 */
79044 /* #include <stdlib.h> */
79045 /* #include <string.h> */
79046 
79047 
79048 /*
79049 ** Walk an expression tree.  Invoke the callback once for each node
79050 ** of the expression, while descending.  (In other words, the callback
79051 ** is invoked before visiting children.)
79052 **
79053 ** The return value from the callback should be one of the WRC_*
79054 ** constants to specify how to proceed with the walk.
79055 **
79056 **    WRC_Continue      Continue descending down the tree.
79057 **
79058 **    WRC_Prune         Do not descend into child nodes.  But allow
79059 **                      the walk to continue with sibling nodes.
79060 **
79061 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
79062 **                      return the top-level walk call.
79063 **
79064 ** The return value from this routine is WRC_Abort to abandon the tree walk
79065 ** and WRC_Continue to continue.
79066 */
79067 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
79068   int rc;
79069   if( pExpr==0 ) return WRC_Continue;
79070   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
79071   testcase( ExprHasProperty(pExpr, EP_Reduced) );
79072   rc = pWalker->xExprCallback(pWalker, pExpr);
79073   if( rc==WRC_Continue
79074               && !ExprHasProperty(pExpr,EP_TokenOnly) ){
79075     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
79076     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
79077     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
79078       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
79079     }else{
79080       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
79081     }
79082   }
79083   return rc & WRC_Abort;
79084 }
79085 
79086 /*
79087 ** Call sqlite3WalkExpr() for every expression in list p or until
79088 ** an abort request is seen.
79089 */
79090 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
79091   int i;
79092   struct ExprList_item *pItem;
79093   if( p ){
79094     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
79095       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
79096     }
79097   }
79098   return WRC_Continue;
79099 }
79100 
79101 /*
79102 ** Walk all expressions associated with SELECT statement p.  Do
79103 ** not invoke the SELECT callback on p, but do (of course) invoke
79104 ** any expr callbacks and SELECT callbacks that come from subqueries.
79105 ** Return WRC_Abort or WRC_Continue.
79106 */
79107 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
79108   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
79109   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
79110   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
79111   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
79112   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
79113   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
79114   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
79115   return WRC_Continue;
79116 }
79117 
79118 /*
79119 ** Walk the parse trees associated with all subqueries in the
79120 ** FROM clause of SELECT statement p.  Do not invoke the select
79121 ** callback on p, but do invoke it on each FROM clause subquery
79122 ** and on any subqueries further down in the tree.  Return
79123 ** WRC_Abort or WRC_Continue;
79124 */
79125 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
79126   SrcList *pSrc;
79127   int i;
79128   struct SrcList_item *pItem;
79129 
79130   pSrc = p->pSrc;
79131   if( ALWAYS(pSrc) ){
79132     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
79133       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
79134         return WRC_Abort;
79135       }
79136     }
79137   }
79138   return WRC_Continue;
79139 }
79140 
79141 /*
79142 ** Call sqlite3WalkExpr() for every expression in Select statement p.
79143 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
79144 ** on the compound select chain, p->pPrior.
79145 **
79146 ** If it is not NULL, the xSelectCallback() callback is invoked before
79147 ** the walk of the expressions and FROM clause. The xSelectCallback2()
79148 ** method, if it is not NULL, is invoked following the walk of the
79149 ** expressions and FROM clause.
79150 **
79151 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
79152 ** there is an abort request.
79153 **
79154 ** If the Walker does not have an xSelectCallback() then this routine
79155 ** is a no-op returning WRC_Continue.
79156 */
79157 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
79158   int rc;
79159   if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
79160     return WRC_Continue;
79161   }
79162   rc = WRC_Continue;
79163   pWalker->walkerDepth++;
79164   while( p ){
79165     if( pWalker->xSelectCallback ){
79166        rc = pWalker->xSelectCallback(pWalker, p);
79167        if( rc ) break;
79168     }
79169     if( sqlite3WalkSelectExpr(pWalker, p)
79170      || sqlite3WalkSelectFrom(pWalker, p)
79171     ){
79172       pWalker->walkerDepth--;
79173       return WRC_Abort;
79174     }
79175     if( pWalker->xSelectCallback2 ){
79176       pWalker->xSelectCallback2(pWalker, p);
79177     }
79178     p = p->pPrior;
79179   }
79180   pWalker->walkerDepth--;
79181   return rc & WRC_Abort;
79182 }
79183 
79184 /************** End of walker.c **********************************************/
79185 /************** Begin file resolve.c *****************************************/
79186 /*
79187 ** 2008 August 18
79188 **
79189 ** The author disclaims copyright to this source code.  In place of
79190 ** a legal notice, here is a blessing:
79191 **
79192 **    May you do good and not evil.
79193 **    May you find forgiveness for yourself and forgive others.
79194 **    May you share freely, never taking more than you give.
79195 **
79196 *************************************************************************
79197 **
79198 ** This file contains routines used for walking the parser tree and
79199 ** resolve all identifiers by associating them with a particular
79200 ** table and column.
79201 */
79202 /* #include <stdlib.h> */
79203 /* #include <string.h> */
79204 
79205 /*
79206 ** Walk the expression tree pExpr and increase the aggregate function
79207 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
79208 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
79209 ** outer query into an inner subquery.
79210 **
79211 ** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
79212 ** is a helper function - a callback for the tree walker.
79213 */
79214 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
79215   if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
79216   return WRC_Continue;
79217 }
79218 static void incrAggFunctionDepth(Expr *pExpr, int N){
79219   if( N>0 ){
79220     Walker w;
79221     memset(&w, 0, sizeof(w));
79222     w.xExprCallback = incrAggDepth;
79223     w.u.i = N;
79224     sqlite3WalkExpr(&w, pExpr);
79225   }
79226 }
79227 
79228 /*
79229 ** Turn the pExpr expression into an alias for the iCol-th column of the
79230 ** result set in pEList.
79231 **
79232 ** If the result set column is a simple column reference, then this routine
79233 ** makes an exact copy.  But for any other kind of expression, this
79234 ** routine make a copy of the result set column as the argument to the
79235 ** TK_AS operator.  The TK_AS operator causes the expression to be
79236 ** evaluated just once and then reused for each alias.
79237 **
79238 ** The reason for suppressing the TK_AS term when the expression is a simple
79239 ** column reference is so that the column reference will be recognized as
79240 ** usable by indices within the WHERE clause processing logic.
79241 **
79242 ** The TK_AS operator is inhibited if zType[0]=='G'.  This means
79243 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
79244 **
79245 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
79246 **
79247 ** Is equivalent to:
79248 **
79249 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
79250 **
79251 ** The result of random()%5 in the GROUP BY clause is probably different
79252 ** from the result in the result-set.  On the other hand Standard SQL does
79253 ** not allow the GROUP BY clause to contain references to result-set columns.
79254 ** So this should never come up in well-formed queries.
79255 **
79256 ** If the reference is followed by a COLLATE operator, then make sure
79257 ** the COLLATE operator is preserved.  For example:
79258 **
79259 **     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
79260 **
79261 ** Should be transformed into:
79262 **
79263 **     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
79264 **
79265 ** The nSubquery parameter specifies how many levels of subquery the
79266 ** alias is removed from the original expression.  The usually value is
79267 ** zero but it might be more if the alias is contained within a subquery
79268 ** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
79269 ** structures must be increased by the nSubquery amount.
79270 */
79271 static void resolveAlias(
79272   Parse *pParse,         /* Parsing context */
79273   ExprList *pEList,      /* A result set */
79274   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
79275   Expr *pExpr,           /* Transform this into an alias to the result set */
79276   const char *zType,     /* "GROUP" or "ORDER" or "" */
79277   int nSubquery          /* Number of subqueries that the label is moving */
79278 ){
79279   Expr *pOrig;           /* The iCol-th column of the result set */
79280   Expr *pDup;            /* Copy of pOrig */
79281   sqlite3 *db;           /* The database connection */
79282 
79283   assert( iCol>=0 && iCol<pEList->nExpr );
79284   pOrig = pEList->a[iCol].pExpr;
79285   assert( pOrig!=0 );
79286   assert( pOrig->flags & EP_Resolved );
79287   db = pParse->db;
79288   pDup = sqlite3ExprDup(db, pOrig, 0);
79289   if( pDup==0 ) return;
79290   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
79291     incrAggFunctionDepth(pDup, nSubquery);
79292     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
79293     if( pDup==0 ) return;
79294     ExprSetProperty(pDup, EP_Skip);
79295     if( pEList->a[iCol].u.x.iAlias==0 ){
79296       pEList->a[iCol].u.x.iAlias = (u16)(++pParse->nAlias);
79297     }
79298     pDup->iTable = pEList->a[iCol].u.x.iAlias;
79299   }
79300   if( pExpr->op==TK_COLLATE ){
79301     pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
79302   }
79303 
79304   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
79305   ** prevents ExprDelete() from deleting the Expr structure itself,
79306   ** allowing it to be repopulated by the memcpy() on the following line.
79307   ** The pExpr->u.zToken might point into memory that will be freed by the
79308   ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
79309   ** make a copy of the token before doing the sqlite3DbFree().
79310   */
79311   ExprSetProperty(pExpr, EP_Static);
79312   sqlite3ExprDelete(db, pExpr);
79313   memcpy(pExpr, pDup, sizeof(*pExpr));
79314   if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
79315     assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
79316     pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
79317     pExpr->flags |= EP_MemToken;
79318   }
79319   sqlite3DbFree(db, pDup);
79320 }
79321 
79322 
79323 /*
79324 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
79325 **
79326 ** Return FALSE if the USING clause is NULL or if it does not contain
79327 ** zCol.
79328 */
79329 static int nameInUsingClause(IdList *pUsing, const char *zCol){
79330   if( pUsing ){
79331     int k;
79332     for(k=0; k<pUsing->nId; k++){
79333       if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
79334     }
79335   }
79336   return 0;
79337 }
79338 
79339 /*
79340 ** Subqueries stores the original database, table and column names for their
79341 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
79342 ** Check to see if the zSpan given to this routine matches the zDb, zTab,
79343 ** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
79344 ** match anything.
79345 */
79346 SQLITE_PRIVATE int sqlite3MatchSpanName(
79347   const char *zSpan,
79348   const char *zCol,
79349   const char *zTab,
79350   const char *zDb
79351 ){
79352   int n;
79353   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
79354   if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
79355     return 0;
79356   }
79357   zSpan += n+1;
79358   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
79359   if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
79360     return 0;
79361   }
79362   zSpan += n+1;
79363   if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
79364     return 0;
79365   }
79366   return 1;
79367 }
79368 
79369 /*
79370 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
79371 ** that name in the set of source tables in pSrcList and make the pExpr
79372 ** expression node refer back to that source column.  The following changes
79373 ** are made to pExpr:
79374 **
79375 **    pExpr->iDb           Set the index in db->aDb[] of the database X
79376 **                         (even if X is implied).
79377 **    pExpr->iTable        Set to the cursor number for the table obtained
79378 **                         from pSrcList.
79379 **    pExpr->pTab          Points to the Table structure of X.Y (even if
79380 **                         X and/or Y are implied.)
79381 **    pExpr->iColumn       Set to the column number within the table.
79382 **    pExpr->op            Set to TK_COLUMN.
79383 **    pExpr->pLeft         Any expression this points to is deleted
79384 **    pExpr->pRight        Any expression this points to is deleted.
79385 **
79386 ** The zDb variable is the name of the database (the "X").  This value may be
79387 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
79388 ** can be used.  The zTable variable is the name of the table (the "Y").  This
79389 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
79390 ** means that the form of the name is Z and that columns from any table
79391 ** can be used.
79392 **
79393 ** If the name cannot be resolved unambiguously, leave an error message
79394 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
79395 */
79396 static int lookupName(
79397   Parse *pParse,       /* The parsing context */
79398   const char *zDb,     /* Name of the database containing table, or NULL */
79399   const char *zTab,    /* Name of table containing column, or NULL */
79400   const char *zCol,    /* Name of the column. */
79401   NameContext *pNC,    /* The name context used to resolve the name */
79402   Expr *pExpr          /* Make this EXPR node point to the selected column */
79403 ){
79404   int i, j;                         /* Loop counters */
79405   int cnt = 0;                      /* Number of matching column names */
79406   int cntTab = 0;                   /* Number of matching table names */
79407   int nSubquery = 0;                /* How many levels of subquery */
79408   sqlite3 *db = pParse->db;         /* The database connection */
79409   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
79410   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
79411   NameContext *pTopNC = pNC;        /* First namecontext in the list */
79412   Schema *pSchema = 0;              /* Schema of the expression */
79413   int isTrigger = 0;                /* True if resolved to a trigger column */
79414   Table *pTab = 0;                  /* Table hold the row */
79415   Column *pCol;                     /* A column of pTab */
79416 
79417   assert( pNC );     /* the name context cannot be NULL. */
79418   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
79419   assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
79420 
79421   /* Initialize the node to no-match */
79422   pExpr->iTable = -1;
79423   pExpr->pTab = 0;
79424   ExprSetVVAProperty(pExpr, EP_NoReduce);
79425 
79426   /* Translate the schema name in zDb into a pointer to the corresponding
79427   ** schema.  If not found, pSchema will remain NULL and nothing will match
79428   ** resulting in an appropriate error message toward the end of this routine
79429   */
79430   if( zDb ){
79431     testcase( pNC->ncFlags & NC_PartIdx );
79432     testcase( pNC->ncFlags & NC_IsCheck );
79433     if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
79434       /* Silently ignore database qualifiers inside CHECK constraints and partial
79435       ** indices.  Do not raise errors because that might break legacy and
79436       ** because it does not hurt anything to just ignore the database name. */
79437       zDb = 0;
79438     }else{
79439       for(i=0; i<db->nDb; i++){
79440         assert( db->aDb[i].zName );
79441         if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
79442           pSchema = db->aDb[i].pSchema;
79443           break;
79444         }
79445       }
79446     }
79447   }
79448 
79449   /* Start at the inner-most context and move outward until a match is found */
79450   while( pNC && cnt==0 ){
79451     ExprList *pEList;
79452     SrcList *pSrcList = pNC->pSrcList;
79453 
79454     if( pSrcList ){
79455       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
79456         pTab = pItem->pTab;
79457         assert( pTab!=0 && pTab->zName!=0 );
79458         assert( pTab->nCol>0 );
79459         if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
79460           int hit = 0;
79461           pEList = pItem->pSelect->pEList;
79462           for(j=0; j<pEList->nExpr; j++){
79463             if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
79464               cnt++;
79465               cntTab = 2;
79466               pMatch = pItem;
79467               pExpr->iColumn = j;
79468               hit = 1;
79469             }
79470           }
79471           if( hit || zTab==0 ) continue;
79472         }
79473         if( zDb && pTab->pSchema!=pSchema ){
79474           continue;
79475         }
79476         if( zTab ){
79477           const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
79478           assert( zTabName!=0 );
79479           if( sqlite3StrICmp(zTabName, zTab)!=0 ){
79480             continue;
79481           }
79482         }
79483         if( 0==(cntTab++) ){
79484           pMatch = pItem;
79485         }
79486         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
79487           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
79488             /* If there has been exactly one prior match and this match
79489             ** is for the right-hand table of a NATURAL JOIN or is in a
79490             ** USING clause, then skip this match.
79491             */
79492             if( cnt==1 ){
79493               if( pItem->jointype & JT_NATURAL ) continue;
79494               if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
79495             }
79496             cnt++;
79497             pMatch = pItem;
79498             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
79499             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
79500             break;
79501           }
79502         }
79503       }
79504       if( pMatch ){
79505         pExpr->iTable = pMatch->iCursor;
79506         pExpr->pTab = pMatch->pTab;
79507         pSchema = pExpr->pTab->pSchema;
79508       }
79509     } /* if( pSrcList ) */
79510 
79511 #ifndef SQLITE_OMIT_TRIGGER
79512     /* If we have not already resolved the name, then maybe
79513     ** it is a new.* or old.* trigger argument reference
79514     */
79515     if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
79516       int op = pParse->eTriggerOp;
79517       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
79518       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
79519         pExpr->iTable = 1;
79520         pTab = pParse->pTriggerTab;
79521       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
79522         pExpr->iTable = 0;
79523         pTab = pParse->pTriggerTab;
79524       }else{
79525         pTab = 0;
79526       }
79527 
79528       if( pTab ){
79529         int iCol;
79530         pSchema = pTab->pSchema;
79531         cntTab++;
79532         for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
79533           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
79534             if( iCol==pTab->iPKey ){
79535               iCol = -1;
79536             }
79537             break;
79538           }
79539         }
79540         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && HasRowid(pTab) ){
79541           /* IMP: R-51414-32910 */
79542           /* IMP: R-44911-55124 */
79543           iCol = -1;
79544         }
79545         if( iCol<pTab->nCol ){
79546           cnt++;
79547           if( iCol<0 ){
79548             pExpr->affinity = SQLITE_AFF_INTEGER;
79549           }else if( pExpr->iTable==0 ){
79550             testcase( iCol==31 );
79551             testcase( iCol==32 );
79552             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
79553           }else{
79554             testcase( iCol==31 );
79555             testcase( iCol==32 );
79556             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
79557           }
79558           pExpr->iColumn = (i16)iCol;
79559           pExpr->pTab = pTab;
79560           isTrigger = 1;
79561         }
79562       }
79563     }
79564 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
79565 
79566     /*
79567     ** Perhaps the name is a reference to the ROWID
79568     */
79569     if( cnt==0 && cntTab==1 && pMatch && sqlite3IsRowid(zCol)
79570      && HasRowid(pMatch->pTab) ){
79571       cnt = 1;
79572       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
79573       pExpr->affinity = SQLITE_AFF_INTEGER;
79574     }
79575 
79576     /*
79577     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
79578     ** might refer to an result-set alias.  This happens, for example, when
79579     ** we are resolving names in the WHERE clause of the following command:
79580     **
79581     **     SELECT a+b AS x FROM table WHERE x<10;
79582     **
79583     ** In cases like this, replace pExpr with a copy of the expression that
79584     ** forms the result set entry ("a+b" in the example) and return immediately.
79585     ** Note that the expression in the result set should have already been
79586     ** resolved by the time the WHERE clause is resolved.
79587     **
79588     ** The ability to use an output result-set column in the WHERE, GROUP BY,
79589     ** or HAVING clauses, or as part of a larger expression in the ORDRE BY
79590     ** clause is not standard SQL.  This is a (goofy) SQLite extension, that
79591     ** is supported for backwards compatibility only.  TO DO: Issue a warning
79592     ** on sqlite3_log() whenever the capability is used.
79593     */
79594     if( (pEList = pNC->pEList)!=0
79595      && zTab==0
79596      && cnt==0
79597     ){
79598       for(j=0; j<pEList->nExpr; j++){
79599         char *zAs = pEList->a[j].zName;
79600         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
79601           Expr *pOrig;
79602           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
79603           assert( pExpr->x.pList==0 );
79604           assert( pExpr->x.pSelect==0 );
79605           pOrig = pEList->a[j].pExpr;
79606           if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
79607             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
79608             return WRC_Abort;
79609           }
79610           resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
79611           cnt = 1;
79612           pMatch = 0;
79613           assert( zTab==0 && zDb==0 );
79614           goto lookupname_end;
79615         }
79616       }
79617     }
79618 
79619     /* Advance to the next name context.  The loop will exit when either
79620     ** we have a match (cnt>0) or when we run out of name contexts.
79621     */
79622     if( cnt==0 ){
79623       pNC = pNC->pNext;
79624       nSubquery++;
79625     }
79626   }
79627 
79628   /*
79629   ** If X and Y are NULL (in other words if only the column name Z is
79630   ** supplied) and the value of Z is enclosed in double-quotes, then
79631   ** Z is a string literal if it doesn't match any column names.  In that
79632   ** case, we need to return right away and not make any changes to
79633   ** pExpr.
79634   **
79635   ** Because no reference was made to outer contexts, the pNC->nRef
79636   ** fields are not changed in any context.
79637   */
79638   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
79639     pExpr->op = TK_STRING;
79640     pExpr->pTab = 0;
79641     return WRC_Prune;
79642   }
79643 
79644   /*
79645   ** cnt==0 means there was not match.  cnt>1 means there were two or
79646   ** more matches.  Either way, we have an error.
79647   */
79648   if( cnt!=1 ){
79649     const char *zErr;
79650     zErr = cnt==0 ? "no such column" : "ambiguous column name";
79651     if( zDb ){
79652       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
79653     }else if( zTab ){
79654       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
79655     }else{
79656       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
79657     }
79658     pParse->checkSchema = 1;
79659     pTopNC->nErr++;
79660   }
79661 
79662   /* If a column from a table in pSrcList is referenced, then record
79663   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
79664   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
79665   ** column number is greater than the number of bits in the bitmask
79666   ** then set the high-order bit of the bitmask.
79667   */
79668   if( pExpr->iColumn>=0 && pMatch!=0 ){
79669     int n = pExpr->iColumn;
79670     testcase( n==BMS-1 );
79671     if( n>=BMS ){
79672       n = BMS-1;
79673     }
79674     assert( pMatch->iCursor==pExpr->iTable );
79675     pMatch->colUsed |= ((Bitmask)1)<<n;
79676   }
79677 
79678   /* Clean up and return
79679   */
79680   sqlite3ExprDelete(db, pExpr->pLeft);
79681   pExpr->pLeft = 0;
79682   sqlite3ExprDelete(db, pExpr->pRight);
79683   pExpr->pRight = 0;
79684   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
79685 lookupname_end:
79686   if( cnt==1 ){
79687     assert( pNC!=0 );
79688     if( pExpr->op!=TK_AS ){
79689       sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
79690     }
79691     /* Increment the nRef value on all name contexts from TopNC up to
79692     ** the point where the name matched. */
79693     for(;;){
79694       assert( pTopNC!=0 );
79695       pTopNC->nRef++;
79696       if( pTopNC==pNC ) break;
79697       pTopNC = pTopNC->pNext;
79698     }
79699     return WRC_Prune;
79700   } else {
79701     return WRC_Abort;
79702   }
79703 }
79704 
79705 /*
79706 ** Allocate and return a pointer to an expression to load the column iCol
79707 ** from datasource iSrc in SrcList pSrc.
79708 */
79709 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
79710   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
79711   if( p ){
79712     struct SrcList_item *pItem = &pSrc->a[iSrc];
79713     p->pTab = pItem->pTab;
79714     p->iTable = pItem->iCursor;
79715     if( p->pTab->iPKey==iCol ){
79716       p->iColumn = -1;
79717     }else{
79718       p->iColumn = (ynVar)iCol;
79719       testcase( iCol==BMS );
79720       testcase( iCol==BMS-1 );
79721       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
79722     }
79723     ExprSetProperty(p, EP_Resolved);
79724   }
79725   return p;
79726 }
79727 
79728 /*
79729 ** Report an error that an expression is not valid for a partial index WHERE
79730 ** clause.
79731 */
79732 static void notValidPartIdxWhere(
79733   Parse *pParse,       /* Leave error message here */
79734   NameContext *pNC,    /* The name context */
79735   const char *zMsg     /* Type of error */
79736 ){
79737   if( (pNC->ncFlags & NC_PartIdx)!=0 ){
79738     sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses",
79739                     zMsg);
79740   }
79741 }
79742 
79743 #ifndef SQLITE_OMIT_CHECK
79744 /*
79745 ** Report an error that an expression is not valid for a CHECK constraint.
79746 */
79747 static void notValidCheckConstraint(
79748   Parse *pParse,       /* Leave error message here */
79749   NameContext *pNC,    /* The name context */
79750   const char *zMsg     /* Type of error */
79751 ){
79752   if( (pNC->ncFlags & NC_IsCheck)!=0 ){
79753     sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg);
79754   }
79755 }
79756 #else
79757 # define notValidCheckConstraint(P,N,M)
79758 #endif
79759 
79760 /*
79761 ** Expression p should encode a floating point value between 1.0 and 0.0.
79762 ** Return 1024 times this value.  Or return -1 if p is not a floating point
79763 ** value between 1.0 and 0.0.
79764 */
79765 static int exprProbability(Expr *p){
79766   double r = -1.0;
79767   if( p->op!=TK_FLOAT ) return -1;
79768   sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
79769   assert( r>=0.0 );
79770   if( r>1.0 ) return -1;
79771   return (int)(r*1000.0);
79772 }
79773 
79774 /*
79775 ** This routine is callback for sqlite3WalkExpr().
79776 **
79777 ** Resolve symbolic names into TK_COLUMN operators for the current
79778 ** node in the expression tree.  Return 0 to continue the search down
79779 ** the tree or 2 to abort the tree walk.
79780 **
79781 ** This routine also does error checking and name resolution for
79782 ** function names.  The operator for aggregate functions is changed
79783 ** to TK_AGG_FUNCTION.
79784 */
79785 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
79786   NameContext *pNC;
79787   Parse *pParse;
79788 
79789   pNC = pWalker->u.pNC;
79790   assert( pNC!=0 );
79791   pParse = pNC->pParse;
79792   assert( pParse==pWalker->pParse );
79793 
79794   if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
79795   ExprSetProperty(pExpr, EP_Resolved);
79796 #ifndef NDEBUG
79797   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
79798     SrcList *pSrcList = pNC->pSrcList;
79799     int i;
79800     for(i=0; i<pNC->pSrcList->nSrc; i++){
79801       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
79802     }
79803   }
79804 #endif
79805   switch( pExpr->op ){
79806 
79807 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
79808     /* The special operator TK_ROW means use the rowid for the first
79809     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
79810     ** clause processing on UPDATE and DELETE statements.
79811     */
79812     case TK_ROW: {
79813       SrcList *pSrcList = pNC->pSrcList;
79814       struct SrcList_item *pItem;
79815       assert( pSrcList && pSrcList->nSrc==1 );
79816       pItem = pSrcList->a;
79817       pExpr->op = TK_COLUMN;
79818       pExpr->pTab = pItem->pTab;
79819       pExpr->iTable = pItem->iCursor;
79820       pExpr->iColumn = -1;
79821       pExpr->affinity = SQLITE_AFF_INTEGER;
79822       break;
79823     }
79824 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
79825 
79826     /* A lone identifier is the name of a column.
79827     */
79828     case TK_ID: {
79829       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
79830     }
79831 
79832     /* A table name and column name:     ID.ID
79833     ** Or a database, table and column:  ID.ID.ID
79834     */
79835     case TK_DOT: {
79836       const char *zColumn;
79837       const char *zTable;
79838       const char *zDb;
79839       Expr *pRight;
79840 
79841       /* if( pSrcList==0 ) break; */
79842       pRight = pExpr->pRight;
79843       if( pRight->op==TK_ID ){
79844         zDb = 0;
79845         zTable = pExpr->pLeft->u.zToken;
79846         zColumn = pRight->u.zToken;
79847       }else{
79848         assert( pRight->op==TK_DOT );
79849         zDb = pExpr->pLeft->u.zToken;
79850         zTable = pRight->pLeft->u.zToken;
79851         zColumn = pRight->pRight->u.zToken;
79852       }
79853       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
79854     }
79855 
79856     /* Resolve function names
79857     */
79858     case TK_FUNCTION: {
79859       ExprList *pList = pExpr->x.pList;    /* The argument list */
79860       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
79861       int no_such_func = 0;       /* True if no such function exists */
79862       int wrong_num_args = 0;     /* True if wrong number of arguments */
79863       int is_agg = 0;             /* True if is an aggregate function */
79864       int auth;                   /* Authorization to use the function */
79865       int nId;                    /* Number of characters in function name */
79866       const char *zId;            /* The function name. */
79867       FuncDef *pDef;              /* Information about the function */
79868       u8 enc = ENC(pParse->db);   /* The database encoding */
79869 
79870       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
79871       notValidPartIdxWhere(pParse, pNC, "functions");
79872       zId = pExpr->u.zToken;
79873       nId = sqlite3Strlen30(zId);
79874       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
79875       if( pDef==0 ){
79876         pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
79877         if( pDef==0 ){
79878           no_such_func = 1;
79879         }else{
79880           wrong_num_args = 1;
79881         }
79882       }else{
79883         is_agg = pDef->xFunc==0;
79884         if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
79885           ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
79886           if( n==2 ){
79887             pExpr->iTable = exprProbability(pList->a[1].pExpr);
79888             if( pExpr->iTable<0 ){
79889               sqlite3ErrorMsg(pParse, "second argument to likelihood() must be a "
79890                                       "constant between 0.0 and 1.0");
79891               pNC->nErr++;
79892             }
79893           }else{
79894             /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is equivalent to
79895             ** likelihood(X, 0.0625).
79896             ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is short-hand for
79897             ** likelihood(X,0.0625).
79898             ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand for
79899             ** likelihood(X,0.9375).
79900             ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent to
79901             ** likelihood(X,0.9375). */
79902             /* TUNING: unlikely() probability is 0.0625.  likely() is 0.9375 */
79903             pExpr->iTable = pDef->zName[0]=='u' ? 62 : 938;
79904           }
79905         }
79906 #ifndef SQLITE_OMIT_AUTHORIZATION
79907         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
79908         if( auth!=SQLITE_OK ){
79909           if( auth==SQLITE_DENY ){
79910             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
79911                                     pDef->zName);
79912             pNC->nErr++;
79913           }
79914           pExpr->op = TK_NULL;
79915           return WRC_Prune;
79916         }
79917 #endif
79918         if( pDef->funcFlags & SQLITE_FUNC_CONSTANT ) ExprSetProperty(pExpr,EP_Constant);
79919       }
79920       if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
79921         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
79922         pNC->nErr++;
79923         is_agg = 0;
79924       }else if( no_such_func && pParse->db->init.busy==0 ){
79925         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
79926         pNC->nErr++;
79927       }else if( wrong_num_args ){
79928         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
79929              nId, zId);
79930         pNC->nErr++;
79931       }
79932       if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
79933       sqlite3WalkExprList(pWalker, pList);
79934       if( is_agg ){
79935         NameContext *pNC2 = pNC;
79936         pExpr->op = TK_AGG_FUNCTION;
79937         pExpr->op2 = 0;
79938         while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
79939           pExpr->op2++;
79940           pNC2 = pNC2->pNext;
79941         }
79942         assert( pDef!=0 );
79943         if( pNC2 ){
79944           assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
79945           testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
79946           pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
79947 
79948         }
79949         pNC->ncFlags |= NC_AllowAgg;
79950       }
79951       /* FIX ME:  Compute pExpr->affinity based on the expected return
79952       ** type of the function
79953       */
79954       return WRC_Prune;
79955     }
79956 #ifndef SQLITE_OMIT_SUBQUERY
79957     case TK_SELECT:
79958     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
79959 #endif
79960     case TK_IN: {
79961       testcase( pExpr->op==TK_IN );
79962       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
79963         int nRef = pNC->nRef;
79964         notValidCheckConstraint(pParse, pNC, "subqueries");
79965         notValidPartIdxWhere(pParse, pNC, "subqueries");
79966         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
79967         assert( pNC->nRef>=nRef );
79968         if( nRef!=pNC->nRef ){
79969           ExprSetProperty(pExpr, EP_VarSelect);
79970         }
79971       }
79972       break;
79973     }
79974     case TK_VARIABLE: {
79975       notValidCheckConstraint(pParse, pNC, "parameters");
79976       notValidPartIdxWhere(pParse, pNC, "parameters");
79977       break;
79978     }
79979   }
79980   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
79981 }
79982 
79983 /*
79984 ** pEList is a list of expressions which are really the result set of the
79985 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
79986 ** This routine checks to see if pE is a simple identifier which corresponds
79987 ** to the AS-name of one of the terms of the expression list.  If it is,
79988 ** this routine return an integer between 1 and N where N is the number of
79989 ** elements in pEList, corresponding to the matching entry.  If there is
79990 ** no match, or if pE is not a simple identifier, then this routine
79991 ** return 0.
79992 **
79993 ** pEList has been resolved.  pE has not.
79994 */
79995 static int resolveAsName(
79996   Parse *pParse,     /* Parsing context for error messages */
79997   ExprList *pEList,  /* List of expressions to scan */
79998   Expr *pE           /* Expression we are trying to match */
79999 ){
80000   int i;             /* Loop counter */
80001 
80002   UNUSED_PARAMETER(pParse);
80003 
80004   if( pE->op==TK_ID ){
80005     char *zCol = pE->u.zToken;
80006     for(i=0; i<pEList->nExpr; i++){
80007       char *zAs = pEList->a[i].zName;
80008       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
80009         return i+1;
80010       }
80011     }
80012   }
80013   return 0;
80014 }
80015 
80016 /*
80017 ** pE is a pointer to an expression which is a single term in the
80018 ** ORDER BY of a compound SELECT.  The expression has not been
80019 ** name resolved.
80020 **
80021 ** At the point this routine is called, we already know that the
80022 ** ORDER BY term is not an integer index into the result set.  That
80023 ** case is handled by the calling routine.
80024 **
80025 ** Attempt to match pE against result set columns in the left-most
80026 ** SELECT statement.  Return the index i of the matching column,
80027 ** as an indication to the caller that it should sort by the i-th column.
80028 ** The left-most column is 1.  In other words, the value returned is the
80029 ** same integer value that would be used in the SQL statement to indicate
80030 ** the column.
80031 **
80032 ** If there is no match, return 0.  Return -1 if an error occurs.
80033 */
80034 static int resolveOrderByTermToExprList(
80035   Parse *pParse,     /* Parsing context for error messages */
80036   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
80037   Expr *pE           /* The specific ORDER BY term */
80038 ){
80039   int i;             /* Loop counter */
80040   ExprList *pEList;  /* The columns of the result set */
80041   NameContext nc;    /* Name context for resolving pE */
80042   sqlite3 *db;       /* Database connection */
80043   int rc;            /* Return code from subprocedures */
80044   u8 savedSuppErr;   /* Saved value of db->suppressErr */
80045 
80046   assert( sqlite3ExprIsInteger(pE, &i)==0 );
80047   pEList = pSelect->pEList;
80048 
80049   /* Resolve all names in the ORDER BY term expression
80050   */
80051   memset(&nc, 0, sizeof(nc));
80052   nc.pParse = pParse;
80053   nc.pSrcList = pSelect->pSrc;
80054   nc.pEList = pEList;
80055   nc.ncFlags = NC_AllowAgg;
80056   nc.nErr = 0;
80057   db = pParse->db;
80058   savedSuppErr = db->suppressErr;
80059   db->suppressErr = 1;
80060   rc = sqlite3ResolveExprNames(&nc, pE);
80061   db->suppressErr = savedSuppErr;
80062   if( rc ) return 0;
80063 
80064   /* Try to match the ORDER BY expression against an expression
80065   ** in the result set.  Return an 1-based index of the matching
80066   ** result-set entry.
80067   */
80068   for(i=0; i<pEList->nExpr; i++){
80069     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
80070       return i+1;
80071     }
80072   }
80073 
80074   /* If no match, return 0. */
80075   return 0;
80076 }
80077 
80078 /*
80079 ** Generate an ORDER BY or GROUP BY term out-of-range error.
80080 */
80081 static void resolveOutOfRangeError(
80082   Parse *pParse,         /* The error context into which to write the error */
80083   const char *zType,     /* "ORDER" or "GROUP" */
80084   int i,                 /* The index (1-based) of the term out of range */
80085   int mx                 /* Largest permissible value of i */
80086 ){
80087   sqlite3ErrorMsg(pParse,
80088     "%r %s BY term out of range - should be "
80089     "between 1 and %d", i, zType, mx);
80090 }
80091 
80092 /*
80093 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
80094 ** each term of the ORDER BY clause is a constant integer between 1
80095 ** and N where N is the number of columns in the compound SELECT.
80096 **
80097 ** ORDER BY terms that are already an integer between 1 and N are
80098 ** unmodified.  ORDER BY terms that are integers outside the range of
80099 ** 1 through N generate an error.  ORDER BY terms that are expressions
80100 ** are matched against result set expressions of compound SELECT
80101 ** beginning with the left-most SELECT and working toward the right.
80102 ** At the first match, the ORDER BY expression is transformed into
80103 ** the integer column number.
80104 **
80105 ** Return the number of errors seen.
80106 */
80107 static int resolveCompoundOrderBy(
80108   Parse *pParse,        /* Parsing context.  Leave error messages here */
80109   Select *pSelect       /* The SELECT statement containing the ORDER BY */
80110 ){
80111   int i;
80112   ExprList *pOrderBy;
80113   ExprList *pEList;
80114   sqlite3 *db;
80115   int moreToDo = 1;
80116 
80117   pOrderBy = pSelect->pOrderBy;
80118   if( pOrderBy==0 ) return 0;
80119   db = pParse->db;
80120 #if SQLITE_MAX_COLUMN
80121   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
80122     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
80123     return 1;
80124   }
80125 #endif
80126   for(i=0; i<pOrderBy->nExpr; i++){
80127     pOrderBy->a[i].done = 0;
80128   }
80129   pSelect->pNext = 0;
80130   while( pSelect->pPrior ){
80131     pSelect->pPrior->pNext = pSelect;
80132     pSelect = pSelect->pPrior;
80133   }
80134   while( pSelect && moreToDo ){
80135     struct ExprList_item *pItem;
80136     moreToDo = 0;
80137     pEList = pSelect->pEList;
80138     assert( pEList!=0 );
80139     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
80140       int iCol = -1;
80141       Expr *pE, *pDup;
80142       if( pItem->done ) continue;
80143       pE = sqlite3ExprSkipCollate(pItem->pExpr);
80144       if( sqlite3ExprIsInteger(pE, &iCol) ){
80145         if( iCol<=0 || iCol>pEList->nExpr ){
80146           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
80147           return 1;
80148         }
80149       }else{
80150         iCol = resolveAsName(pParse, pEList, pE);
80151         if( iCol==0 ){
80152           pDup = sqlite3ExprDup(db, pE, 0);
80153           if( !db->mallocFailed ){
80154             assert(pDup);
80155             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
80156           }
80157           sqlite3ExprDelete(db, pDup);
80158         }
80159       }
80160       if( iCol>0 ){
80161         /* Convert the ORDER BY term into an integer column number iCol,
80162         ** taking care to preserve the COLLATE clause if it exists */
80163         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
80164         if( pNew==0 ) return 1;
80165         pNew->flags |= EP_IntValue;
80166         pNew->u.iValue = iCol;
80167         if( pItem->pExpr==pE ){
80168           pItem->pExpr = pNew;
80169         }else{
80170           assert( pItem->pExpr->op==TK_COLLATE );
80171           assert( pItem->pExpr->pLeft==pE );
80172           pItem->pExpr->pLeft = pNew;
80173         }
80174         sqlite3ExprDelete(db, pE);
80175         pItem->u.x.iOrderByCol = (u16)iCol;
80176         pItem->done = 1;
80177       }else{
80178         moreToDo = 1;
80179       }
80180     }
80181     pSelect = pSelect->pNext;
80182   }
80183   for(i=0; i<pOrderBy->nExpr; i++){
80184     if( pOrderBy->a[i].done==0 ){
80185       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
80186             "column in the result set", i+1);
80187       return 1;
80188     }
80189   }
80190   return 0;
80191 }
80192 
80193 /*
80194 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
80195 ** the SELECT statement pSelect.  If any term is reference to a
80196 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
80197 ** field) then convert that term into a copy of the corresponding result set
80198 ** column.
80199 **
80200 ** If any errors are detected, add an error message to pParse and
80201 ** return non-zero.  Return zero if no errors are seen.
80202 */
80203 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
80204   Parse *pParse,        /* Parsing context.  Leave error messages here */
80205   Select *pSelect,      /* The SELECT statement containing the clause */
80206   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
80207   const char *zType     /* "ORDER" or "GROUP" */
80208 ){
80209   int i;
80210   sqlite3 *db = pParse->db;
80211   ExprList *pEList;
80212   struct ExprList_item *pItem;
80213 
80214   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
80215 #if SQLITE_MAX_COLUMN
80216   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
80217     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
80218     return 1;
80219   }
80220 #endif
80221   pEList = pSelect->pEList;
80222   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
80223   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
80224     if( pItem->u.x.iOrderByCol ){
80225       if( pItem->u.x.iOrderByCol>pEList->nExpr ){
80226         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
80227         return 1;
80228       }
80229       resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr, zType,0);
80230     }
80231   }
80232   return 0;
80233 }
80234 
80235 /*
80236 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
80237 ** The Name context of the SELECT statement is pNC.  zType is either
80238 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
80239 **
80240 ** This routine resolves each term of the clause into an expression.
80241 ** If the order-by term is an integer I between 1 and N (where N is the
80242 ** number of columns in the result set of the SELECT) then the expression
80243 ** in the resolution is a copy of the I-th result-set expression.  If
80244 ** the order-by term is an identifier that corresponds to the AS-name of
80245 ** a result-set expression, then the term resolves to a copy of the
80246 ** result-set expression.  Otherwise, the expression is resolved in
80247 ** the usual way - using sqlite3ResolveExprNames().
80248 **
80249 ** This routine returns the number of errors.  If errors occur, then
80250 ** an appropriate error message might be left in pParse.  (OOM errors
80251 ** excepted.)
80252 */
80253 static int resolveOrderGroupBy(
80254   NameContext *pNC,     /* The name context of the SELECT statement */
80255   Select *pSelect,      /* The SELECT statement holding pOrderBy */
80256   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
80257   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
80258 ){
80259   int i, j;                      /* Loop counters */
80260   int iCol;                      /* Column number */
80261   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
80262   Parse *pParse;                 /* Parsing context */
80263   int nResult;                   /* Number of terms in the result set */
80264 
80265   if( pOrderBy==0 ) return 0;
80266   nResult = pSelect->pEList->nExpr;
80267   pParse = pNC->pParse;
80268   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
80269     Expr *pE = pItem->pExpr;
80270     Expr *pE2 = sqlite3ExprSkipCollate(pE);
80271     if( zType[0]!='G' ){
80272       iCol = resolveAsName(pParse, pSelect->pEList, pE2);
80273       if( iCol>0 ){
80274         /* If an AS-name match is found, mark this ORDER BY column as being
80275         ** a copy of the iCol-th result-set column.  The subsequent call to
80276         ** sqlite3ResolveOrderGroupBy() will convert the expression to a
80277         ** copy of the iCol-th result-set expression. */
80278         pItem->u.x.iOrderByCol = (u16)iCol;
80279         continue;
80280       }
80281     }
80282     if( sqlite3ExprIsInteger(pE2, &iCol) ){
80283       /* The ORDER BY term is an integer constant.  Again, set the column
80284       ** number so that sqlite3ResolveOrderGroupBy() will convert the
80285       ** order-by term to a copy of the result-set expression */
80286       if( iCol<1 || iCol>0xffff ){
80287         resolveOutOfRangeError(pParse, zType, i+1, nResult);
80288         return 1;
80289       }
80290       pItem->u.x.iOrderByCol = (u16)iCol;
80291       continue;
80292     }
80293 
80294     /* Otherwise, treat the ORDER BY term as an ordinary expression */
80295     pItem->u.x.iOrderByCol = 0;
80296     if( sqlite3ResolveExprNames(pNC, pE) ){
80297       return 1;
80298     }
80299     for(j=0; j<pSelect->pEList->nExpr; j++){
80300       if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
80301         pItem->u.x.iOrderByCol = j+1;
80302       }
80303     }
80304   }
80305   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
80306 }
80307 
80308 /*
80309 ** Resolve names in the SELECT statement p and all of its descendants.
80310 */
80311 static int resolveSelectStep(Walker *pWalker, Select *p){
80312   NameContext *pOuterNC;  /* Context that contains this SELECT */
80313   NameContext sNC;        /* Name context of this SELECT */
80314   int isCompound;         /* True if p is a compound select */
80315   int nCompound;          /* Number of compound terms processed so far */
80316   Parse *pParse;          /* Parsing context */
80317   ExprList *pEList;       /* Result set expression list */
80318   int i;                  /* Loop counter */
80319   ExprList *pGroupBy;     /* The GROUP BY clause */
80320   Select *pLeftmost;      /* Left-most of SELECT of a compound */
80321   sqlite3 *db;            /* Database connection */
80322 
80323 
80324   assert( p!=0 );
80325   if( p->selFlags & SF_Resolved ){
80326     return WRC_Prune;
80327   }
80328   pOuterNC = pWalker->u.pNC;
80329   pParse = pWalker->pParse;
80330   db = pParse->db;
80331 
80332   /* Normally sqlite3SelectExpand() will be called first and will have
80333   ** already expanded this SELECT.  However, if this is a subquery within
80334   ** an expression, sqlite3ResolveExprNames() will be called without a
80335   ** prior call to sqlite3SelectExpand().  When that happens, let
80336   ** sqlite3SelectPrep() do all of the processing for this SELECT.
80337   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
80338   ** this routine in the correct order.
80339   */
80340   if( (p->selFlags & SF_Expanded)==0 ){
80341     sqlite3SelectPrep(pParse, p, pOuterNC);
80342     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
80343   }
80344 
80345   isCompound = p->pPrior!=0;
80346   nCompound = 0;
80347   pLeftmost = p;
80348   while( p ){
80349     assert( (p->selFlags & SF_Expanded)!=0 );
80350     assert( (p->selFlags & SF_Resolved)==0 );
80351     p->selFlags |= SF_Resolved;
80352 
80353     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
80354     ** are not allowed to refer to any names, so pass an empty NameContext.
80355     */
80356     memset(&sNC, 0, sizeof(sNC));
80357     sNC.pParse = pParse;
80358     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
80359         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
80360       return WRC_Abort;
80361     }
80362 
80363     /* Recursively resolve names in all subqueries
80364     */
80365     for(i=0; i<p->pSrc->nSrc; i++){
80366       struct SrcList_item *pItem = &p->pSrc->a[i];
80367       if( pItem->pSelect ){
80368         NameContext *pNC;         /* Used to iterate name contexts */
80369         int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
80370         const char *zSavedContext = pParse->zAuthContext;
80371 
80372         /* Count the total number of references to pOuterNC and all of its
80373         ** parent contexts. After resolving references to expressions in
80374         ** pItem->pSelect, check if this value has changed. If so, then
80375         ** SELECT statement pItem->pSelect must be correlated. Set the
80376         ** pItem->isCorrelated flag if this is the case. */
80377         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
80378 
80379         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
80380         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
80381         pParse->zAuthContext = zSavedContext;
80382         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
80383 
80384         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
80385         assert( pItem->isCorrelated==0 && nRef<=0 );
80386         pItem->isCorrelated = (nRef!=0);
80387       }
80388     }
80389 
80390     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
80391     ** resolve the result-set expression list.
80392     */
80393     sNC.ncFlags = NC_AllowAgg;
80394     sNC.pSrcList = p->pSrc;
80395     sNC.pNext = pOuterNC;
80396 
80397     /* Resolve names in the result set. */
80398     pEList = p->pEList;
80399     assert( pEList!=0 );
80400     for(i=0; i<pEList->nExpr; i++){
80401       Expr *pX = pEList->a[i].pExpr;
80402       if( sqlite3ResolveExprNames(&sNC, pX) ){
80403         return WRC_Abort;
80404       }
80405     }
80406 
80407     /* If there are no aggregate functions in the result-set, and no GROUP BY
80408     ** expression, do not allow aggregates in any of the other expressions.
80409     */
80410     assert( (p->selFlags & SF_Aggregate)==0 );
80411     pGroupBy = p->pGroupBy;
80412     if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
80413       assert( NC_MinMaxAgg==SF_MinMaxAgg );
80414       p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
80415     }else{
80416       sNC.ncFlags &= ~NC_AllowAgg;
80417     }
80418 
80419     /* If a HAVING clause is present, then there must be a GROUP BY clause.
80420     */
80421     if( p->pHaving && !pGroupBy ){
80422       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
80423       return WRC_Abort;
80424     }
80425 
80426     /* Add the output column list to the name-context before parsing the
80427     ** other expressions in the SELECT statement. This is so that
80428     ** expressions in the WHERE clause (etc.) can refer to expressions by
80429     ** aliases in the result set.
80430     **
80431     ** Minor point: If this is the case, then the expression will be
80432     ** re-evaluated for each reference to it.
80433     */
80434     sNC.pEList = p->pEList;
80435     if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
80436     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
80437 
80438     /* The ORDER BY and GROUP BY clauses may not refer to terms in
80439     ** outer queries
80440     */
80441     sNC.pNext = 0;
80442     sNC.ncFlags |= NC_AllowAgg;
80443 
80444     /* Process the ORDER BY clause for singleton SELECT statements.
80445     ** The ORDER BY clause for compounds SELECT statements is handled
80446     ** below, after all of the result-sets for all of the elements of
80447     ** the compound have been resolved.
80448     */
80449     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
80450       return WRC_Abort;
80451     }
80452     if( db->mallocFailed ){
80453       return WRC_Abort;
80454     }
80455 
80456     /* Resolve the GROUP BY clause.  At the same time, make sure
80457     ** the GROUP BY clause does not contain aggregate functions.
80458     */
80459     if( pGroupBy ){
80460       struct ExprList_item *pItem;
80461 
80462       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
80463         return WRC_Abort;
80464       }
80465       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
80466         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
80467           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
80468               "the GROUP BY clause");
80469           return WRC_Abort;
80470         }
80471       }
80472     }
80473 
80474     /* Advance to the next term of the compound
80475     */
80476     p = p->pPrior;
80477     nCompound++;
80478   }
80479 
80480   /* Resolve the ORDER BY on a compound SELECT after all terms of
80481   ** the compound have been resolved.
80482   */
80483   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
80484     return WRC_Abort;
80485   }
80486 
80487   return WRC_Prune;
80488 }
80489 
80490 /*
80491 ** This routine walks an expression tree and resolves references to
80492 ** table columns and result-set columns.  At the same time, do error
80493 ** checking on function usage and set a flag if any aggregate functions
80494 ** are seen.
80495 **
80496 ** To resolve table columns references we look for nodes (or subtrees) of the
80497 ** form X.Y.Z or Y.Z or just Z where
80498 **
80499 **      X:   The name of a database.  Ex:  "main" or "temp" or
80500 **           the symbolic name assigned to an ATTACH-ed database.
80501 **
80502 **      Y:   The name of a table in a FROM clause.  Or in a trigger
80503 **           one of the special names "old" or "new".
80504 **
80505 **      Z:   The name of a column in table Y.
80506 **
80507 ** The node at the root of the subtree is modified as follows:
80508 **
80509 **    Expr.op        Changed to TK_COLUMN
80510 **    Expr.pTab      Points to the Table object for X.Y
80511 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
80512 **    Expr.iTable    The VDBE cursor number for X.Y
80513 **
80514 **
80515 ** To resolve result-set references, look for expression nodes of the
80516 ** form Z (with no X and Y prefix) where the Z matches the right-hand
80517 ** size of an AS clause in the result-set of a SELECT.  The Z expression
80518 ** is replaced by a copy of the left-hand side of the result-set expression.
80519 ** Table-name and function resolution occurs on the substituted expression
80520 ** tree.  For example, in:
80521 **
80522 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
80523 **
80524 ** The "x" term of the order by is replaced by "a+b" to render:
80525 **
80526 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
80527 **
80528 ** Function calls are checked to make sure that the function is
80529 ** defined and that the correct number of arguments are specified.
80530 ** If the function is an aggregate function, then the NC_HasAgg flag is
80531 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
80532 ** If an expression contains aggregate functions then the EP_Agg
80533 ** property on the expression is set.
80534 **
80535 ** An error message is left in pParse if anything is amiss.  The number
80536 ** if errors is returned.
80537 */
80538 SQLITE_PRIVATE int sqlite3ResolveExprNames(
80539   NameContext *pNC,       /* Namespace to resolve expressions in. */
80540   Expr *pExpr             /* The expression to be analyzed. */
80541 ){
80542   u16 savedHasAgg;
80543   Walker w;
80544 
80545   if( pExpr==0 ) return 0;
80546 #if SQLITE_MAX_EXPR_DEPTH>0
80547   {
80548     Parse *pParse = pNC->pParse;
80549     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
80550       return 1;
80551     }
80552     pParse->nHeight += pExpr->nHeight;
80553   }
80554 #endif
80555   savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
80556   pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
80557   memset(&w, 0, sizeof(w));
80558   w.xExprCallback = resolveExprStep;
80559   w.xSelectCallback = resolveSelectStep;
80560   w.pParse = pNC->pParse;
80561   w.u.pNC = pNC;
80562   sqlite3WalkExpr(&w, pExpr);
80563 #if SQLITE_MAX_EXPR_DEPTH>0
80564   pNC->pParse->nHeight -= pExpr->nHeight;
80565 #endif
80566   if( pNC->nErr>0 || w.pParse->nErr>0 ){
80567     ExprSetProperty(pExpr, EP_Error);
80568   }
80569   if( pNC->ncFlags & NC_HasAgg ){
80570     ExprSetProperty(pExpr, EP_Agg);
80571   }
80572   pNC->ncFlags |= savedHasAgg;
80573   return ExprHasProperty(pExpr, EP_Error);
80574 }
80575 
80576 
80577 /*
80578 ** Resolve all names in all expressions of a SELECT and in all
80579 ** decendents of the SELECT, including compounds off of p->pPrior,
80580 ** subqueries in expressions, and subqueries used as FROM clause
80581 ** terms.
80582 **
80583 ** See sqlite3ResolveExprNames() for a description of the kinds of
80584 ** transformations that occur.
80585 **
80586 ** All SELECT statements should have been expanded using
80587 ** sqlite3SelectExpand() prior to invoking this routine.
80588 */
80589 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
80590   Parse *pParse,         /* The parser context */
80591   Select *p,             /* The SELECT statement being coded. */
80592   NameContext *pOuterNC  /* Name context for parent SELECT statement */
80593 ){
80594   Walker w;
80595 
80596   assert( p!=0 );
80597   memset(&w, 0, sizeof(w));
80598   w.xExprCallback = resolveExprStep;
80599   w.xSelectCallback = resolveSelectStep;
80600   w.pParse = pParse;
80601   w.u.pNC = pOuterNC;
80602   sqlite3WalkSelect(&w, p);
80603 }
80604 
80605 /*
80606 ** Resolve names in expressions that can only reference a single table:
80607 **
80608 **    *   CHECK constraints
80609 **    *   WHERE clauses on partial indices
80610 **
80611 ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
80612 ** is set to -1 and the Expr.iColumn value is set to the column number.
80613 **
80614 ** Any errors cause an error message to be set in pParse.
80615 */
80616 SQLITE_PRIVATE void sqlite3ResolveSelfReference(
80617   Parse *pParse,      /* Parsing context */
80618   Table *pTab,        /* The table being referenced */
80619   int type,           /* NC_IsCheck or NC_PartIdx */
80620   Expr *pExpr,        /* Expression to resolve.  May be NULL. */
80621   ExprList *pList     /* Expression list to resolve.  May be NUL. */
80622 ){
80623   SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
80624   NameContext sNC;                /* Name context for pParse->pNewTable */
80625   int i;                          /* Loop counter */
80626 
80627   assert( type==NC_IsCheck || type==NC_PartIdx );
80628   memset(&sNC, 0, sizeof(sNC));
80629   memset(&sSrc, 0, sizeof(sSrc));
80630   sSrc.nSrc = 1;
80631   sSrc.a[0].zName = pTab->zName;
80632   sSrc.a[0].pTab = pTab;
80633   sSrc.a[0].iCursor = -1;
80634   sNC.pParse = pParse;
80635   sNC.pSrcList = &sSrc;
80636   sNC.ncFlags = type;
80637   if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
80638   if( pList ){
80639     for(i=0; i<pList->nExpr; i++){
80640       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
80641         return;
80642       }
80643     }
80644   }
80645 }
80646 
80647 /************** End of resolve.c *********************************************/
80648 /************** Begin file expr.c ********************************************/
80649 /*
80650 ** 2001 September 15
80651 **
80652 ** The author disclaims copyright to this source code.  In place of
80653 ** a legal notice, here is a blessing:
80654 **
80655 **    May you do good and not evil.
80656 **    May you find forgiveness for yourself and forgive others.
80657 **    May you share freely, never taking more than you give.
80658 **
80659 *************************************************************************
80660 ** This file contains routines used for analyzing expressions and
80661 ** for generating VDBE code that evaluates expressions in SQLite.
80662 */
80663 
80664 /*
80665 ** Return the 'affinity' of the expression pExpr if any.
80666 **
80667 ** If pExpr is a column, a reference to a column via an 'AS' alias,
80668 ** or a sub-select with a column as the return value, then the
80669 ** affinity of that column is returned. Otherwise, 0x00 is returned,
80670 ** indicating no affinity for the expression.
80671 **
80672 ** i.e. the WHERE clause expressions in the following statements all
80673 ** have an affinity:
80674 **
80675 ** CREATE TABLE t1(a);
80676 ** SELECT * FROM t1 WHERE a;
80677 ** SELECT a AS b FROM t1 WHERE b;
80678 ** SELECT * FROM t1 WHERE (select a from t1);
80679 */
80680 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
80681   int op;
80682   pExpr = sqlite3ExprSkipCollate(pExpr);
80683   if( pExpr->flags & EP_Generic ) return 0;
80684   op = pExpr->op;
80685   if( op==TK_SELECT ){
80686     assert( pExpr->flags&EP_xIsSelect );
80687     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
80688   }
80689 #ifndef SQLITE_OMIT_CAST
80690   if( op==TK_CAST ){
80691     assert( !ExprHasProperty(pExpr, EP_IntValue) );
80692     return sqlite3AffinityType(pExpr->u.zToken, 0);
80693   }
80694 #endif
80695   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
80696    && pExpr->pTab!=0
80697   ){
80698     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
80699     ** a TK_COLUMN but was previously evaluated and cached in a register */
80700     int j = pExpr->iColumn;
80701     if( j<0 ) return SQLITE_AFF_INTEGER;
80702     assert( pExpr->pTab && j<pExpr->pTab->nCol );
80703     return pExpr->pTab->aCol[j].affinity;
80704   }
80705   return pExpr->affinity;
80706 }
80707 
80708 /*
80709 ** Set the collating sequence for expression pExpr to be the collating
80710 ** sequence named by pToken.   Return a pointer to a new Expr node that
80711 ** implements the COLLATE operator.
80712 **
80713 ** If a memory allocation error occurs, that fact is recorded in pParse->db
80714 ** and the pExpr parameter is returned unchanged.
80715 */
80716 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
80717   Parse *pParse,           /* Parsing context */
80718   Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
80719   const Token *pCollName   /* Name of collating sequence */
80720 ){
80721   if( pCollName->n>0 ){
80722     Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
80723     if( pNew ){
80724       pNew->pLeft = pExpr;
80725       pNew->flags |= EP_Collate|EP_Skip;
80726       pExpr = pNew;
80727     }
80728   }
80729   return pExpr;
80730 }
80731 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
80732   Token s;
80733   assert( zC!=0 );
80734   s.z = zC;
80735   s.n = sqlite3Strlen30(s.z);
80736   return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
80737 }
80738 
80739 /*
80740 ** Skip over any TK_COLLATE or TK_AS operators and any unlikely()
80741 ** or likelihood() function at the root of an expression.
80742 */
80743 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
80744   while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
80745     if( ExprHasProperty(pExpr, EP_Unlikely) ){
80746       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
80747       assert( pExpr->x.pList->nExpr>0 );
80748       assert( pExpr->op==TK_FUNCTION );
80749       pExpr = pExpr->x.pList->a[0].pExpr;
80750     }else{
80751       assert( pExpr->op==TK_COLLATE || pExpr->op==TK_AS );
80752       pExpr = pExpr->pLeft;
80753     }
80754   }
80755   return pExpr;
80756 }
80757 
80758 /*
80759 ** Return the collation sequence for the expression pExpr. If
80760 ** there is no defined collating sequence, return NULL.
80761 **
80762 ** The collating sequence might be determined by a COLLATE operator
80763 ** or by the presence of a column with a defined collating sequence.
80764 ** COLLATE operators take first precedence.  Left operands take
80765 ** precedence over right operands.
80766 */
80767 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
80768   sqlite3 *db = pParse->db;
80769   CollSeq *pColl = 0;
80770   Expr *p = pExpr;
80771   while( p ){
80772     int op = p->op;
80773     if( p->flags & EP_Generic ) break;
80774     if( op==TK_CAST || op==TK_UPLUS ){
80775       p = p->pLeft;
80776       continue;
80777     }
80778     if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
80779       pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
80780       break;
80781     }
80782     if( p->pTab!=0
80783      && (op==TK_AGG_COLUMN || op==TK_COLUMN
80784           || op==TK_REGISTER || op==TK_TRIGGER)
80785     ){
80786       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
80787       ** a TK_COLUMN but was previously evaluated and cached in a register */
80788       int j = p->iColumn;
80789       if( j>=0 ){
80790         const char *zColl = p->pTab->aCol[j].zColl;
80791         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
80792       }
80793       break;
80794     }
80795     if( p->flags & EP_Collate ){
80796       if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
80797         p = p->pLeft;
80798       }else{
80799         p = p->pRight;
80800       }
80801     }else{
80802       break;
80803     }
80804   }
80805   if( sqlite3CheckCollSeq(pParse, pColl) ){
80806     pColl = 0;
80807   }
80808   return pColl;
80809 }
80810 
80811 /*
80812 ** pExpr is an operand of a comparison operator.  aff2 is the
80813 ** type affinity of the other operand.  This routine returns the
80814 ** type affinity that should be used for the comparison operator.
80815 */
80816 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
80817   char aff1 = sqlite3ExprAffinity(pExpr);
80818   if( aff1 && aff2 ){
80819     /* Both sides of the comparison are columns. If one has numeric
80820     ** affinity, use that. Otherwise use no affinity.
80821     */
80822     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
80823       return SQLITE_AFF_NUMERIC;
80824     }else{
80825       return SQLITE_AFF_NONE;
80826     }
80827   }else if( !aff1 && !aff2 ){
80828     /* Neither side of the comparison is a column.  Compare the
80829     ** results directly.
80830     */
80831     return SQLITE_AFF_NONE;
80832   }else{
80833     /* One side is a column, the other is not. Use the columns affinity. */
80834     assert( aff1==0 || aff2==0 );
80835     return (aff1 + aff2);
80836   }
80837 }
80838 
80839 /*
80840 ** pExpr is a comparison operator.  Return the type affinity that should
80841 ** be applied to both operands prior to doing the comparison.
80842 */
80843 static char comparisonAffinity(Expr *pExpr){
80844   char aff;
80845   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
80846           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
80847           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
80848   assert( pExpr->pLeft );
80849   aff = sqlite3ExprAffinity(pExpr->pLeft);
80850   if( pExpr->pRight ){
80851     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
80852   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
80853     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
80854   }else if( !aff ){
80855     aff = SQLITE_AFF_NONE;
80856   }
80857   return aff;
80858 }
80859 
80860 /*
80861 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
80862 ** idx_affinity is the affinity of an indexed column. Return true
80863 ** if the index with affinity idx_affinity may be used to implement
80864 ** the comparison in pExpr.
80865 */
80866 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
80867   char aff = comparisonAffinity(pExpr);
80868   switch( aff ){
80869     case SQLITE_AFF_NONE:
80870       return 1;
80871     case SQLITE_AFF_TEXT:
80872       return idx_affinity==SQLITE_AFF_TEXT;
80873     default:
80874       return sqlite3IsNumericAffinity(idx_affinity);
80875   }
80876 }
80877 
80878 /*
80879 ** Return the P5 value that should be used for a binary comparison
80880 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
80881 */
80882 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
80883   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
80884   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
80885   return aff;
80886 }
80887 
80888 /*
80889 ** Return a pointer to the collation sequence that should be used by
80890 ** a binary comparison operator comparing pLeft and pRight.
80891 **
80892 ** If the left hand expression has a collating sequence type, then it is
80893 ** used. Otherwise the collation sequence for the right hand expression
80894 ** is used, or the default (BINARY) if neither expression has a collating
80895 ** type.
80896 **
80897 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
80898 ** it is not considered.
80899 */
80900 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
80901   Parse *pParse,
80902   Expr *pLeft,
80903   Expr *pRight
80904 ){
80905   CollSeq *pColl;
80906   assert( pLeft );
80907   if( pLeft->flags & EP_Collate ){
80908     pColl = sqlite3ExprCollSeq(pParse, pLeft);
80909   }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
80910     pColl = sqlite3ExprCollSeq(pParse, pRight);
80911   }else{
80912     pColl = sqlite3ExprCollSeq(pParse, pLeft);
80913     if( !pColl ){
80914       pColl = sqlite3ExprCollSeq(pParse, pRight);
80915     }
80916   }
80917   return pColl;
80918 }
80919 
80920 /*
80921 ** Generate code for a comparison operator.
80922 */
80923 static int codeCompare(
80924   Parse *pParse,    /* The parsing (and code generating) context */
80925   Expr *pLeft,      /* The left operand */
80926   Expr *pRight,     /* The right operand */
80927   int opcode,       /* The comparison opcode */
80928   int in1, int in2, /* Register holding operands */
80929   int dest,         /* Jump here if true.  */
80930   int jumpIfNull    /* If true, jump if either operand is NULL */
80931 ){
80932   int p5;
80933   int addr;
80934   CollSeq *p4;
80935 
80936   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
80937   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
80938   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
80939                            (void*)p4, P4_COLLSEQ);
80940   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
80941   return addr;
80942 }
80943 
80944 #if SQLITE_MAX_EXPR_DEPTH>0
80945 /*
80946 ** Check that argument nHeight is less than or equal to the maximum
80947 ** expression depth allowed. If it is not, leave an error message in
80948 ** pParse.
80949 */
80950 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
80951   int rc = SQLITE_OK;
80952   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
80953   if( nHeight>mxHeight ){
80954     sqlite3ErrorMsg(pParse,
80955        "Expression tree is too large (maximum depth %d)", mxHeight
80956     );
80957     rc = SQLITE_ERROR;
80958   }
80959   return rc;
80960 }
80961 
80962 /* The following three functions, heightOfExpr(), heightOfExprList()
80963 ** and heightOfSelect(), are used to determine the maximum height
80964 ** of any expression tree referenced by the structure passed as the
80965 ** first argument.
80966 **
80967 ** If this maximum height is greater than the current value pointed
80968 ** to by pnHeight, the second parameter, then set *pnHeight to that
80969 ** value.
80970 */
80971 static void heightOfExpr(Expr *p, int *pnHeight){
80972   if( p ){
80973     if( p->nHeight>*pnHeight ){
80974       *pnHeight = p->nHeight;
80975     }
80976   }
80977 }
80978 static void heightOfExprList(ExprList *p, int *pnHeight){
80979   if( p ){
80980     int i;
80981     for(i=0; i<p->nExpr; i++){
80982       heightOfExpr(p->a[i].pExpr, pnHeight);
80983     }
80984   }
80985 }
80986 static void heightOfSelect(Select *p, int *pnHeight){
80987   if( p ){
80988     heightOfExpr(p->pWhere, pnHeight);
80989     heightOfExpr(p->pHaving, pnHeight);
80990     heightOfExpr(p->pLimit, pnHeight);
80991     heightOfExpr(p->pOffset, pnHeight);
80992     heightOfExprList(p->pEList, pnHeight);
80993     heightOfExprList(p->pGroupBy, pnHeight);
80994     heightOfExprList(p->pOrderBy, pnHeight);
80995     heightOfSelect(p->pPrior, pnHeight);
80996   }
80997 }
80998 
80999 /*
81000 ** Set the Expr.nHeight variable in the structure passed as an
81001 ** argument. An expression with no children, Expr.pList or
81002 ** Expr.pSelect member has a height of 1. Any other expression
81003 ** has a height equal to the maximum height of any other
81004 ** referenced Expr plus one.
81005 */
81006 static void exprSetHeight(Expr *p){
81007   int nHeight = 0;
81008   heightOfExpr(p->pLeft, &nHeight);
81009   heightOfExpr(p->pRight, &nHeight);
81010   if( ExprHasProperty(p, EP_xIsSelect) ){
81011     heightOfSelect(p->x.pSelect, &nHeight);
81012   }else{
81013     heightOfExprList(p->x.pList, &nHeight);
81014   }
81015   p->nHeight = nHeight + 1;
81016 }
81017 
81018 /*
81019 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
81020 ** the height is greater than the maximum allowed expression depth,
81021 ** leave an error in pParse.
81022 */
81023 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
81024   exprSetHeight(p);
81025   sqlite3ExprCheckHeight(pParse, p->nHeight);
81026 }
81027 
81028 /*
81029 ** Return the maximum height of any expression tree referenced
81030 ** by the select statement passed as an argument.
81031 */
81032 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
81033   int nHeight = 0;
81034   heightOfSelect(p, &nHeight);
81035   return nHeight;
81036 }
81037 #else
81038   #define exprSetHeight(y)
81039 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
81040 
81041 /*
81042 ** This routine is the core allocator for Expr nodes.
81043 **
81044 ** Construct a new expression node and return a pointer to it.  Memory
81045 ** for this node and for the pToken argument is a single allocation
81046 ** obtained from sqlite3DbMalloc().  The calling function
81047 ** is responsible for making sure the node eventually gets freed.
81048 **
81049 ** If dequote is true, then the token (if it exists) is dequoted.
81050 ** If dequote is false, no dequoting is performance.  The deQuote
81051 ** parameter is ignored if pToken is NULL or if the token does not
81052 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
81053 ** then the EP_DblQuoted flag is set on the expression node.
81054 **
81055 ** Special case:  If op==TK_INTEGER and pToken points to a string that
81056 ** can be translated into a 32-bit integer, then the token is not
81057 ** stored in u.zToken.  Instead, the integer values is written
81058 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
81059 ** is allocated to hold the integer text and the dequote flag is ignored.
81060 */
81061 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
81062   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
81063   int op,                 /* Expression opcode */
81064   const Token *pToken,    /* Token argument.  Might be NULL */
81065   int dequote             /* True to dequote */
81066 ){
81067   Expr *pNew;
81068   int nExtra = 0;
81069   int iValue = 0;
81070 
81071   if( pToken ){
81072     if( op!=TK_INTEGER || pToken->z==0
81073           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
81074       nExtra = pToken->n+1;
81075       assert( iValue>=0 );
81076     }
81077   }
81078   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
81079   if( pNew ){
81080     pNew->op = (u8)op;
81081     pNew->iAgg = -1;
81082     if( pToken ){
81083       if( nExtra==0 ){
81084         pNew->flags |= EP_IntValue;
81085         pNew->u.iValue = iValue;
81086       }else{
81087         int c;
81088         pNew->u.zToken = (char*)&pNew[1];
81089         assert( pToken->z!=0 || pToken->n==0 );
81090         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
81091         pNew->u.zToken[pToken->n] = 0;
81092         if( dequote && nExtra>=3
81093              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
81094           sqlite3Dequote(pNew->u.zToken);
81095           if( c=='"' ) pNew->flags |= EP_DblQuoted;
81096         }
81097       }
81098     }
81099 #if SQLITE_MAX_EXPR_DEPTH>0
81100     pNew->nHeight = 1;
81101 #endif
81102   }
81103   return pNew;
81104 }
81105 
81106 /*
81107 ** Allocate a new expression node from a zero-terminated token that has
81108 ** already been dequoted.
81109 */
81110 SQLITE_PRIVATE Expr *sqlite3Expr(
81111   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
81112   int op,                 /* Expression opcode */
81113   const char *zToken      /* Token argument.  Might be NULL */
81114 ){
81115   Token x;
81116   x.z = zToken;
81117   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
81118   return sqlite3ExprAlloc(db, op, &x, 0);
81119 }
81120 
81121 /*
81122 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
81123 **
81124 ** If pRoot==NULL that means that a memory allocation error has occurred.
81125 ** In that case, delete the subtrees pLeft and pRight.
81126 */
81127 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
81128   sqlite3 *db,
81129   Expr *pRoot,
81130   Expr *pLeft,
81131   Expr *pRight
81132 ){
81133   if( pRoot==0 ){
81134     assert( db->mallocFailed );
81135     sqlite3ExprDelete(db, pLeft);
81136     sqlite3ExprDelete(db, pRight);
81137   }else{
81138     if( pRight ){
81139       pRoot->pRight = pRight;
81140       pRoot->flags |= EP_Collate & pRight->flags;
81141     }
81142     if( pLeft ){
81143       pRoot->pLeft = pLeft;
81144       pRoot->flags |= EP_Collate & pLeft->flags;
81145     }
81146     exprSetHeight(pRoot);
81147   }
81148 }
81149 
81150 /*
81151 ** Allocate an Expr node which joins as many as two subtrees.
81152 **
81153 ** One or both of the subtrees can be NULL.  Return a pointer to the new
81154 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
81155 ** free the subtrees and return NULL.
81156 */
81157 SQLITE_PRIVATE Expr *sqlite3PExpr(
81158   Parse *pParse,          /* Parsing context */
81159   int op,                 /* Expression opcode */
81160   Expr *pLeft,            /* Left operand */
81161   Expr *pRight,           /* Right operand */
81162   const Token *pToken     /* Argument token */
81163 ){
81164   Expr *p;
81165   if( op==TK_AND && pLeft && pRight ){
81166     /* Take advantage of short-circuit false optimization for AND */
81167     p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
81168   }else{
81169     p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
81170     sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
81171   }
81172   if( p ) {
81173     sqlite3ExprCheckHeight(pParse, p->nHeight);
81174   }
81175   return p;
81176 }
81177 
81178 /*
81179 ** If the expression is always either TRUE or FALSE (respectively),
81180 ** then return 1.  If one cannot determine the truth value of the
81181 ** expression at compile-time return 0.
81182 **
81183 ** This is an optimization.  If is OK to return 0 here even if
81184 ** the expression really is always false or false (a false negative).
81185 ** But it is a bug to return 1 if the expression might have different
81186 ** boolean values in different circumstances (a false positive.)
81187 **
81188 ** Note that if the expression is part of conditional for a
81189 ** LEFT JOIN, then we cannot determine at compile-time whether or not
81190 ** is it true or false, so always return 0.
81191 */
81192 static int exprAlwaysTrue(Expr *p){
81193   int v = 0;
81194   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
81195   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
81196   return v!=0;
81197 }
81198 static int exprAlwaysFalse(Expr *p){
81199   int v = 0;
81200   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
81201   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
81202   return v==0;
81203 }
81204 
81205 /*
81206 ** Join two expressions using an AND operator.  If either expression is
81207 ** NULL, then just return the other expression.
81208 **
81209 ** If one side or the other of the AND is known to be false, then instead
81210 ** of returning an AND expression, just return a constant expression with
81211 ** a value of false.
81212 */
81213 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
81214   if( pLeft==0 ){
81215     return pRight;
81216   }else if( pRight==0 ){
81217     return pLeft;
81218   }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
81219     sqlite3ExprDelete(db, pLeft);
81220     sqlite3ExprDelete(db, pRight);
81221     return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
81222   }else{
81223     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
81224     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
81225     return pNew;
81226   }
81227 }
81228 
81229 /*
81230 ** Construct a new expression node for a function with multiple
81231 ** arguments.
81232 */
81233 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
81234   Expr *pNew;
81235   sqlite3 *db = pParse->db;
81236   assert( pToken );
81237   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
81238   if( pNew==0 ){
81239     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
81240     return 0;
81241   }
81242   pNew->x.pList = pList;
81243   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
81244   sqlite3ExprSetHeight(pParse, pNew);
81245   return pNew;
81246 }
81247 
81248 /*
81249 ** Assign a variable number to an expression that encodes a wildcard
81250 ** in the original SQL statement.
81251 **
81252 ** Wildcards consisting of a single "?" are assigned the next sequential
81253 ** variable number.
81254 **
81255 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
81256 ** sure "nnn" is not too be to avoid a denial of service attack when
81257 ** the SQL statement comes from an external source.
81258 **
81259 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
81260 ** as the previous instance of the same wildcard.  Or if this is the first
81261 ** instance of the wildcard, the next sequential variable number is
81262 ** assigned.
81263 */
81264 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
81265   sqlite3 *db = pParse->db;
81266   const char *z;
81267 
81268   if( pExpr==0 ) return;
81269   assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
81270   z = pExpr->u.zToken;
81271   assert( z!=0 );
81272   assert( z[0]!=0 );
81273   if( z[1]==0 ){
81274     /* Wildcard of the form "?".  Assign the next variable number */
81275     assert( z[0]=='?' );
81276     pExpr->iColumn = (ynVar)(++pParse->nVar);
81277   }else{
81278     ynVar x = 0;
81279     u32 n = sqlite3Strlen30(z);
81280     if( z[0]=='?' ){
81281       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
81282       ** use it as the variable number */
81283       i64 i;
81284       int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
81285       pExpr->iColumn = x = (ynVar)i;
81286       testcase( i==0 );
81287       testcase( i==1 );
81288       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
81289       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
81290       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
81291         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
81292             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
81293         x = 0;
81294       }
81295       if( i>pParse->nVar ){
81296         pParse->nVar = (int)i;
81297       }
81298     }else{
81299       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
81300       ** number as the prior appearance of the same name, or if the name
81301       ** has never appeared before, reuse the same variable number
81302       */
81303       ynVar i;
81304       for(i=0; i<pParse->nzVar; i++){
81305         if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
81306           pExpr->iColumn = x = (ynVar)i+1;
81307           break;
81308         }
81309       }
81310       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
81311     }
81312     if( x>0 ){
81313       if( x>pParse->nzVar ){
81314         char **a;
81315         a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
81316         if( a==0 ) return;  /* Error reported through db->mallocFailed */
81317         pParse->azVar = a;
81318         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
81319         pParse->nzVar = x;
81320       }
81321       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
81322         sqlite3DbFree(db, pParse->azVar[x-1]);
81323         pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
81324       }
81325     }
81326   }
81327   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
81328     sqlite3ErrorMsg(pParse, "too many SQL variables");
81329   }
81330 }
81331 
81332 /*
81333 ** Recursively delete an expression tree.
81334 */
81335 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
81336   if( p==0 ) return;
81337   /* Sanity check: Assert that the IntValue is non-negative if it exists */
81338   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
81339   if( !ExprHasProperty(p, EP_TokenOnly) ){
81340     /* The Expr.x union is never used at the same time as Expr.pRight */
81341     assert( p->x.pList==0 || p->pRight==0 );
81342     sqlite3ExprDelete(db, p->pLeft);
81343     sqlite3ExprDelete(db, p->pRight);
81344     if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
81345     if( ExprHasProperty(p, EP_xIsSelect) ){
81346       sqlite3SelectDelete(db, p->x.pSelect);
81347     }else{
81348       sqlite3ExprListDelete(db, p->x.pList);
81349     }
81350   }
81351   if( !ExprHasProperty(p, EP_Static) ){
81352     sqlite3DbFree(db, p);
81353   }
81354 }
81355 
81356 /*
81357 ** Return the number of bytes allocated for the expression structure
81358 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
81359 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
81360 */
81361 static int exprStructSize(Expr *p){
81362   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
81363   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
81364   return EXPR_FULLSIZE;
81365 }
81366 
81367 /*
81368 ** The dupedExpr*Size() routines each return the number of bytes required
81369 ** to store a copy of an expression or expression tree.  They differ in
81370 ** how much of the tree is measured.
81371 **
81372 **     dupedExprStructSize()     Size of only the Expr structure
81373 **     dupedExprNodeSize()       Size of Expr + space for token
81374 **     dupedExprSize()           Expr + token + subtree components
81375 **
81376 ***************************************************************************
81377 **
81378 ** The dupedExprStructSize() function returns two values OR-ed together:
81379 ** (1) the space required for a copy of the Expr structure only and
81380 ** (2) the EP_xxx flags that indicate what the structure size should be.
81381 ** The return values is always one of:
81382 **
81383 **      EXPR_FULLSIZE
81384 **      EXPR_REDUCEDSIZE   | EP_Reduced
81385 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
81386 **
81387 ** The size of the structure can be found by masking the return value
81388 ** of this routine with 0xfff.  The flags can be found by masking the
81389 ** return value with EP_Reduced|EP_TokenOnly.
81390 **
81391 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
81392 ** (unreduced) Expr objects as they or originally constructed by the parser.
81393 ** During expression analysis, extra information is computed and moved into
81394 ** later parts of teh Expr object and that extra information might get chopped
81395 ** off if the expression is reduced.  Note also that it does not work to
81396 ** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
81397 ** to reduce a pristine expression tree from the parser.  The implementation
81398 ** of dupedExprStructSize() contain multiple assert() statements that attempt
81399 ** to enforce this constraint.
81400 */
81401 static int dupedExprStructSize(Expr *p, int flags){
81402   int nSize;
81403   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
81404   assert( EXPR_FULLSIZE<=0xfff );
81405   assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
81406   if( 0==(flags&EXPRDUP_REDUCE) ){
81407     nSize = EXPR_FULLSIZE;
81408   }else{
81409     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
81410     assert( !ExprHasProperty(p, EP_FromJoin) );
81411     assert( !ExprHasProperty(p, EP_MemToken) );
81412     assert( !ExprHasProperty(p, EP_NoReduce) );
81413     if( p->pLeft || p->x.pList ){
81414       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
81415     }else{
81416       assert( p->pRight==0 );
81417       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
81418     }
81419   }
81420   return nSize;
81421 }
81422 
81423 /*
81424 ** This function returns the space in bytes required to store the copy
81425 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
81426 ** string is defined.)
81427 */
81428 static int dupedExprNodeSize(Expr *p, int flags){
81429   int nByte = dupedExprStructSize(p, flags) & 0xfff;
81430   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
81431     nByte += sqlite3Strlen30(p->u.zToken)+1;
81432   }
81433   return ROUND8(nByte);
81434 }
81435 
81436 /*
81437 ** Return the number of bytes required to create a duplicate of the
81438 ** expression passed as the first argument. The second argument is a
81439 ** mask containing EXPRDUP_XXX flags.
81440 **
81441 ** The value returned includes space to create a copy of the Expr struct
81442 ** itself and the buffer referred to by Expr.u.zToken, if any.
81443 **
81444 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
81445 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
81446 ** and Expr.pRight variables (but not for any structures pointed to or
81447 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
81448 */
81449 static int dupedExprSize(Expr *p, int flags){
81450   int nByte = 0;
81451   if( p ){
81452     nByte = dupedExprNodeSize(p, flags);
81453     if( flags&EXPRDUP_REDUCE ){
81454       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
81455     }
81456   }
81457   return nByte;
81458 }
81459 
81460 /*
81461 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
81462 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
81463 ** to store the copy of expression p, the copies of p->u.zToken
81464 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
81465 ** if any. Before returning, *pzBuffer is set to the first byte past the
81466 ** portion of the buffer copied into by this function.
81467 */
81468 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
81469   Expr *pNew = 0;                      /* Value to return */
81470   if( p ){
81471     const int isReduced = (flags&EXPRDUP_REDUCE);
81472     u8 *zAlloc;
81473     u32 staticFlag = 0;
81474 
81475     assert( pzBuffer==0 || isReduced );
81476 
81477     /* Figure out where to write the new Expr structure. */
81478     if( pzBuffer ){
81479       zAlloc = *pzBuffer;
81480       staticFlag = EP_Static;
81481     }else{
81482       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
81483     }
81484     pNew = (Expr *)zAlloc;
81485 
81486     if( pNew ){
81487       /* Set nNewSize to the size allocated for the structure pointed to
81488       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
81489       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
81490       ** by the copy of the p->u.zToken string (if any).
81491       */
81492       const unsigned nStructSize = dupedExprStructSize(p, flags);
81493       const int nNewSize = nStructSize & 0xfff;
81494       int nToken;
81495       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
81496         nToken = sqlite3Strlen30(p->u.zToken) + 1;
81497       }else{
81498         nToken = 0;
81499       }
81500       if( isReduced ){
81501         assert( ExprHasProperty(p, EP_Reduced)==0 );
81502         memcpy(zAlloc, p, nNewSize);
81503       }else{
81504         int nSize = exprStructSize(p);
81505         memcpy(zAlloc, p, nSize);
81506         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
81507       }
81508 
81509       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
81510       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
81511       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
81512       pNew->flags |= staticFlag;
81513 
81514       /* Copy the p->u.zToken string, if any. */
81515       if( nToken ){
81516         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
81517         memcpy(zToken, p->u.zToken, nToken);
81518       }
81519 
81520       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
81521         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
81522         if( ExprHasProperty(p, EP_xIsSelect) ){
81523           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
81524         }else{
81525           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
81526         }
81527       }
81528 
81529       /* Fill in pNew->pLeft and pNew->pRight. */
81530       if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
81531         zAlloc += dupedExprNodeSize(p, flags);
81532         if( ExprHasProperty(pNew, EP_Reduced) ){
81533           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
81534           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
81535         }
81536         if( pzBuffer ){
81537           *pzBuffer = zAlloc;
81538         }
81539       }else{
81540         if( !ExprHasProperty(p, EP_TokenOnly) ){
81541           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
81542           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
81543         }
81544       }
81545 
81546     }
81547   }
81548   return pNew;
81549 }
81550 
81551 /*
81552 ** Create and return a deep copy of the object passed as the second
81553 ** argument. If an OOM condition is encountered, NULL is returned
81554 ** and the db->mallocFailed flag set.
81555 */
81556 #ifndef SQLITE_OMIT_CTE
81557 static With *withDup(sqlite3 *db, With *p){
81558   With *pRet = 0;
81559   if( p ){
81560     int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
81561     pRet = sqlite3DbMallocZero(db, nByte);
81562     if( pRet ){
81563       int i;
81564       pRet->nCte = p->nCte;
81565       for(i=0; i<p->nCte; i++){
81566         pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
81567         pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
81568         pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
81569       }
81570     }
81571   }
81572   return pRet;
81573 }
81574 #else
81575 # define withDup(x,y) 0
81576 #endif
81577 
81578 /*
81579 ** The following group of routines make deep copies of expressions,
81580 ** expression lists, ID lists, and select statements.  The copies can
81581 ** be deleted (by being passed to their respective ...Delete() routines)
81582 ** without effecting the originals.
81583 **
81584 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
81585 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
81586 ** by subsequent calls to sqlite*ListAppend() routines.
81587 **
81588 ** Any tables that the SrcList might point to are not duplicated.
81589 **
81590 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
81591 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
81592 ** truncated version of the usual Expr structure that will be stored as
81593 ** part of the in-memory representation of the database schema.
81594 */
81595 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
81596   return exprDup(db, p, flags, 0);
81597 }
81598 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
81599   ExprList *pNew;
81600   struct ExprList_item *pItem, *pOldItem;
81601   int i;
81602   if( p==0 ) return 0;
81603   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
81604   if( pNew==0 ) return 0;
81605   pNew->nExpr = i = p->nExpr;
81606   if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
81607   pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
81608   if( pItem==0 ){
81609     sqlite3DbFree(db, pNew);
81610     return 0;
81611   }
81612   pOldItem = p->a;
81613   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
81614     Expr *pOldExpr = pOldItem->pExpr;
81615     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
81616     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
81617     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
81618     pItem->sortOrder = pOldItem->sortOrder;
81619     pItem->done = 0;
81620     pItem->bSpanIsTab = pOldItem->bSpanIsTab;
81621     pItem->u = pOldItem->u;
81622   }
81623   return pNew;
81624 }
81625 
81626 /*
81627 ** If cursors, triggers, views and subqueries are all omitted from
81628 ** the build, then none of the following routines, except for
81629 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
81630 ** called with a NULL argument.
81631 */
81632 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
81633  || !defined(SQLITE_OMIT_SUBQUERY)
81634 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
81635   SrcList *pNew;
81636   int i;
81637   int nByte;
81638   if( p==0 ) return 0;
81639   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
81640   pNew = sqlite3DbMallocRaw(db, nByte );
81641   if( pNew==0 ) return 0;
81642   pNew->nSrc = pNew->nAlloc = p->nSrc;
81643   for(i=0; i<p->nSrc; i++){
81644     struct SrcList_item *pNewItem = &pNew->a[i];
81645     struct SrcList_item *pOldItem = &p->a[i];
81646     Table *pTab;
81647     pNewItem->pSchema = pOldItem->pSchema;
81648     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
81649     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
81650     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
81651     pNewItem->jointype = pOldItem->jointype;
81652     pNewItem->iCursor = pOldItem->iCursor;
81653     pNewItem->addrFillSub = pOldItem->addrFillSub;
81654     pNewItem->regReturn = pOldItem->regReturn;
81655     pNewItem->isCorrelated = pOldItem->isCorrelated;
81656     pNewItem->viaCoroutine = pOldItem->viaCoroutine;
81657     pNewItem->isRecursive = pOldItem->isRecursive;
81658     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
81659     pNewItem->notIndexed = pOldItem->notIndexed;
81660     pNewItem->pIndex = pOldItem->pIndex;
81661     pTab = pNewItem->pTab = pOldItem->pTab;
81662     if( pTab ){
81663       pTab->nRef++;
81664     }
81665     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
81666     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
81667     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
81668     pNewItem->colUsed = pOldItem->colUsed;
81669   }
81670   return pNew;
81671 }
81672 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
81673   IdList *pNew;
81674   int i;
81675   if( p==0 ) return 0;
81676   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
81677   if( pNew==0 ) return 0;
81678   pNew->nId = p->nId;
81679   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
81680   if( pNew->a==0 ){
81681     sqlite3DbFree(db, pNew);
81682     return 0;
81683   }
81684   /* Note that because the size of the allocation for p->a[] is not
81685   ** necessarily a power of two, sqlite3IdListAppend() may not be called
81686   ** on the duplicate created by this function. */
81687   for(i=0; i<p->nId; i++){
81688     struct IdList_item *pNewItem = &pNew->a[i];
81689     struct IdList_item *pOldItem = &p->a[i];
81690     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
81691     pNewItem->idx = pOldItem->idx;
81692   }
81693   return pNew;
81694 }
81695 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
81696   Select *pNew, *pPrior;
81697   if( p==0 ) return 0;
81698   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
81699   if( pNew==0 ) return 0;
81700   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
81701   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
81702   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
81703   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
81704   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
81705   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
81706   pNew->op = p->op;
81707   pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
81708   if( pPrior ) pPrior->pNext = pNew;
81709   pNew->pNext = 0;
81710   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
81711   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
81712   pNew->iLimit = 0;
81713   pNew->iOffset = 0;
81714   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
81715   pNew->addrOpenEphm[0] = -1;
81716   pNew->addrOpenEphm[1] = -1;
81717   pNew->nSelectRow = p->nSelectRow;
81718   pNew->pWith = withDup(db, p->pWith);
81719   sqlite3SelectSetName(pNew, p->zSelName);
81720   return pNew;
81721 }
81722 #else
81723 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
81724   assert( p==0 );
81725   return 0;
81726 }
81727 #endif
81728 
81729 
81730 /*
81731 ** Add a new element to the end of an expression list.  If pList is
81732 ** initially NULL, then create a new expression list.
81733 **
81734 ** If a memory allocation error occurs, the entire list is freed and
81735 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
81736 ** that the new entry was successfully appended.
81737 */
81738 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
81739   Parse *pParse,          /* Parsing context */
81740   ExprList *pList,        /* List to which to append. Might be NULL */
81741   Expr *pExpr             /* Expression to be appended. Might be NULL */
81742 ){
81743   sqlite3 *db = pParse->db;
81744   if( pList==0 ){
81745     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
81746     if( pList==0 ){
81747       goto no_mem;
81748     }
81749     pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
81750     if( pList->a==0 ) goto no_mem;
81751   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
81752     struct ExprList_item *a;
81753     assert( pList->nExpr>0 );
81754     a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
81755     if( a==0 ){
81756       goto no_mem;
81757     }
81758     pList->a = a;
81759   }
81760   assert( pList->a!=0 );
81761   if( 1 ){
81762     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
81763     memset(pItem, 0, sizeof(*pItem));
81764     pItem->pExpr = pExpr;
81765   }
81766   return pList;
81767 
81768 no_mem:
81769   /* Avoid leaking memory if malloc has failed. */
81770   sqlite3ExprDelete(db, pExpr);
81771   sqlite3ExprListDelete(db, pList);
81772   return 0;
81773 }
81774 
81775 /*
81776 ** Set the ExprList.a[].zName element of the most recently added item
81777 ** on the expression list.
81778 **
81779 ** pList might be NULL following an OOM error.  But pName should never be
81780 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
81781 ** is set.
81782 */
81783 SQLITE_PRIVATE void sqlite3ExprListSetName(
81784   Parse *pParse,          /* Parsing context */
81785   ExprList *pList,        /* List to which to add the span. */
81786   Token *pName,           /* Name to be added */
81787   int dequote             /* True to cause the name to be dequoted */
81788 ){
81789   assert( pList!=0 || pParse->db->mallocFailed!=0 );
81790   if( pList ){
81791     struct ExprList_item *pItem;
81792     assert( pList->nExpr>0 );
81793     pItem = &pList->a[pList->nExpr-1];
81794     assert( pItem->zName==0 );
81795     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
81796     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
81797   }
81798 }
81799 
81800 /*
81801 ** Set the ExprList.a[].zSpan element of the most recently added item
81802 ** on the expression list.
81803 **
81804 ** pList might be NULL following an OOM error.  But pSpan should never be
81805 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
81806 ** is set.
81807 */
81808 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
81809   Parse *pParse,          /* Parsing context */
81810   ExprList *pList,        /* List to which to add the span. */
81811   ExprSpan *pSpan         /* The span to be added */
81812 ){
81813   sqlite3 *db = pParse->db;
81814   assert( pList!=0 || db->mallocFailed!=0 );
81815   if( pList ){
81816     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
81817     assert( pList->nExpr>0 );
81818     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
81819     sqlite3DbFree(db, pItem->zSpan);
81820     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
81821                                     (int)(pSpan->zEnd - pSpan->zStart));
81822   }
81823 }
81824 
81825 /*
81826 ** If the expression list pEList contains more than iLimit elements,
81827 ** leave an error message in pParse.
81828 */
81829 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
81830   Parse *pParse,
81831   ExprList *pEList,
81832   const char *zObject
81833 ){
81834   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
81835   testcase( pEList && pEList->nExpr==mx );
81836   testcase( pEList && pEList->nExpr==mx+1 );
81837   if( pEList && pEList->nExpr>mx ){
81838     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
81839   }
81840 }
81841 
81842 /*
81843 ** Delete an entire expression list.
81844 */
81845 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
81846   int i;
81847   struct ExprList_item *pItem;
81848   if( pList==0 ) return;
81849   assert( pList->a!=0 || pList->nExpr==0 );
81850   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
81851     sqlite3ExprDelete(db, pItem->pExpr);
81852     sqlite3DbFree(db, pItem->zName);
81853     sqlite3DbFree(db, pItem->zSpan);
81854   }
81855   sqlite3DbFree(db, pList->a);
81856   sqlite3DbFree(db, pList);
81857 }
81858 
81859 /*
81860 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
81861 ** to an integer.  These routines are checking an expression to see
81862 ** if it is a constant.  Set *Walker.u.i to 0 if the expression is
81863 ** not constant.
81864 **
81865 ** These callback routines are used to implement the following:
81866 **
81867 **     sqlite3ExprIsConstant()                  pWalker->u.i==1
81868 **     sqlite3ExprIsConstantNotJoin()           pWalker->u.i==2
81869 **     sqlite3ExprIsConstantOrFunction()        pWalker->u.i==3 or 4
81870 **
81871 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
81872 ** in a CREATE TABLE statement.  The Walker.u.i value is 4 when parsing
81873 ** an existing schema and 3 when processing a new statement.  A bound
81874 ** parameter raises an error for new statements, but is silently converted
81875 ** to NULL for existing schemas.  This allows sqlite_master tables that
81876 ** contain a bound parameter because they were generated by older versions
81877 ** of SQLite to be parsed by newer versions of SQLite without raising a
81878 ** malformed schema error.
81879 */
81880 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
81881 
81882   /* If pWalker->u.i is 2 then any term of the expression that comes from
81883   ** the ON or USING clauses of a join disqualifies the expression
81884   ** from being considered constant. */
81885   if( pWalker->u.i==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
81886     pWalker->u.i = 0;
81887     return WRC_Abort;
81888   }
81889 
81890   switch( pExpr->op ){
81891     /* Consider functions to be constant if all their arguments are constant
81892     ** and either pWalker->u.i==3 or 4 or the function as the SQLITE_FUNC_CONST
81893     ** flag. */
81894     case TK_FUNCTION:
81895       if( pWalker->u.i>=3 || ExprHasProperty(pExpr,EP_Constant) ){
81896         return WRC_Continue;
81897       }
81898       /* Fall through */
81899     case TK_ID:
81900     case TK_COLUMN:
81901     case TK_AGG_FUNCTION:
81902     case TK_AGG_COLUMN:
81903       testcase( pExpr->op==TK_ID );
81904       testcase( pExpr->op==TK_COLUMN );
81905       testcase( pExpr->op==TK_AGG_FUNCTION );
81906       testcase( pExpr->op==TK_AGG_COLUMN );
81907       pWalker->u.i = 0;
81908       return WRC_Abort;
81909     case TK_VARIABLE:
81910       if( pWalker->u.i==4 ){
81911         /* Silently convert bound parameters that appear inside of CREATE
81912         ** statements into a NULL when parsing the CREATE statement text out
81913         ** of the sqlite_master table */
81914         pExpr->op = TK_NULL;
81915       }else if( pWalker->u.i==3 ){
81916         /* A bound parameter in a CREATE statement that originates from
81917         ** sqlite3_prepare() causes an error */
81918         pWalker->u.i = 0;
81919         return WRC_Abort;
81920       }
81921       /* Fall through */
81922     default:
81923       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
81924       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
81925       return WRC_Continue;
81926   }
81927 }
81928 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
81929   UNUSED_PARAMETER(NotUsed);
81930   pWalker->u.i = 0;
81931   return WRC_Abort;
81932 }
81933 static int exprIsConst(Expr *p, int initFlag){
81934   Walker w;
81935   memset(&w, 0, sizeof(w));
81936   w.u.i = initFlag;
81937   w.xExprCallback = exprNodeIsConstant;
81938   w.xSelectCallback = selectNodeIsConstant;
81939   sqlite3WalkExpr(&w, p);
81940   return w.u.i;
81941 }
81942 
81943 /*
81944 ** Walk an expression tree.  Return 1 if the expression is constant
81945 ** and 0 if it involves variables or function calls.
81946 **
81947 ** For the purposes of this function, a double-quoted string (ex: "abc")
81948 ** is considered a variable but a single-quoted string (ex: 'abc') is
81949 ** a constant.
81950 */
81951 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
81952   return exprIsConst(p, 1);
81953 }
81954 
81955 /*
81956 ** Walk an expression tree.  Return 1 if the expression is constant
81957 ** that does no originate from the ON or USING clauses of a join.
81958 ** Return 0 if it involves variables or function calls or terms from
81959 ** an ON or USING clause.
81960 */
81961 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
81962   return exprIsConst(p, 2);
81963 }
81964 
81965 /*
81966 ** Walk an expression tree.  Return 1 if the expression is constant
81967 ** or a function call with constant arguments.  Return and 0 if there
81968 ** are any variables.
81969 **
81970 ** For the purposes of this function, a double-quoted string (ex: "abc")
81971 ** is considered a variable but a single-quoted string (ex: 'abc') is
81972 ** a constant.
81973 */
81974 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
81975   assert( isInit==0 || isInit==1 );
81976   return exprIsConst(p, 3+isInit);
81977 }
81978 
81979 /*
81980 ** If the expression p codes a constant integer that is small enough
81981 ** to fit in a 32-bit integer, return 1 and put the value of the integer
81982 ** in *pValue.  If the expression is not an integer or if it is too big
81983 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
81984 */
81985 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
81986   int rc = 0;
81987 
81988   /* If an expression is an integer literal that fits in a signed 32-bit
81989   ** integer, then the EP_IntValue flag will have already been set */
81990   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
81991            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
81992 
81993   if( p->flags & EP_IntValue ){
81994     *pValue = p->u.iValue;
81995     return 1;
81996   }
81997   switch( p->op ){
81998     case TK_UPLUS: {
81999       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
82000       break;
82001     }
82002     case TK_UMINUS: {
82003       int v;
82004       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
82005         assert( v!=(-2147483647-1) );
82006         *pValue = -v;
82007         rc = 1;
82008       }
82009       break;
82010     }
82011     default: break;
82012   }
82013   return rc;
82014 }
82015 
82016 /*
82017 ** Return FALSE if there is no chance that the expression can be NULL.
82018 **
82019 ** If the expression might be NULL or if the expression is too complex
82020 ** to tell return TRUE.
82021 **
82022 ** This routine is used as an optimization, to skip OP_IsNull opcodes
82023 ** when we know that a value cannot be NULL.  Hence, a false positive
82024 ** (returning TRUE when in fact the expression can never be NULL) might
82025 ** be a small performance hit but is otherwise harmless.  On the other
82026 ** hand, a false negative (returning FALSE when the result could be NULL)
82027 ** will likely result in an incorrect answer.  So when in doubt, return
82028 ** TRUE.
82029 */
82030 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
82031   u8 op;
82032   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
82033   op = p->op;
82034   if( op==TK_REGISTER ) op = p->op2;
82035   switch( op ){
82036     case TK_INTEGER:
82037     case TK_STRING:
82038     case TK_FLOAT:
82039     case TK_BLOB:
82040       return 0;
82041     case TK_COLUMN:
82042       assert( p->pTab!=0 );
82043       return p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0;
82044     default:
82045       return 1;
82046   }
82047 }
82048 
82049 /*
82050 ** Return TRUE if the given expression is a constant which would be
82051 ** unchanged by OP_Affinity with the affinity given in the second
82052 ** argument.
82053 **
82054 ** This routine is used to determine if the OP_Affinity operation
82055 ** can be omitted.  When in doubt return FALSE.  A false negative
82056 ** is harmless.  A false positive, however, can result in the wrong
82057 ** answer.
82058 */
82059 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
82060   u8 op;
82061   if( aff==SQLITE_AFF_NONE ) return 1;
82062   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
82063   op = p->op;
82064   if( op==TK_REGISTER ) op = p->op2;
82065   switch( op ){
82066     case TK_INTEGER: {
82067       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
82068     }
82069     case TK_FLOAT: {
82070       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
82071     }
82072     case TK_STRING: {
82073       return aff==SQLITE_AFF_TEXT;
82074     }
82075     case TK_BLOB: {
82076       return 1;
82077     }
82078     case TK_COLUMN: {
82079       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
82080       return p->iColumn<0
82081           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
82082     }
82083     default: {
82084       return 0;
82085     }
82086   }
82087 }
82088 
82089 /*
82090 ** Return TRUE if the given string is a row-id column name.
82091 */
82092 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
82093   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
82094   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
82095   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
82096   return 0;
82097 }
82098 
82099 /*
82100 ** Return true if we are able to the IN operator optimization on a
82101 ** query of the form
82102 **
82103 **       x IN (SELECT ...)
82104 **
82105 ** Where the SELECT... clause is as specified by the parameter to this
82106 ** routine.
82107 **
82108 ** The Select object passed in has already been preprocessed and no
82109 ** errors have been found.
82110 */
82111 #ifndef SQLITE_OMIT_SUBQUERY
82112 static int isCandidateForInOpt(Select *p){
82113   SrcList *pSrc;
82114   ExprList *pEList;
82115   Table *pTab;
82116   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
82117   if( p->pPrior ) return 0;              /* Not a compound SELECT */
82118   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
82119     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
82120     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
82121     return 0; /* No DISTINCT keyword and no aggregate functions */
82122   }
82123   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
82124   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
82125   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
82126   if( p->pWhere ) return 0;              /* Has no WHERE clause */
82127   pSrc = p->pSrc;
82128   assert( pSrc!=0 );
82129   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
82130   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
82131   pTab = pSrc->a[0].pTab;
82132   if( NEVER(pTab==0) ) return 0;
82133   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
82134   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
82135   pEList = p->pEList;
82136   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
82137   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
82138   return 1;
82139 }
82140 #endif /* SQLITE_OMIT_SUBQUERY */
82141 
82142 /*
82143 ** Code an OP_Once instruction and allocate space for its flag. Return the
82144 ** address of the new instruction.
82145 */
82146 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
82147   Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
82148   return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
82149 }
82150 
82151 /*
82152 ** Generate code that checks the left-most column of index table iCur to see if
82153 ** it contains any NULL entries.  Cause the register at regHasNull to be set
82154 ** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
82155 ** to be set to NULL if iCur contains one or more NULL values.
82156 */
82157 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
82158   int j1;
82159   sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
82160   j1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
82161   sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
82162   sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
82163   VdbeComment((v, "first_entry_in(%d)", iCur));
82164   sqlite3VdbeJumpHere(v, j1);
82165 }
82166 
82167 
82168 #ifndef SQLITE_OMIT_SUBQUERY
82169 /*
82170 ** The argument is an IN operator with a list (not a subquery) on the
82171 ** right-hand side.  Return TRUE if that list is constant.
82172 */
82173 static int sqlite3InRhsIsConstant(Expr *pIn){
82174   Expr *pLHS;
82175   int res;
82176   assert( !ExprHasProperty(pIn, EP_xIsSelect) );
82177   pLHS = pIn->pLeft;
82178   pIn->pLeft = 0;
82179   res = sqlite3ExprIsConstant(pIn);
82180   pIn->pLeft = pLHS;
82181   return res;
82182 }
82183 #endif
82184 
82185 /*
82186 ** This function is used by the implementation of the IN (...) operator.
82187 ** The pX parameter is the expression on the RHS of the IN operator, which
82188 ** might be either a list of expressions or a subquery.
82189 **
82190 ** The job of this routine is to find or create a b-tree object that can
82191 ** be used either to test for membership in the RHS set or to iterate through
82192 ** all members of the RHS set, skipping duplicates.
82193 **
82194 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
82195 ** and pX->iTable is set to the index of that cursor.
82196 **
82197 ** The returned value of this function indicates the b-tree type, as follows:
82198 **
82199 **   IN_INDEX_ROWID      - The cursor was opened on a database table.
82200 **   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
82201 **   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
82202 **   IN_INDEX_EPH        - The cursor was opened on a specially created and
82203 **                         populated epheremal table.
82204 **   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
82205 **                         implemented as a sequence of comparisons.
82206 **
82207 ** An existing b-tree might be used if the RHS expression pX is a simple
82208 ** subquery such as:
82209 **
82210 **     SELECT <column> FROM <table>
82211 **
82212 ** If the RHS of the IN operator is a list or a more complex subquery, then
82213 ** an ephemeral table might need to be generated from the RHS and then
82214 ** pX->iTable made to point to the ephemeral table instead of an
82215 ** existing table.
82216 **
82217 ** The inFlags parameter must contain exactly one of the bits
82218 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP.  If inFlags contains
82219 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
82220 ** fast membership test.  When the IN_INDEX_LOOP bit is set, the
82221 ** IN index will be used to loop over all values of the RHS of the
82222 ** IN operator.
82223 **
82224 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
82225 ** through the set members) then the b-tree must not contain duplicates.
82226 ** An epheremal table must be used unless the selected <column> is guaranteed
82227 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
82228 ** has a UNIQUE constraint or UNIQUE index.
82229 **
82230 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
82231 ** for fast set membership tests) then an epheremal table must
82232 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
82233 ** be found with <column> as its left-most column.
82234 **
82235 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
82236 ** if the RHS of the IN operator is a list (not a subquery) then this
82237 ** routine might decide that creating an ephemeral b-tree for membership
82238 ** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
82239 ** calling routine should implement the IN operator using a sequence
82240 ** of Eq or Ne comparison operations.
82241 **
82242 ** When the b-tree is being used for membership tests, the calling function
82243 ** might need to know whether or not the RHS side of the IN operator
82244 ** contains a NULL.  If prRhsHasNull is not a NULL pointer and
82245 ** if there is any chance that the (...) might contain a NULL value at
82246 ** runtime, then a register is allocated and the register number written
82247 ** to *prRhsHasNull. If there is no chance that the (...) contains a
82248 ** NULL value, then *prRhsHasNull is left unchanged.
82249 **
82250 ** If a register is allocated and its location stored in *prRhsHasNull, then
82251 ** the value in that register will be NULL if the b-tree contains one or more
82252 ** NULL values, and it will be some non-NULL value if the b-tree contains no
82253 ** NULL values.
82254 */
82255 #ifndef SQLITE_OMIT_SUBQUERY
82256 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
82257   Select *p;                            /* SELECT to the right of IN operator */
82258   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
82259   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
82260   int mustBeUnique;                     /* True if RHS must be unique */
82261   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
82262 
82263   assert( pX->op==TK_IN );
82264   mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
82265 
82266   /* Check to see if an existing table or index can be used to
82267   ** satisfy the query.  This is preferable to generating a new
82268   ** ephemeral table.
82269   */
82270   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
82271   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
82272     sqlite3 *db = pParse->db;              /* Database connection */
82273     Table *pTab;                           /* Table <table>. */
82274     Expr *pExpr;                           /* Expression <column> */
82275     i16 iCol;                              /* Index of column <column> */
82276     i16 iDb;                               /* Database idx for pTab */
82277 
82278     assert( p );                        /* Because of isCandidateForInOpt(p) */
82279     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
82280     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
82281     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
82282     pTab = p->pSrc->a[0].pTab;
82283     pExpr = p->pEList->a[0].pExpr;
82284     iCol = (i16)pExpr->iColumn;
82285 
82286     /* Code an OP_Transaction and OP_TableLock for <table>. */
82287     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
82288     sqlite3CodeVerifySchema(pParse, iDb);
82289     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
82290 
82291     /* This function is only called from two places. In both cases the vdbe
82292     ** has already been allocated. So assume sqlite3GetVdbe() is always
82293     ** successful here.
82294     */
82295     assert(v);
82296     if( iCol<0 ){
82297       int iAddr = sqlite3CodeOnce(pParse);
82298       VdbeCoverage(v);
82299 
82300       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
82301       eType = IN_INDEX_ROWID;
82302 
82303       sqlite3VdbeJumpHere(v, iAddr);
82304     }else{
82305       Index *pIdx;                         /* Iterator variable */
82306 
82307       /* The collation sequence used by the comparison. If an index is to
82308       ** be used in place of a temp-table, it must be ordered according
82309       ** to this collation sequence.  */
82310       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
82311 
82312       /* Check that the affinity that will be used to perform the
82313       ** comparison is the same as the affinity of the column. If
82314       ** it is not, it is not possible to use any index.
82315       */
82316       int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
82317 
82318       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
82319         if( (pIdx->aiColumn[0]==iCol)
82320          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
82321          && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
82322         ){
82323           int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
82324           sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
82325           sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
82326           VdbeComment((v, "%s", pIdx->zName));
82327           assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
82328           eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
82329 
82330           if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
82331             *prRhsHasNull = ++pParse->nMem;
82332             sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
82333           }
82334           sqlite3VdbeJumpHere(v, iAddr);
82335         }
82336       }
82337     }
82338   }
82339 
82340   /* If no preexisting index is available for the IN clause
82341   ** and IN_INDEX_NOOP is an allowed reply
82342   ** and the RHS of the IN operator is a list, not a subquery
82343   ** and the RHS is not contant or has two or fewer terms,
82344   ** then it is not worth creating an ephemeral table to evaluate
82345   ** the IN operator so return IN_INDEX_NOOP.
82346   */
82347   if( eType==0
82348    && (inFlags & IN_INDEX_NOOP_OK)
82349    && !ExprHasProperty(pX, EP_xIsSelect)
82350    && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
82351   ){
82352     eType = IN_INDEX_NOOP;
82353   }
82354 
82355 
82356   if( eType==0 ){
82357     /* Could not find an existing table or index to use as the RHS b-tree.
82358     ** We will have to generate an ephemeral table to do the job.
82359     */
82360     u32 savedNQueryLoop = pParse->nQueryLoop;
82361     int rMayHaveNull = 0;
82362     eType = IN_INDEX_EPH;
82363     if( inFlags & IN_INDEX_LOOP ){
82364       pParse->nQueryLoop = 0;
82365       if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
82366         eType = IN_INDEX_ROWID;
82367       }
82368     }else if( prRhsHasNull ){
82369       *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
82370     }
82371     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
82372     pParse->nQueryLoop = savedNQueryLoop;
82373   }else{
82374     pX->iTable = iTab;
82375   }
82376   return eType;
82377 }
82378 #endif
82379 
82380 /*
82381 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
82382 ** or IN operators.  Examples:
82383 **
82384 **     (SELECT a FROM b)          -- subquery
82385 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
82386 **     x IN (4,5,11)              -- IN operator with list on right-hand side
82387 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
82388 **
82389 ** The pExpr parameter describes the expression that contains the IN
82390 ** operator or subquery.
82391 **
82392 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
82393 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
82394 ** to some integer key column of a table B-Tree. In this case, use an
82395 ** intkey B-Tree to store the set of IN(...) values instead of the usual
82396 ** (slower) variable length keys B-Tree.
82397 **
82398 ** If rMayHaveNull is non-zero, that means that the operation is an IN
82399 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
82400 ** All this routine does is initialize the register given by rMayHaveNull
82401 ** to NULL.  Calling routines will take care of changing this register
82402 ** value to non-NULL if the RHS is NULL-free.
82403 **
82404 ** For a SELECT or EXISTS operator, return the register that holds the
82405 ** result.  For IN operators or if an error occurs, the return value is 0.
82406 */
82407 #ifndef SQLITE_OMIT_SUBQUERY
82408 SQLITE_PRIVATE int sqlite3CodeSubselect(
82409   Parse *pParse,          /* Parsing context */
82410   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
82411   int rHasNullFlag,       /* Register that records whether NULLs exist in RHS */
82412   int isRowid             /* If true, LHS of IN operator is a rowid */
82413 ){
82414   int jmpIfDynamic = -1;                      /* One-time test address */
82415   int rReg = 0;                           /* Register storing resulting */
82416   Vdbe *v = sqlite3GetVdbe(pParse);
82417   if( NEVER(v==0) ) return 0;
82418   sqlite3ExprCachePush(pParse);
82419 
82420   /* This code must be run in its entirety every time it is encountered
82421   ** if any of the following is true:
82422   **
82423   **    *  The right-hand side is a correlated subquery
82424   **    *  The right-hand side is an expression list containing variables
82425   **    *  We are inside a trigger
82426   **
82427   ** If all of the above are false, then we can run this code just once
82428   ** save the results, and reuse the same result on subsequent invocations.
82429   */
82430   if( !ExprHasProperty(pExpr, EP_VarSelect) ){
82431     jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
82432   }
82433 
82434 #ifndef SQLITE_OMIT_EXPLAIN
82435   if( pParse->explain==2 ){
82436     char *zMsg = sqlite3MPrintf(
82437         pParse->db, "EXECUTE %s%s SUBQUERY %d", jmpIfDynamic>=0?"":"CORRELATED ",
82438         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
82439     );
82440     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
82441   }
82442 #endif
82443 
82444   switch( pExpr->op ){
82445     case TK_IN: {
82446       char affinity;              /* Affinity of the LHS of the IN */
82447       int addr;                   /* Address of OP_OpenEphemeral instruction */
82448       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
82449       KeyInfo *pKeyInfo = 0;      /* Key information */
82450 
82451       affinity = sqlite3ExprAffinity(pLeft);
82452 
82453       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
82454       ** expression it is handled the same way.  An ephemeral table is
82455       ** filled with single-field index keys representing the results
82456       ** from the SELECT or the <exprlist>.
82457       **
82458       ** If the 'x' expression is a column value, or the SELECT...
82459       ** statement returns a column value, then the affinity of that
82460       ** column is used to build the index keys. If both 'x' and the
82461       ** SELECT... statement are columns, then numeric affinity is used
82462       ** if either column has NUMERIC or INTEGER affinity. If neither
82463       ** 'x' nor the SELECT... statement are columns, then numeric affinity
82464       ** is used.
82465       */
82466       pExpr->iTable = pParse->nTab++;
82467       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
82468       pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
82469 
82470       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
82471         /* Case 1:     expr IN (SELECT ...)
82472         **
82473         ** Generate code to write the results of the select into the temporary
82474         ** table allocated and opened above.
82475         */
82476         Select *pSelect = pExpr->x.pSelect;
82477         SelectDest dest;
82478         ExprList *pEList;
82479 
82480         assert( !isRowid );
82481         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
82482         dest.affSdst = (u8)affinity;
82483         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
82484         pSelect->iLimit = 0;
82485         testcase( pSelect->selFlags & SF_Distinct );
82486         testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
82487         if( sqlite3Select(pParse, pSelect, &dest) ){
82488           sqlite3KeyInfoUnref(pKeyInfo);
82489           return 0;
82490         }
82491         pEList = pSelect->pEList;
82492         assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
82493         assert( pEList!=0 );
82494         assert( pEList->nExpr>0 );
82495         assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
82496         pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
82497                                                          pEList->a[0].pExpr);
82498       }else if( ALWAYS(pExpr->x.pList!=0) ){
82499         /* Case 2:     expr IN (exprlist)
82500         **
82501         ** For each expression, build an index key from the evaluation and
82502         ** store it in the temporary table. If <expr> is a column, then use
82503         ** that columns affinity when building index keys. If <expr> is not
82504         ** a column, use numeric affinity.
82505         */
82506         int i;
82507         ExprList *pList = pExpr->x.pList;
82508         struct ExprList_item *pItem;
82509         int r1, r2, r3;
82510 
82511         if( !affinity ){
82512           affinity = SQLITE_AFF_NONE;
82513         }
82514         if( pKeyInfo ){
82515           assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
82516           pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
82517         }
82518 
82519         /* Loop through each expression in <exprlist>. */
82520         r1 = sqlite3GetTempReg(pParse);
82521         r2 = sqlite3GetTempReg(pParse);
82522         if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
82523         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
82524           Expr *pE2 = pItem->pExpr;
82525           int iValToIns;
82526 
82527           /* If the expression is not constant then we will need to
82528           ** disable the test that was generated above that makes sure
82529           ** this code only executes once.  Because for a non-constant
82530           ** expression we need to rerun this code each time.
82531           */
82532           if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
82533             sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
82534             jmpIfDynamic = -1;
82535           }
82536 
82537           /* Evaluate the expression and insert it into the temp table */
82538           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
82539             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
82540           }else{
82541             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
82542             if( isRowid ){
82543               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
82544                                 sqlite3VdbeCurrentAddr(v)+2);
82545               VdbeCoverage(v);
82546               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
82547             }else{
82548               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
82549               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
82550               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
82551             }
82552           }
82553         }
82554         sqlite3ReleaseTempReg(pParse, r1);
82555         sqlite3ReleaseTempReg(pParse, r2);
82556       }
82557       if( pKeyInfo ){
82558         sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
82559       }
82560       break;
82561     }
82562 
82563     case TK_EXISTS:
82564     case TK_SELECT:
82565     default: {
82566       /* If this has to be a scalar SELECT.  Generate code to put the
82567       ** value of this select in a memory cell and record the number
82568       ** of the memory cell in iColumn.  If this is an EXISTS, write
82569       ** an integer 0 (not exists) or 1 (exists) into a memory cell
82570       ** and record that memory cell in iColumn.
82571       */
82572       Select *pSel;                         /* SELECT statement to encode */
82573       SelectDest dest;                      /* How to deal with SELECt result */
82574 
82575       testcase( pExpr->op==TK_EXISTS );
82576       testcase( pExpr->op==TK_SELECT );
82577       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
82578 
82579       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
82580       pSel = pExpr->x.pSelect;
82581       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
82582       if( pExpr->op==TK_SELECT ){
82583         dest.eDest = SRT_Mem;
82584         dest.iSdst = dest.iSDParm;
82585         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
82586         VdbeComment((v, "Init subquery result"));
82587       }else{
82588         dest.eDest = SRT_Exists;
82589         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
82590         VdbeComment((v, "Init EXISTS result"));
82591       }
82592       sqlite3ExprDelete(pParse->db, pSel->pLimit);
82593       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
82594                                   &sqlite3IntTokens[1]);
82595       pSel->iLimit = 0;
82596       if( sqlite3Select(pParse, pSel, &dest) ){
82597         return 0;
82598       }
82599       rReg = dest.iSDParm;
82600       ExprSetVVAProperty(pExpr, EP_NoReduce);
82601       break;
82602     }
82603   }
82604 
82605   if( rHasNullFlag ){
82606     sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
82607   }
82608 
82609   if( jmpIfDynamic>=0 ){
82610     sqlite3VdbeJumpHere(v, jmpIfDynamic);
82611   }
82612   sqlite3ExprCachePop(pParse);
82613 
82614   return rReg;
82615 }
82616 #endif /* SQLITE_OMIT_SUBQUERY */
82617 
82618 #ifndef SQLITE_OMIT_SUBQUERY
82619 /*
82620 ** Generate code for an IN expression.
82621 **
82622 **      x IN (SELECT ...)
82623 **      x IN (value, value, ...)
82624 **
82625 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
82626 ** is an array of zero or more values.  The expression is true if the LHS is
82627 ** contained within the RHS.  The value of the expression is unknown (NULL)
82628 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
82629 ** RHS contains one or more NULL values.
82630 **
82631 ** This routine generates code that jumps to destIfFalse if the LHS is not
82632 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
82633 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
82634 ** within the RHS then fall through.
82635 */
82636 static void sqlite3ExprCodeIN(
82637   Parse *pParse,        /* Parsing and code generating context */
82638   Expr *pExpr,          /* The IN expression */
82639   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
82640   int destIfNull        /* Jump here if the results are unknown due to NULLs */
82641 ){
82642   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
82643   char affinity;        /* Comparison affinity to use */
82644   int eType;            /* Type of the RHS */
82645   int r1;               /* Temporary use register */
82646   Vdbe *v;              /* Statement under construction */
82647 
82648   /* Compute the RHS.   After this step, the table with cursor
82649   ** pExpr->iTable will contains the values that make up the RHS.
82650   */
82651   v = pParse->pVdbe;
82652   assert( v!=0 );       /* OOM detected prior to this routine */
82653   VdbeNoopComment((v, "begin IN expr"));
82654   eType = sqlite3FindInIndex(pParse, pExpr,
82655                              IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
82656                              destIfFalse==destIfNull ? 0 : &rRhsHasNull);
82657 
82658   /* Figure out the affinity to use to create a key from the results
82659   ** of the expression. affinityStr stores a static string suitable for
82660   ** P4 of OP_MakeRecord.
82661   */
82662   affinity = comparisonAffinity(pExpr);
82663 
82664   /* Code the LHS, the <expr> from "<expr> IN (...)".
82665   */
82666   sqlite3ExprCachePush(pParse);
82667   r1 = sqlite3GetTempReg(pParse);
82668   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
82669 
82670   /* If sqlite3FindInIndex() did not find or create an index that is
82671   ** suitable for evaluating the IN operator, then evaluate using a
82672   ** sequence of comparisons.
82673   */
82674   if( eType==IN_INDEX_NOOP ){
82675     ExprList *pList = pExpr->x.pList;
82676     CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
82677     int labelOk = sqlite3VdbeMakeLabel(v);
82678     int r2, regToFree;
82679     int regCkNull = 0;
82680     int ii;
82681     assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
82682     if( destIfNull!=destIfFalse ){
82683       regCkNull = sqlite3GetTempReg(pParse);
82684       sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
82685     }
82686     for(ii=0; ii<pList->nExpr; ii++){
82687       r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
82688       if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
82689         sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
82690       }
82691       if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
82692         sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
82693                           (void*)pColl, P4_COLLSEQ);
82694         VdbeCoverageIf(v, ii<pList->nExpr-1);
82695         VdbeCoverageIf(v, ii==pList->nExpr-1);
82696         sqlite3VdbeChangeP5(v, affinity);
82697       }else{
82698         assert( destIfNull==destIfFalse );
82699         sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
82700                           (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
82701         sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
82702       }
82703       sqlite3ReleaseTempReg(pParse, regToFree);
82704     }
82705     if( regCkNull ){
82706       sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
82707       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
82708     }
82709     sqlite3VdbeResolveLabel(v, labelOk);
82710     sqlite3ReleaseTempReg(pParse, regCkNull);
82711   }else{
82712 
82713     /* If the LHS is NULL, then the result is either false or NULL depending
82714     ** on whether the RHS is empty or not, respectively.
82715     */
82716     if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
82717       if( destIfNull==destIfFalse ){
82718         /* Shortcut for the common case where the false and NULL outcomes are
82719         ** the same. */
82720         sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
82721       }else{
82722         int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
82723         sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
82724         VdbeCoverage(v);
82725         sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
82726         sqlite3VdbeJumpHere(v, addr1);
82727       }
82728     }
82729 
82730     if( eType==IN_INDEX_ROWID ){
82731       /* In this case, the RHS is the ROWID of table b-tree
82732       */
82733       sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); VdbeCoverage(v);
82734       sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
82735       VdbeCoverage(v);
82736     }else{
82737       /* In this case, the RHS is an index b-tree.
82738       */
82739       sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
82740 
82741       /* If the set membership test fails, then the result of the
82742       ** "x IN (...)" expression must be either 0 or NULL. If the set
82743       ** contains no NULL values, then the result is 0. If the set
82744       ** contains one or more NULL values, then the result of the
82745       ** expression is also NULL.
82746       */
82747       assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
82748       if( rRhsHasNull==0 ){
82749         /* This branch runs if it is known at compile time that the RHS
82750         ** cannot contain NULL values. This happens as the result
82751         ** of a "NOT NULL" constraint in the database schema.
82752         **
82753         ** Also run this branch if NULL is equivalent to FALSE
82754         ** for this particular IN operator.
82755         */
82756         sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
82757         VdbeCoverage(v);
82758       }else{
82759         /* In this branch, the RHS of the IN might contain a NULL and
82760         ** the presence of a NULL on the RHS makes a difference in the
82761         ** outcome.
82762         */
82763         int j1;
82764 
82765         /* First check to see if the LHS is contained in the RHS.  If so,
82766         ** then the answer is TRUE the presence of NULLs in the RHS does
82767         ** not matter.  If the LHS is not contained in the RHS, then the
82768         ** answer is NULL if the RHS contains NULLs and the answer is
82769         ** FALSE if the RHS is NULL-free.
82770         */
82771         j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
82772         VdbeCoverage(v);
82773         sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
82774         VdbeCoverage(v);
82775         sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
82776         sqlite3VdbeJumpHere(v, j1);
82777       }
82778     }
82779   }
82780   sqlite3ReleaseTempReg(pParse, r1);
82781   sqlite3ExprCachePop(pParse);
82782   VdbeComment((v, "end IN expr"));
82783 }
82784 #endif /* SQLITE_OMIT_SUBQUERY */
82785 
82786 /*
82787 ** Duplicate an 8-byte value
82788 */
82789 static char *dup8bytes(Vdbe *v, const char *in){
82790   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
82791   if( out ){
82792     memcpy(out, in, 8);
82793   }
82794   return out;
82795 }
82796 
82797 #ifndef SQLITE_OMIT_FLOATING_POINT
82798 /*
82799 ** Generate an instruction that will put the floating point
82800 ** value described by z[0..n-1] into register iMem.
82801 **
82802 ** The z[] string will probably not be zero-terminated.  But the
82803 ** z[n] character is guaranteed to be something that does not look
82804 ** like the continuation of the number.
82805 */
82806 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
82807   if( ALWAYS(z!=0) ){
82808     double value;
82809     char *zV;
82810     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
82811     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
82812     if( negateFlag ) value = -value;
82813     zV = dup8bytes(v, (char*)&value);
82814     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
82815   }
82816 }
82817 #endif
82818 
82819 
82820 /*
82821 ** Generate an instruction that will put the integer describe by
82822 ** text z[0..n-1] into register iMem.
82823 **
82824 ** Expr.u.zToken is always UTF8 and zero-terminated.
82825 */
82826 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
82827   Vdbe *v = pParse->pVdbe;
82828   if( pExpr->flags & EP_IntValue ){
82829     int i = pExpr->u.iValue;
82830     assert( i>=0 );
82831     if( negFlag ) i = -i;
82832     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
82833   }else{
82834     int c;
82835     i64 value;
82836     const char *z = pExpr->u.zToken;
82837     assert( z!=0 );
82838     c = sqlite3DecOrHexToI64(z, &value);
82839     if( c==0 || (c==2 && negFlag) ){
82840       char *zV;
82841       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
82842       zV = dup8bytes(v, (char*)&value);
82843       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
82844     }else{
82845 #ifdef SQLITE_OMIT_FLOATING_POINT
82846       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
82847 #else
82848 #ifndef SQLITE_OMIT_HEX_INTEGER
82849       if( sqlite3_strnicmp(z,"0x",2)==0 ){
82850         sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
82851       }else
82852 #endif
82853       {
82854         codeReal(v, z, negFlag, iMem);
82855       }
82856 #endif
82857     }
82858   }
82859 }
82860 
82861 /*
82862 ** Clear a cache entry.
82863 */
82864 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
82865   if( p->tempReg ){
82866     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
82867       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
82868     }
82869     p->tempReg = 0;
82870   }
82871 }
82872 
82873 
82874 /*
82875 ** Record in the column cache that a particular column from a
82876 ** particular table is stored in a particular register.
82877 */
82878 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
82879   int i;
82880   int minLru;
82881   int idxLru;
82882   struct yColCache *p;
82883 
82884   assert( iReg>0 );  /* Register numbers are always positive */
82885   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
82886 
82887   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
82888   ** for testing only - to verify that SQLite always gets the same answer
82889   ** with and without the column cache.
82890   */
82891   if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
82892 
82893   /* First replace any existing entry.
82894   **
82895   ** Actually, the way the column cache is currently used, we are guaranteed
82896   ** that the object will never already be in cache.  Verify this guarantee.
82897   */
82898 #ifndef NDEBUG
82899   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
82900     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
82901   }
82902 #endif
82903 
82904   /* Find an empty slot and replace it */
82905   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
82906     if( p->iReg==0 ){
82907       p->iLevel = pParse->iCacheLevel;
82908       p->iTable = iTab;
82909       p->iColumn = iCol;
82910       p->iReg = iReg;
82911       p->tempReg = 0;
82912       p->lru = pParse->iCacheCnt++;
82913       return;
82914     }
82915   }
82916 
82917   /* Replace the last recently used */
82918   minLru = 0x7fffffff;
82919   idxLru = -1;
82920   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
82921     if( p->lru<minLru ){
82922       idxLru = i;
82923       minLru = p->lru;
82924     }
82925   }
82926   if( ALWAYS(idxLru>=0) ){
82927     p = &pParse->aColCache[idxLru];
82928     p->iLevel = pParse->iCacheLevel;
82929     p->iTable = iTab;
82930     p->iColumn = iCol;
82931     p->iReg = iReg;
82932     p->tempReg = 0;
82933     p->lru = pParse->iCacheCnt++;
82934     return;
82935   }
82936 }
82937 
82938 /*
82939 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
82940 ** Purge the range of registers from the column cache.
82941 */
82942 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
82943   int i;
82944   int iLast = iReg + nReg - 1;
82945   struct yColCache *p;
82946   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
82947     int r = p->iReg;
82948     if( r>=iReg && r<=iLast ){
82949       cacheEntryClear(pParse, p);
82950       p->iReg = 0;
82951     }
82952   }
82953 }
82954 
82955 /*
82956 ** Remember the current column cache context.  Any new entries added
82957 ** added to the column cache after this call are removed when the
82958 ** corresponding pop occurs.
82959 */
82960 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
82961   pParse->iCacheLevel++;
82962 #ifdef SQLITE_DEBUG
82963   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
82964     printf("PUSH to %d\n", pParse->iCacheLevel);
82965   }
82966 #endif
82967 }
82968 
82969 /*
82970 ** Remove from the column cache any entries that were added since the
82971 ** the previous sqlite3ExprCachePush operation.  In other words, restore
82972 ** the cache to the state it was in prior the most recent Push.
82973 */
82974 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
82975   int i;
82976   struct yColCache *p;
82977   assert( pParse->iCacheLevel>=1 );
82978   pParse->iCacheLevel--;
82979 #ifdef SQLITE_DEBUG
82980   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
82981     printf("POP  to %d\n", pParse->iCacheLevel);
82982   }
82983 #endif
82984   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
82985     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
82986       cacheEntryClear(pParse, p);
82987       p->iReg = 0;
82988     }
82989   }
82990 }
82991 
82992 /*
82993 ** When a cached column is reused, make sure that its register is
82994 ** no longer available as a temp register.  ticket #3879:  that same
82995 ** register might be in the cache in multiple places, so be sure to
82996 ** get them all.
82997 */
82998 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
82999   int i;
83000   struct yColCache *p;
83001   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
83002     if( p->iReg==iReg ){
83003       p->tempReg = 0;
83004     }
83005   }
83006 }
83007 
83008 /*
83009 ** Generate code to extract the value of the iCol-th column of a table.
83010 */
83011 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
83012   Vdbe *v,        /* The VDBE under construction */
83013   Table *pTab,    /* The table containing the value */
83014   int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
83015   int iCol,       /* Index of the column to extract */
83016   int regOut      /* Extract the value into this register */
83017 ){
83018   if( iCol<0 || iCol==pTab->iPKey ){
83019     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
83020   }else{
83021     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
83022     int x = iCol;
83023     if( !HasRowid(pTab) ){
83024       x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
83025     }
83026     sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
83027   }
83028   if( iCol>=0 ){
83029     sqlite3ColumnDefault(v, pTab, iCol, regOut);
83030   }
83031 }
83032 
83033 /*
83034 ** Generate code that will extract the iColumn-th column from
83035 ** table pTab and store the column value in a register.  An effort
83036 ** is made to store the column value in register iReg, but this is
83037 ** not guaranteed.  The location of the column value is returned.
83038 **
83039 ** There must be an open cursor to pTab in iTable when this routine
83040 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
83041 */
83042 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
83043   Parse *pParse,   /* Parsing and code generating context */
83044   Table *pTab,     /* Description of the table we are reading from */
83045   int iColumn,     /* Index of the table column */
83046   int iTable,      /* The cursor pointing to the table */
83047   int iReg,        /* Store results here */
83048   u8 p5            /* P5 value for OP_Column */
83049 ){
83050   Vdbe *v = pParse->pVdbe;
83051   int i;
83052   struct yColCache *p;
83053 
83054   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
83055     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
83056       p->lru = pParse->iCacheCnt++;
83057       sqlite3ExprCachePinRegister(pParse, p->iReg);
83058       return p->iReg;
83059     }
83060   }
83061   assert( v!=0 );
83062   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
83063   if( p5 ){
83064     sqlite3VdbeChangeP5(v, p5);
83065   }else{
83066     sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
83067   }
83068   return iReg;
83069 }
83070 
83071 /*
83072 ** Clear all column cache entries.
83073 */
83074 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
83075   int i;
83076   struct yColCache *p;
83077 
83078 #if SQLITE_DEBUG
83079   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
83080     printf("CLEAR\n");
83081   }
83082 #endif
83083   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
83084     if( p->iReg ){
83085       cacheEntryClear(pParse, p);
83086       p->iReg = 0;
83087     }
83088   }
83089 }
83090 
83091 /*
83092 ** Record the fact that an affinity change has occurred on iCount
83093 ** registers starting with iStart.
83094 */
83095 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
83096   sqlite3ExprCacheRemove(pParse, iStart, iCount);
83097 }
83098 
83099 /*
83100 ** Generate code to move content from registers iFrom...iFrom+nReg-1
83101 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
83102 */
83103 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
83104   assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
83105   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
83106   sqlite3ExprCacheRemove(pParse, iFrom, nReg);
83107 }
83108 
83109 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
83110 /*
83111 ** Return true if any register in the range iFrom..iTo (inclusive)
83112 ** is used as part of the column cache.
83113 **
83114 ** This routine is used within assert() and testcase() macros only
83115 ** and does not appear in a normal build.
83116 */
83117 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
83118   int i;
83119   struct yColCache *p;
83120   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
83121     int r = p->iReg;
83122     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
83123   }
83124   return 0;
83125 }
83126 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
83127 
83128 /*
83129 ** Convert an expression node to a TK_REGISTER
83130 */
83131 static void exprToRegister(Expr *p, int iReg){
83132   p->op2 = p->op;
83133   p->op = TK_REGISTER;
83134   p->iTable = iReg;
83135   ExprClearProperty(p, EP_Skip);
83136 }
83137 
83138 /*
83139 ** Generate code into the current Vdbe to evaluate the given
83140 ** expression.  Attempt to store the results in register "target".
83141 ** Return the register where results are stored.
83142 **
83143 ** With this routine, there is no guarantee that results will
83144 ** be stored in target.  The result might be stored in some other
83145 ** register if it is convenient to do so.  The calling function
83146 ** must check the return code and move the results to the desired
83147 ** register.
83148 */
83149 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
83150   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
83151   int op;                   /* The opcode being coded */
83152   int inReg = target;       /* Results stored in register inReg */
83153   int regFree1 = 0;         /* If non-zero free this temporary register */
83154   int regFree2 = 0;         /* If non-zero free this temporary register */
83155   int r1, r2, r3, r4;       /* Various register numbers */
83156   sqlite3 *db = pParse->db; /* The database connection */
83157   Expr tempX;               /* Temporary expression node */
83158 
83159   assert( target>0 && target<=pParse->nMem );
83160   if( v==0 ){
83161     assert( pParse->db->mallocFailed );
83162     return 0;
83163   }
83164 
83165   if( pExpr==0 ){
83166     op = TK_NULL;
83167   }else{
83168     op = pExpr->op;
83169   }
83170   switch( op ){
83171     case TK_AGG_COLUMN: {
83172       AggInfo *pAggInfo = pExpr->pAggInfo;
83173       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
83174       if( !pAggInfo->directMode ){
83175         assert( pCol->iMem>0 );
83176         inReg = pCol->iMem;
83177         break;
83178       }else if( pAggInfo->useSortingIdx ){
83179         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
83180                               pCol->iSorterColumn, target);
83181         break;
83182       }
83183       /* Otherwise, fall thru into the TK_COLUMN case */
83184     }
83185     case TK_COLUMN: {
83186       int iTab = pExpr->iTable;
83187       if( iTab<0 ){
83188         if( pParse->ckBase>0 ){
83189           /* Generating CHECK constraints or inserting into partial index */
83190           inReg = pExpr->iColumn + pParse->ckBase;
83191           break;
83192         }else{
83193           /* Deleting from a partial index */
83194           iTab = pParse->iPartIdxTab;
83195         }
83196       }
83197       inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
83198                                pExpr->iColumn, iTab, target,
83199                                pExpr->op2);
83200       break;
83201     }
83202     case TK_INTEGER: {
83203       codeInteger(pParse, pExpr, 0, target);
83204       break;
83205     }
83206 #ifndef SQLITE_OMIT_FLOATING_POINT
83207     case TK_FLOAT: {
83208       assert( !ExprHasProperty(pExpr, EP_IntValue) );
83209       codeReal(v, pExpr->u.zToken, 0, target);
83210       break;
83211     }
83212 #endif
83213     case TK_STRING: {
83214       assert( !ExprHasProperty(pExpr, EP_IntValue) );
83215       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
83216       break;
83217     }
83218     case TK_NULL: {
83219       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
83220       break;
83221     }
83222 #ifndef SQLITE_OMIT_BLOB_LITERAL
83223     case TK_BLOB: {
83224       int n;
83225       const char *z;
83226       char *zBlob;
83227       assert( !ExprHasProperty(pExpr, EP_IntValue) );
83228       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
83229       assert( pExpr->u.zToken[1]=='\'' );
83230       z = &pExpr->u.zToken[2];
83231       n = sqlite3Strlen30(z) - 1;
83232       assert( z[n]=='\'' );
83233       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
83234       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
83235       break;
83236     }
83237 #endif
83238     case TK_VARIABLE: {
83239       assert( !ExprHasProperty(pExpr, EP_IntValue) );
83240       assert( pExpr->u.zToken!=0 );
83241       assert( pExpr->u.zToken[0]!=0 );
83242       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
83243       if( pExpr->u.zToken[1]!=0 ){
83244         assert( pExpr->u.zToken[0]=='?'
83245              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
83246         sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
83247       }
83248       break;
83249     }
83250     case TK_REGISTER: {
83251       inReg = pExpr->iTable;
83252       break;
83253     }
83254     case TK_AS: {
83255       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
83256       break;
83257     }
83258 #ifndef SQLITE_OMIT_CAST
83259     case TK_CAST: {
83260       /* Expressions of the form:   CAST(pLeft AS token) */
83261       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
83262       if( inReg!=target ){
83263         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
83264         inReg = target;
83265       }
83266       sqlite3VdbeAddOp2(v, OP_Cast, target,
83267                         sqlite3AffinityType(pExpr->u.zToken, 0));
83268       testcase( usedAsColumnCache(pParse, inReg, inReg) );
83269       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
83270       break;
83271     }
83272 #endif /* SQLITE_OMIT_CAST */
83273     case TK_LT:
83274     case TK_LE:
83275     case TK_GT:
83276     case TK_GE:
83277     case TK_NE:
83278     case TK_EQ: {
83279       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
83280       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
83281       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
83282                   r1, r2, inReg, SQLITE_STOREP2);
83283       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
83284       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
83285       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
83286       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
83287       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
83288       assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
83289       testcase( regFree1==0 );
83290       testcase( regFree2==0 );
83291       break;
83292     }
83293     case TK_IS:
83294     case TK_ISNOT: {
83295       testcase( op==TK_IS );
83296       testcase( op==TK_ISNOT );
83297       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
83298       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
83299       op = (op==TK_IS) ? TK_EQ : TK_NE;
83300       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
83301                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
83302       VdbeCoverageIf(v, op==TK_EQ);
83303       VdbeCoverageIf(v, op==TK_NE);
83304       testcase( regFree1==0 );
83305       testcase( regFree2==0 );
83306       break;
83307     }
83308     case TK_AND:
83309     case TK_OR:
83310     case TK_PLUS:
83311     case TK_STAR:
83312     case TK_MINUS:
83313     case TK_REM:
83314     case TK_BITAND:
83315     case TK_BITOR:
83316     case TK_SLASH:
83317     case TK_LSHIFT:
83318     case TK_RSHIFT:
83319     case TK_CONCAT: {
83320       assert( TK_AND==OP_And );            testcase( op==TK_AND );
83321       assert( TK_OR==OP_Or );              testcase( op==TK_OR );
83322       assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
83323       assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
83324       assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
83325       assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
83326       assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
83327       assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
83328       assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
83329       assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
83330       assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
83331       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
83332       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
83333       sqlite3VdbeAddOp3(v, op, r2, r1, target);
83334       testcase( regFree1==0 );
83335       testcase( regFree2==0 );
83336       break;
83337     }
83338     case TK_UMINUS: {
83339       Expr *pLeft = pExpr->pLeft;
83340       assert( pLeft );
83341       if( pLeft->op==TK_INTEGER ){
83342         codeInteger(pParse, pLeft, 1, target);
83343 #ifndef SQLITE_OMIT_FLOATING_POINT
83344       }else if( pLeft->op==TK_FLOAT ){
83345         assert( !ExprHasProperty(pExpr, EP_IntValue) );
83346         codeReal(v, pLeft->u.zToken, 1, target);
83347 #endif
83348       }else{
83349         tempX.op = TK_INTEGER;
83350         tempX.flags = EP_IntValue|EP_TokenOnly;
83351         tempX.u.iValue = 0;
83352         r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
83353         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
83354         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
83355         testcase( regFree2==0 );
83356       }
83357       inReg = target;
83358       break;
83359     }
83360     case TK_BITNOT:
83361     case TK_NOT: {
83362       assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
83363       assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
83364       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
83365       testcase( regFree1==0 );
83366       inReg = target;
83367       sqlite3VdbeAddOp2(v, op, r1, inReg);
83368       break;
83369     }
83370     case TK_ISNULL:
83371     case TK_NOTNULL: {
83372       int addr;
83373       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
83374       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
83375       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
83376       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
83377       testcase( regFree1==0 );
83378       addr = sqlite3VdbeAddOp1(v, op, r1);
83379       VdbeCoverageIf(v, op==TK_ISNULL);
83380       VdbeCoverageIf(v, op==TK_NOTNULL);
83381       sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
83382       sqlite3VdbeJumpHere(v, addr);
83383       break;
83384     }
83385     case TK_AGG_FUNCTION: {
83386       AggInfo *pInfo = pExpr->pAggInfo;
83387       if( pInfo==0 ){
83388         assert( !ExprHasProperty(pExpr, EP_IntValue) );
83389         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
83390       }else{
83391         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
83392       }
83393       break;
83394     }
83395     case TK_FUNCTION: {
83396       ExprList *pFarg;       /* List of function arguments */
83397       int nFarg;             /* Number of function arguments */
83398       FuncDef *pDef;         /* The function definition object */
83399       int nId;               /* Length of the function name in bytes */
83400       const char *zId;       /* The function name */
83401       u32 constMask = 0;     /* Mask of function arguments that are constant */
83402       int i;                 /* Loop counter */
83403       u8 enc = ENC(db);      /* The text encoding used by this database */
83404       CollSeq *pColl = 0;    /* A collating sequence */
83405 
83406       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
83407       if( ExprHasProperty(pExpr, EP_TokenOnly) ){
83408         pFarg = 0;
83409       }else{
83410         pFarg = pExpr->x.pList;
83411       }
83412       nFarg = pFarg ? pFarg->nExpr : 0;
83413       assert( !ExprHasProperty(pExpr, EP_IntValue) );
83414       zId = pExpr->u.zToken;
83415       nId = sqlite3Strlen30(zId);
83416       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
83417       if( pDef==0 || pDef->xFunc==0 ){
83418         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
83419         break;
83420       }
83421 
83422       /* Attempt a direct implementation of the built-in COALESCE() and
83423       ** IFNULL() functions.  This avoids unnecessary evaluation of
83424       ** arguments past the first non-NULL argument.
83425       */
83426       if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
83427         int endCoalesce = sqlite3VdbeMakeLabel(v);
83428         assert( nFarg>=2 );
83429         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
83430         for(i=1; i<nFarg; i++){
83431           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
83432           VdbeCoverage(v);
83433           sqlite3ExprCacheRemove(pParse, target, 1);
83434           sqlite3ExprCachePush(pParse);
83435           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
83436           sqlite3ExprCachePop(pParse);
83437         }
83438         sqlite3VdbeResolveLabel(v, endCoalesce);
83439         break;
83440       }
83441 
83442       /* The UNLIKELY() function is a no-op.  The result is the value
83443       ** of the first argument.
83444       */
83445       if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
83446         assert( nFarg>=1 );
83447         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
83448         break;
83449       }
83450 
83451       for(i=0; i<nFarg; i++){
83452         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
83453           testcase( i==31 );
83454           constMask |= MASKBIT32(i);
83455         }
83456         if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
83457           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
83458         }
83459       }
83460       if( pFarg ){
83461         if( constMask ){
83462           r1 = pParse->nMem+1;
83463           pParse->nMem += nFarg;
83464         }else{
83465           r1 = sqlite3GetTempRange(pParse, nFarg);
83466         }
83467 
83468         /* For length() and typeof() functions with a column argument,
83469         ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
83470         ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
83471         ** loading.
83472         */
83473         if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
83474           u8 exprOp;
83475           assert( nFarg==1 );
83476           assert( pFarg->a[0].pExpr!=0 );
83477           exprOp = pFarg->a[0].pExpr->op;
83478           if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
83479             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
83480             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
83481             testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
83482             pFarg->a[0].pExpr->op2 =
83483                   pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
83484           }
83485         }
83486 
83487         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
83488         sqlite3ExprCodeExprList(pParse, pFarg, r1,
83489                                 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
83490         sqlite3ExprCachePop(pParse);      /* Ticket 2ea2425d34be */
83491       }else{
83492         r1 = 0;
83493       }
83494 #ifndef SQLITE_OMIT_VIRTUALTABLE
83495       /* Possibly overload the function if the first argument is
83496       ** a virtual table column.
83497       **
83498       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
83499       ** second argument, not the first, as the argument to test to
83500       ** see if it is a column in a virtual table.  This is done because
83501       ** the left operand of infix functions (the operand we want to
83502       ** control overloading) ends up as the second argument to the
83503       ** function.  The expression "A glob B" is equivalent to
83504       ** "glob(B,A).  We want to use the A in "A glob B" to test
83505       ** for function overloading.  But we use the B term in "glob(B,A)".
83506       */
83507       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
83508         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
83509       }else if( nFarg>0 ){
83510         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
83511       }
83512 #endif
83513       if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
83514         if( !pColl ) pColl = db->pDfltColl;
83515         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
83516       }
83517       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
83518                         (char*)pDef, P4_FUNCDEF);
83519       sqlite3VdbeChangeP5(v, (u8)nFarg);
83520       if( nFarg && constMask==0 ){
83521         sqlite3ReleaseTempRange(pParse, r1, nFarg);
83522       }
83523       break;
83524     }
83525 #ifndef SQLITE_OMIT_SUBQUERY
83526     case TK_EXISTS:
83527     case TK_SELECT: {
83528       testcase( op==TK_EXISTS );
83529       testcase( op==TK_SELECT );
83530       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
83531       break;
83532     }
83533     case TK_IN: {
83534       int destIfFalse = sqlite3VdbeMakeLabel(v);
83535       int destIfNull = sqlite3VdbeMakeLabel(v);
83536       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
83537       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
83538       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
83539       sqlite3VdbeResolveLabel(v, destIfFalse);
83540       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
83541       sqlite3VdbeResolveLabel(v, destIfNull);
83542       break;
83543     }
83544 #endif /* SQLITE_OMIT_SUBQUERY */
83545 
83546 
83547     /*
83548     **    x BETWEEN y AND z
83549     **
83550     ** This is equivalent to
83551     **
83552     **    x>=y AND x<=z
83553     **
83554     ** X is stored in pExpr->pLeft.
83555     ** Y is stored in pExpr->pList->a[0].pExpr.
83556     ** Z is stored in pExpr->pList->a[1].pExpr.
83557     */
83558     case TK_BETWEEN: {
83559       Expr *pLeft = pExpr->pLeft;
83560       struct ExprList_item *pLItem = pExpr->x.pList->a;
83561       Expr *pRight = pLItem->pExpr;
83562 
83563       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
83564       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
83565       testcase( regFree1==0 );
83566       testcase( regFree2==0 );
83567       r3 = sqlite3GetTempReg(pParse);
83568       r4 = sqlite3GetTempReg(pParse);
83569       codeCompare(pParse, pLeft, pRight, OP_Ge,
83570                   r1, r2, r3, SQLITE_STOREP2);  VdbeCoverage(v);
83571       pLItem++;
83572       pRight = pLItem->pExpr;
83573       sqlite3ReleaseTempReg(pParse, regFree2);
83574       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
83575       testcase( regFree2==0 );
83576       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
83577       VdbeCoverage(v);
83578       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
83579       sqlite3ReleaseTempReg(pParse, r3);
83580       sqlite3ReleaseTempReg(pParse, r4);
83581       break;
83582     }
83583     case TK_COLLATE:
83584     case TK_UPLUS: {
83585       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
83586       break;
83587     }
83588 
83589     case TK_TRIGGER: {
83590       /* If the opcode is TK_TRIGGER, then the expression is a reference
83591       ** to a column in the new.* or old.* pseudo-tables available to
83592       ** trigger programs. In this case Expr.iTable is set to 1 for the
83593       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
83594       ** is set to the column of the pseudo-table to read, or to -1 to
83595       ** read the rowid field.
83596       **
83597       ** The expression is implemented using an OP_Param opcode. The p1
83598       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
83599       ** to reference another column of the old.* pseudo-table, where
83600       ** i is the index of the column. For a new.rowid reference, p1 is
83601       ** set to (n+1), where n is the number of columns in each pseudo-table.
83602       ** For a reference to any other column in the new.* pseudo-table, p1
83603       ** is set to (n+2+i), where n and i are as defined previously. For
83604       ** example, if the table on which triggers are being fired is
83605       ** declared as:
83606       **
83607       **   CREATE TABLE t1(a, b);
83608       **
83609       ** Then p1 is interpreted as follows:
83610       **
83611       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
83612       **   p1==1   ->    old.a         p1==4   ->    new.a
83613       **   p1==2   ->    old.b         p1==5   ->    new.b
83614       */
83615       Table *pTab = pExpr->pTab;
83616       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
83617 
83618       assert( pExpr->iTable==0 || pExpr->iTable==1 );
83619       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
83620       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
83621       assert( p1>=0 && p1<(pTab->nCol*2+2) );
83622 
83623       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
83624       VdbeComment((v, "%s.%s -> $%d",
83625         (pExpr->iTable ? "new" : "old"),
83626         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
83627         target
83628       ));
83629 
83630 #ifndef SQLITE_OMIT_FLOATING_POINT
83631       /* If the column has REAL affinity, it may currently be stored as an
83632       ** integer. Use OP_RealAffinity to make sure it is really real.  */
83633       if( pExpr->iColumn>=0
83634        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
83635       ){
83636         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
83637       }
83638 #endif
83639       break;
83640     }
83641 
83642 
83643     /*
83644     ** Form A:
83645     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
83646     **
83647     ** Form B:
83648     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
83649     **
83650     ** Form A is can be transformed into the equivalent form B as follows:
83651     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
83652     **        WHEN x=eN THEN rN ELSE y END
83653     **
83654     ** X (if it exists) is in pExpr->pLeft.
83655     ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
83656     ** odd.  The Y is also optional.  If the number of elements in x.pList
83657     ** is even, then Y is omitted and the "otherwise" result is NULL.
83658     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
83659     **
83660     ** The result of the expression is the Ri for the first matching Ei,
83661     ** or if there is no matching Ei, the ELSE term Y, or if there is
83662     ** no ELSE term, NULL.
83663     */
83664     default: assert( op==TK_CASE ); {
83665       int endLabel;                     /* GOTO label for end of CASE stmt */
83666       int nextCase;                     /* GOTO label for next WHEN clause */
83667       int nExpr;                        /* 2x number of WHEN terms */
83668       int i;                            /* Loop counter */
83669       ExprList *pEList;                 /* List of WHEN terms */
83670       struct ExprList_item *aListelem;  /* Array of WHEN terms */
83671       Expr opCompare;                   /* The X==Ei expression */
83672       Expr *pX;                         /* The X expression */
83673       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
83674       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
83675 
83676       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
83677       assert(pExpr->x.pList->nExpr > 0);
83678       pEList = pExpr->x.pList;
83679       aListelem = pEList->a;
83680       nExpr = pEList->nExpr;
83681       endLabel = sqlite3VdbeMakeLabel(v);
83682       if( (pX = pExpr->pLeft)!=0 ){
83683         tempX = *pX;
83684         testcase( pX->op==TK_COLUMN );
83685         exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
83686         testcase( regFree1==0 );
83687         opCompare.op = TK_EQ;
83688         opCompare.pLeft = &tempX;
83689         pTest = &opCompare;
83690         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
83691         ** The value in regFree1 might get SCopy-ed into the file result.
83692         ** So make sure that the regFree1 register is not reused for other
83693         ** purposes and possibly overwritten.  */
83694         regFree1 = 0;
83695       }
83696       for(i=0; i<nExpr-1; i=i+2){
83697         sqlite3ExprCachePush(pParse);
83698         if( pX ){
83699           assert( pTest!=0 );
83700           opCompare.pRight = aListelem[i].pExpr;
83701         }else{
83702           pTest = aListelem[i].pExpr;
83703         }
83704         nextCase = sqlite3VdbeMakeLabel(v);
83705         testcase( pTest->op==TK_COLUMN );
83706         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
83707         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
83708         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
83709         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
83710         sqlite3ExprCachePop(pParse);
83711         sqlite3VdbeResolveLabel(v, nextCase);
83712       }
83713       if( (nExpr&1)!=0 ){
83714         sqlite3ExprCachePush(pParse);
83715         sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
83716         sqlite3ExprCachePop(pParse);
83717       }else{
83718         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
83719       }
83720       assert( db->mallocFailed || pParse->nErr>0
83721            || pParse->iCacheLevel==iCacheLevel );
83722       sqlite3VdbeResolveLabel(v, endLabel);
83723       break;
83724     }
83725 #ifndef SQLITE_OMIT_TRIGGER
83726     case TK_RAISE: {
83727       assert( pExpr->affinity==OE_Rollback
83728            || pExpr->affinity==OE_Abort
83729            || pExpr->affinity==OE_Fail
83730            || pExpr->affinity==OE_Ignore
83731       );
83732       if( !pParse->pTriggerTab ){
83733         sqlite3ErrorMsg(pParse,
83734                        "RAISE() may only be used within a trigger-program");
83735         return 0;
83736       }
83737       if( pExpr->affinity==OE_Abort ){
83738         sqlite3MayAbort(pParse);
83739       }
83740       assert( !ExprHasProperty(pExpr, EP_IntValue) );
83741       if( pExpr->affinity==OE_Ignore ){
83742         sqlite3VdbeAddOp4(
83743             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
83744         VdbeCoverage(v);
83745       }else{
83746         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
83747                               pExpr->affinity, pExpr->u.zToken, 0, 0);
83748       }
83749 
83750       break;
83751     }
83752 #endif
83753   }
83754   sqlite3ReleaseTempReg(pParse, regFree1);
83755   sqlite3ReleaseTempReg(pParse, regFree2);
83756   return inReg;
83757 }
83758 
83759 /*
83760 ** Factor out the code of the given expression to initialization time.
83761 */
83762 SQLITE_PRIVATE void sqlite3ExprCodeAtInit(
83763   Parse *pParse,    /* Parsing context */
83764   Expr *pExpr,      /* The expression to code when the VDBE initializes */
83765   int regDest,      /* Store the value in this register */
83766   u8 reusable       /* True if this expression is reusable */
83767 ){
83768   ExprList *p;
83769   assert( ConstFactorOk(pParse) );
83770   p = pParse->pConstExpr;
83771   pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
83772   p = sqlite3ExprListAppend(pParse, p, pExpr);
83773   if( p ){
83774      struct ExprList_item *pItem = &p->a[p->nExpr-1];
83775      pItem->u.iConstExprReg = regDest;
83776      pItem->reusable = reusable;
83777   }
83778   pParse->pConstExpr = p;
83779 }
83780 
83781 /*
83782 ** Generate code to evaluate an expression and store the results
83783 ** into a register.  Return the register number where the results
83784 ** are stored.
83785 **
83786 ** If the register is a temporary register that can be deallocated,
83787 ** then write its number into *pReg.  If the result register is not
83788 ** a temporary, then set *pReg to zero.
83789 **
83790 ** If pExpr is a constant, then this routine might generate this
83791 ** code to fill the register in the initialization section of the
83792 ** VDBE program, in order to factor it out of the evaluation loop.
83793 */
83794 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
83795   int r2;
83796   pExpr = sqlite3ExprSkipCollate(pExpr);
83797   if( ConstFactorOk(pParse)
83798    && pExpr->op!=TK_REGISTER
83799    && sqlite3ExprIsConstantNotJoin(pExpr)
83800   ){
83801     ExprList *p = pParse->pConstExpr;
83802     int i;
83803     *pReg  = 0;
83804     if( p ){
83805       struct ExprList_item *pItem;
83806       for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
83807         if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
83808           return pItem->u.iConstExprReg;
83809         }
83810       }
83811     }
83812     r2 = ++pParse->nMem;
83813     sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
83814   }else{
83815     int r1 = sqlite3GetTempReg(pParse);
83816     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
83817     if( r2==r1 ){
83818       *pReg = r1;
83819     }else{
83820       sqlite3ReleaseTempReg(pParse, r1);
83821       *pReg = 0;
83822     }
83823   }
83824   return r2;
83825 }
83826 
83827 /*
83828 ** Generate code that will evaluate expression pExpr and store the
83829 ** results in register target.  The results are guaranteed to appear
83830 ** in register target.
83831 */
83832 SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
83833   int inReg;
83834 
83835   assert( target>0 && target<=pParse->nMem );
83836   if( pExpr && pExpr->op==TK_REGISTER ){
83837     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
83838   }else{
83839     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
83840     assert( pParse->pVdbe || pParse->db->mallocFailed );
83841     if( inReg!=target && pParse->pVdbe ){
83842       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
83843     }
83844   }
83845 }
83846 
83847 /*
83848 ** Generate code that will evaluate expression pExpr and store the
83849 ** results in register target.  The results are guaranteed to appear
83850 ** in register target.  If the expression is constant, then this routine
83851 ** might choose to code the expression at initialization time.
83852 */
83853 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
83854   if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
83855     sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
83856   }else{
83857     sqlite3ExprCode(pParse, pExpr, target);
83858   }
83859 }
83860 
83861 /*
83862 ** Generate code that evaluates the given expression and puts the result
83863 ** in register target.
83864 **
83865 ** Also make a copy of the expression results into another "cache" register
83866 ** and modify the expression so that the next time it is evaluated,
83867 ** the result is a copy of the cache register.
83868 **
83869 ** This routine is used for expressions that are used multiple
83870 ** times.  They are evaluated once and the results of the expression
83871 ** are reused.
83872 */
83873 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
83874   Vdbe *v = pParse->pVdbe;
83875   int iMem;
83876 
83877   assert( target>0 );
83878   assert( pExpr->op!=TK_REGISTER );
83879   sqlite3ExprCode(pParse, pExpr, target);
83880   iMem = ++pParse->nMem;
83881   sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
83882   exprToRegister(pExpr, iMem);
83883 }
83884 
83885 #ifdef SQLITE_DEBUG
83886 /*
83887 ** Generate a human-readable explanation of an expression tree.
83888 */
83889 SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
83890   const char *zBinOp = 0;   /* Binary operator */
83891   const char *zUniOp = 0;   /* Unary operator */
83892   pView = sqlite3TreeViewPush(pView, moreToFollow);
83893   if( pExpr==0 ){
83894     sqlite3TreeViewLine(pView, "nil");
83895     sqlite3TreeViewPop(pView);
83896     return;
83897   }
83898   switch( pExpr->op ){
83899     case TK_AGG_COLUMN: {
83900       sqlite3TreeViewLine(pView, "AGG{%d:%d}",
83901             pExpr->iTable, pExpr->iColumn);
83902       break;
83903     }
83904     case TK_COLUMN: {
83905       if( pExpr->iTable<0 ){
83906         /* This only happens when coding check constraints */
83907         sqlite3TreeViewLine(pView, "COLUMN(%d)", pExpr->iColumn);
83908       }else{
83909         sqlite3TreeViewLine(pView, "{%d:%d}",
83910                              pExpr->iTable, pExpr->iColumn);
83911       }
83912       break;
83913     }
83914     case TK_INTEGER: {
83915       if( pExpr->flags & EP_IntValue ){
83916         sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
83917       }else{
83918         sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
83919       }
83920       break;
83921     }
83922 #ifndef SQLITE_OMIT_FLOATING_POINT
83923     case TK_FLOAT: {
83924       sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
83925       break;
83926     }
83927 #endif
83928     case TK_STRING: {
83929       sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
83930       break;
83931     }
83932     case TK_NULL: {
83933       sqlite3TreeViewLine(pView,"NULL");
83934       break;
83935     }
83936 #ifndef SQLITE_OMIT_BLOB_LITERAL
83937     case TK_BLOB: {
83938       sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
83939       break;
83940     }
83941 #endif
83942     case TK_VARIABLE: {
83943       sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
83944                           pExpr->u.zToken, pExpr->iColumn);
83945       break;
83946     }
83947     case TK_REGISTER: {
83948       sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
83949       break;
83950     }
83951     case TK_AS: {
83952       sqlite3TreeViewLine(pView,"AS %Q", pExpr->u.zToken);
83953       sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
83954       break;
83955     }
83956     case TK_ID: {
83957       sqlite3TreeViewLine(pView,"ID %Q", pExpr->u.zToken);
83958       break;
83959     }
83960 #ifndef SQLITE_OMIT_CAST
83961     case TK_CAST: {
83962       /* Expressions of the form:   CAST(pLeft AS token) */
83963       sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
83964       sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
83965       break;
83966     }
83967 #endif /* SQLITE_OMIT_CAST */
83968     case TK_LT:      zBinOp = "LT";     break;
83969     case TK_LE:      zBinOp = "LE";     break;
83970     case TK_GT:      zBinOp = "GT";     break;
83971     case TK_GE:      zBinOp = "GE";     break;
83972     case TK_NE:      zBinOp = "NE";     break;
83973     case TK_EQ:      zBinOp = "EQ";     break;
83974     case TK_IS:      zBinOp = "IS";     break;
83975     case TK_ISNOT:   zBinOp = "ISNOT";  break;
83976     case TK_AND:     zBinOp = "AND";    break;
83977     case TK_OR:      zBinOp = "OR";     break;
83978     case TK_PLUS:    zBinOp = "ADD";    break;
83979     case TK_STAR:    zBinOp = "MUL";    break;
83980     case TK_MINUS:   zBinOp = "SUB";    break;
83981     case TK_REM:     zBinOp = "REM";    break;
83982     case TK_BITAND:  zBinOp = "BITAND"; break;
83983     case TK_BITOR:   zBinOp = "BITOR";  break;
83984     case TK_SLASH:   zBinOp = "DIV";    break;
83985     case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
83986     case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
83987     case TK_CONCAT:  zBinOp = "CONCAT"; break;
83988     case TK_DOT:     zBinOp = "DOT";    break;
83989 
83990     case TK_UMINUS:  zUniOp = "UMINUS"; break;
83991     case TK_UPLUS:   zUniOp = "UPLUS";  break;
83992     case TK_BITNOT:  zUniOp = "BITNOT"; break;
83993     case TK_NOT:     zUniOp = "NOT";    break;
83994     case TK_ISNULL:  zUniOp = "ISNULL"; break;
83995     case TK_NOTNULL: zUniOp = "NOTNULL"; break;
83996 
83997     case TK_COLLATE: {
83998       sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
83999       sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
84000       break;
84001     }
84002 
84003     case TK_AGG_FUNCTION:
84004     case TK_FUNCTION: {
84005       ExprList *pFarg;       /* List of function arguments */
84006       if( ExprHasProperty(pExpr, EP_TokenOnly) ){
84007         pFarg = 0;
84008       }else{
84009         pFarg = pExpr->x.pList;
84010       }
84011       if( pExpr->op==TK_AGG_FUNCTION ){
84012         sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
84013                              pExpr->op2, pExpr->u.zToken);
84014       }else{
84015         sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
84016       }
84017       if( pFarg ){
84018         sqlite3TreeViewExprList(pView, pFarg, 0, 0);
84019       }
84020       break;
84021     }
84022 #ifndef SQLITE_OMIT_SUBQUERY
84023     case TK_EXISTS: {
84024       sqlite3TreeViewLine(pView, "EXISTS-expr");
84025       sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
84026       break;
84027     }
84028     case TK_SELECT: {
84029       sqlite3TreeViewLine(pView, "SELECT-expr");
84030       sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
84031       break;
84032     }
84033     case TK_IN: {
84034       sqlite3TreeViewLine(pView, "IN");
84035       sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
84036       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
84037         sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
84038       }else{
84039         sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
84040       }
84041       break;
84042     }
84043 #endif /* SQLITE_OMIT_SUBQUERY */
84044 
84045     /*
84046     **    x BETWEEN y AND z
84047     **
84048     ** This is equivalent to
84049     **
84050     **    x>=y AND x<=z
84051     **
84052     ** X is stored in pExpr->pLeft.
84053     ** Y is stored in pExpr->pList->a[0].pExpr.
84054     ** Z is stored in pExpr->pList->a[1].pExpr.
84055     */
84056     case TK_BETWEEN: {
84057       Expr *pX = pExpr->pLeft;
84058       Expr *pY = pExpr->x.pList->a[0].pExpr;
84059       Expr *pZ = pExpr->x.pList->a[1].pExpr;
84060       sqlite3TreeViewLine(pView, "BETWEEN");
84061       sqlite3TreeViewExpr(pView, pX, 1);
84062       sqlite3TreeViewExpr(pView, pY, 1);
84063       sqlite3TreeViewExpr(pView, pZ, 0);
84064       break;
84065     }
84066     case TK_TRIGGER: {
84067       /* If the opcode is TK_TRIGGER, then the expression is a reference
84068       ** to a column in the new.* or old.* pseudo-tables available to
84069       ** trigger programs. In this case Expr.iTable is set to 1 for the
84070       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
84071       ** is set to the column of the pseudo-table to read, or to -1 to
84072       ** read the rowid field.
84073       */
84074       sqlite3TreeViewLine(pView, "%s(%d)",
84075           pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
84076       break;
84077     }
84078     case TK_CASE: {
84079       sqlite3TreeViewLine(pView, "CASE");
84080       sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
84081       sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
84082       break;
84083     }
84084 #ifndef SQLITE_OMIT_TRIGGER
84085     case TK_RAISE: {
84086       const char *zType = "unk";
84087       switch( pExpr->affinity ){
84088         case OE_Rollback:   zType = "rollback";  break;
84089         case OE_Abort:      zType = "abort";     break;
84090         case OE_Fail:       zType = "fail";      break;
84091         case OE_Ignore:     zType = "ignore";    break;
84092       }
84093       sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
84094       break;
84095     }
84096 #endif
84097     default: {
84098       sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
84099       break;
84100     }
84101   }
84102   if( zBinOp ){
84103     sqlite3TreeViewLine(pView, "%s", zBinOp);
84104     sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
84105     sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
84106   }else if( zUniOp ){
84107     sqlite3TreeViewLine(pView, "%s", zUniOp);
84108     sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
84109   }
84110   sqlite3TreeViewPop(pView);
84111 }
84112 #endif /* SQLITE_DEBUG */
84113 
84114 #ifdef SQLITE_DEBUG
84115 /*
84116 ** Generate a human-readable explanation of an expression list.
84117 */
84118 SQLITE_PRIVATE void sqlite3TreeViewExprList(
84119   TreeView *pView,
84120   const ExprList *pList,
84121   u8 moreToFollow,
84122   const char *zLabel
84123 ){
84124   int i;
84125   pView = sqlite3TreeViewPush(pView, moreToFollow);
84126   if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
84127   if( pList==0 ){
84128     sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
84129   }else{
84130     sqlite3TreeViewLine(pView, "%s", zLabel);
84131     for(i=0; i<pList->nExpr; i++){
84132       sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
84133 #if 0
84134      if( pList->a[i].zName ){
84135         sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
84136       }
84137       if( pList->a[i].bSpanIsTab ){
84138         sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
84139       }
84140 #endif
84141     }
84142   }
84143   sqlite3TreeViewPop(pView);
84144 }
84145 #endif /* SQLITE_DEBUG */
84146 
84147 /*
84148 ** Generate code that pushes the value of every element of the given
84149 ** expression list into a sequence of registers beginning at target.
84150 **
84151 ** Return the number of elements evaluated.
84152 **
84153 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
84154 ** filled using OP_SCopy.  OP_Copy must be used instead.
84155 **
84156 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
84157 ** factored out into initialization code.
84158 */
84159 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
84160   Parse *pParse,     /* Parsing context */
84161   ExprList *pList,   /* The expression list to be coded */
84162   int target,        /* Where to write results */
84163   u8 flags           /* SQLITE_ECEL_* flags */
84164 ){
84165   struct ExprList_item *pItem;
84166   int i, n;
84167   u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
84168   assert( pList!=0 );
84169   assert( target>0 );
84170   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
84171   n = pList->nExpr;
84172   if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
84173   for(pItem=pList->a, i=0; i<n; i++, pItem++){
84174     Expr *pExpr = pItem->pExpr;
84175     if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
84176       sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
84177     }else{
84178       int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
84179       if( inReg!=target+i ){
84180         VdbeOp *pOp;
84181         Vdbe *v = pParse->pVdbe;
84182         if( copyOp==OP_Copy
84183          && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
84184          && pOp->p1+pOp->p3+1==inReg
84185          && pOp->p2+pOp->p3+1==target+i
84186         ){
84187           pOp->p3++;
84188         }else{
84189           sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
84190         }
84191       }
84192     }
84193   }
84194   return n;
84195 }
84196 
84197 /*
84198 ** Generate code for a BETWEEN operator.
84199 **
84200 **    x BETWEEN y AND z
84201 **
84202 ** The above is equivalent to
84203 **
84204 **    x>=y AND x<=z
84205 **
84206 ** Code it as such, taking care to do the common subexpression
84207 ** elimination of x.
84208 */
84209 static void exprCodeBetween(
84210   Parse *pParse,    /* Parsing and code generating context */
84211   Expr *pExpr,      /* The BETWEEN expression */
84212   int dest,         /* Jump here if the jump is taken */
84213   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
84214   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
84215 ){
84216   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
84217   Expr compLeft;    /* The  x>=y  term */
84218   Expr compRight;   /* The  x<=z  term */
84219   Expr exprX;       /* The  x  subexpression */
84220   int regFree1 = 0; /* Temporary use register */
84221 
84222   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
84223   exprX = *pExpr->pLeft;
84224   exprAnd.op = TK_AND;
84225   exprAnd.pLeft = &compLeft;
84226   exprAnd.pRight = &compRight;
84227   compLeft.op = TK_GE;
84228   compLeft.pLeft = &exprX;
84229   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
84230   compRight.op = TK_LE;
84231   compRight.pLeft = &exprX;
84232   compRight.pRight = pExpr->x.pList->a[1].pExpr;
84233   exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
84234   if( jumpIfTrue ){
84235     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
84236   }else{
84237     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
84238   }
84239   sqlite3ReleaseTempReg(pParse, regFree1);
84240 
84241   /* Ensure adequate test coverage */
84242   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
84243   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
84244   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
84245   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
84246   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
84247   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
84248   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
84249   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
84250 }
84251 
84252 /*
84253 ** Generate code for a boolean expression such that a jump is made
84254 ** to the label "dest" if the expression is true but execution
84255 ** continues straight thru if the expression is false.
84256 **
84257 ** If the expression evaluates to NULL (neither true nor false), then
84258 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
84259 **
84260 ** This code depends on the fact that certain token values (ex: TK_EQ)
84261 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
84262 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
84263 ** the make process cause these values to align.  Assert()s in the code
84264 ** below verify that the numbers are aligned correctly.
84265 */
84266 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
84267   Vdbe *v = pParse->pVdbe;
84268   int op = 0;
84269   int regFree1 = 0;
84270   int regFree2 = 0;
84271   int r1, r2;
84272 
84273   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
84274   if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
84275   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
84276   op = pExpr->op;
84277   switch( op ){
84278     case TK_AND: {
84279       int d2 = sqlite3VdbeMakeLabel(v);
84280       testcase( jumpIfNull==0 );
84281       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
84282       sqlite3ExprCachePush(pParse);
84283       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
84284       sqlite3VdbeResolveLabel(v, d2);
84285       sqlite3ExprCachePop(pParse);
84286       break;
84287     }
84288     case TK_OR: {
84289       testcase( jumpIfNull==0 );
84290       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
84291       sqlite3ExprCachePush(pParse);
84292       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
84293       sqlite3ExprCachePop(pParse);
84294       break;
84295     }
84296     case TK_NOT: {
84297       testcase( jumpIfNull==0 );
84298       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
84299       break;
84300     }
84301     case TK_LT:
84302     case TK_LE:
84303     case TK_GT:
84304     case TK_GE:
84305     case TK_NE:
84306     case TK_EQ: {
84307       testcase( jumpIfNull==0 );
84308       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
84309       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
84310       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
84311                   r1, r2, dest, jumpIfNull);
84312       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
84313       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
84314       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
84315       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
84316       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
84317       assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
84318       testcase( regFree1==0 );
84319       testcase( regFree2==0 );
84320       break;
84321     }
84322     case TK_IS:
84323     case TK_ISNOT: {
84324       testcase( op==TK_IS );
84325       testcase( op==TK_ISNOT );
84326       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
84327       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
84328       op = (op==TK_IS) ? TK_EQ : TK_NE;
84329       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
84330                   r1, r2, dest, SQLITE_NULLEQ);
84331       VdbeCoverageIf(v, op==TK_EQ);
84332       VdbeCoverageIf(v, op==TK_NE);
84333       testcase( regFree1==0 );
84334       testcase( regFree2==0 );
84335       break;
84336     }
84337     case TK_ISNULL:
84338     case TK_NOTNULL: {
84339       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
84340       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
84341       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
84342       sqlite3VdbeAddOp2(v, op, r1, dest);
84343       VdbeCoverageIf(v, op==TK_ISNULL);
84344       VdbeCoverageIf(v, op==TK_NOTNULL);
84345       testcase( regFree1==0 );
84346       break;
84347     }
84348     case TK_BETWEEN: {
84349       testcase( jumpIfNull==0 );
84350       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
84351       break;
84352     }
84353 #ifndef SQLITE_OMIT_SUBQUERY
84354     case TK_IN: {
84355       int destIfFalse = sqlite3VdbeMakeLabel(v);
84356       int destIfNull = jumpIfNull ? dest : destIfFalse;
84357       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
84358       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
84359       sqlite3VdbeResolveLabel(v, destIfFalse);
84360       break;
84361     }
84362 #endif
84363     default: {
84364       if( exprAlwaysTrue(pExpr) ){
84365         sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
84366       }else if( exprAlwaysFalse(pExpr) ){
84367         /* No-op */
84368       }else{
84369         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
84370         sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
84371         VdbeCoverage(v);
84372         testcase( regFree1==0 );
84373         testcase( jumpIfNull==0 );
84374       }
84375       break;
84376     }
84377   }
84378   sqlite3ReleaseTempReg(pParse, regFree1);
84379   sqlite3ReleaseTempReg(pParse, regFree2);
84380 }
84381 
84382 /*
84383 ** Generate code for a boolean expression such that a jump is made
84384 ** to the label "dest" if the expression is false but execution
84385 ** continues straight thru if the expression is true.
84386 **
84387 ** If the expression evaluates to NULL (neither true nor false) then
84388 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
84389 ** is 0.
84390 */
84391 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
84392   Vdbe *v = pParse->pVdbe;
84393   int op = 0;
84394   int regFree1 = 0;
84395   int regFree2 = 0;
84396   int r1, r2;
84397 
84398   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
84399   if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
84400   if( pExpr==0 )    return;
84401 
84402   /* The value of pExpr->op and op are related as follows:
84403   **
84404   **       pExpr->op            op
84405   **       ---------          ----------
84406   **       TK_ISNULL          OP_NotNull
84407   **       TK_NOTNULL         OP_IsNull
84408   **       TK_NE              OP_Eq
84409   **       TK_EQ              OP_Ne
84410   **       TK_GT              OP_Le
84411   **       TK_LE              OP_Gt
84412   **       TK_GE              OP_Lt
84413   **       TK_LT              OP_Ge
84414   **
84415   ** For other values of pExpr->op, op is undefined and unused.
84416   ** The value of TK_ and OP_ constants are arranged such that we
84417   ** can compute the mapping above using the following expression.
84418   ** Assert()s verify that the computation is correct.
84419   */
84420   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
84421 
84422   /* Verify correct alignment of TK_ and OP_ constants
84423   */
84424   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
84425   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
84426   assert( pExpr->op!=TK_NE || op==OP_Eq );
84427   assert( pExpr->op!=TK_EQ || op==OP_Ne );
84428   assert( pExpr->op!=TK_LT || op==OP_Ge );
84429   assert( pExpr->op!=TK_LE || op==OP_Gt );
84430   assert( pExpr->op!=TK_GT || op==OP_Le );
84431   assert( pExpr->op!=TK_GE || op==OP_Lt );
84432 
84433   switch( pExpr->op ){
84434     case TK_AND: {
84435       testcase( jumpIfNull==0 );
84436       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
84437       sqlite3ExprCachePush(pParse);
84438       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
84439       sqlite3ExprCachePop(pParse);
84440       break;
84441     }
84442     case TK_OR: {
84443       int d2 = sqlite3VdbeMakeLabel(v);
84444       testcase( jumpIfNull==0 );
84445       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
84446       sqlite3ExprCachePush(pParse);
84447       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
84448       sqlite3VdbeResolveLabel(v, d2);
84449       sqlite3ExprCachePop(pParse);
84450       break;
84451     }
84452     case TK_NOT: {
84453       testcase( jumpIfNull==0 );
84454       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
84455       break;
84456     }
84457     case TK_LT:
84458     case TK_LE:
84459     case TK_GT:
84460     case TK_GE:
84461     case TK_NE:
84462     case TK_EQ: {
84463       testcase( jumpIfNull==0 );
84464       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
84465       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
84466       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
84467                   r1, r2, dest, jumpIfNull);
84468       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
84469       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
84470       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
84471       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
84472       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
84473       assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
84474       testcase( regFree1==0 );
84475       testcase( regFree2==0 );
84476       break;
84477     }
84478     case TK_IS:
84479     case TK_ISNOT: {
84480       testcase( pExpr->op==TK_IS );
84481       testcase( pExpr->op==TK_ISNOT );
84482       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
84483       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
84484       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
84485       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
84486                   r1, r2, dest, SQLITE_NULLEQ);
84487       VdbeCoverageIf(v, op==TK_EQ);
84488       VdbeCoverageIf(v, op==TK_NE);
84489       testcase( regFree1==0 );
84490       testcase( regFree2==0 );
84491       break;
84492     }
84493     case TK_ISNULL:
84494     case TK_NOTNULL: {
84495       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
84496       sqlite3VdbeAddOp2(v, op, r1, dest);
84497       testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
84498       testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
84499       testcase( regFree1==0 );
84500       break;
84501     }
84502     case TK_BETWEEN: {
84503       testcase( jumpIfNull==0 );
84504       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
84505       break;
84506     }
84507 #ifndef SQLITE_OMIT_SUBQUERY
84508     case TK_IN: {
84509       if( jumpIfNull ){
84510         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
84511       }else{
84512         int destIfNull = sqlite3VdbeMakeLabel(v);
84513         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
84514         sqlite3VdbeResolveLabel(v, destIfNull);
84515       }
84516       break;
84517     }
84518 #endif
84519     default: {
84520       if( exprAlwaysFalse(pExpr) ){
84521         sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
84522       }else if( exprAlwaysTrue(pExpr) ){
84523         /* no-op */
84524       }else{
84525         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
84526         sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
84527         VdbeCoverage(v);
84528         testcase( regFree1==0 );
84529         testcase( jumpIfNull==0 );
84530       }
84531       break;
84532     }
84533   }
84534   sqlite3ReleaseTempReg(pParse, regFree1);
84535   sqlite3ReleaseTempReg(pParse, regFree2);
84536 }
84537 
84538 /*
84539 ** Do a deep comparison of two expression trees.  Return 0 if the two
84540 ** expressions are completely identical.  Return 1 if they differ only
84541 ** by a COLLATE operator at the top level.  Return 2 if there are differences
84542 ** other than the top-level COLLATE operator.
84543 **
84544 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
84545 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
84546 **
84547 ** The pA side might be using TK_REGISTER.  If that is the case and pB is
84548 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
84549 **
84550 ** Sometimes this routine will return 2 even if the two expressions
84551 ** really are equivalent.  If we cannot prove that the expressions are
84552 ** identical, we return 2 just to be safe.  So if this routine
84553 ** returns 2, then you do not really know for certain if the two
84554 ** expressions are the same.  But if you get a 0 or 1 return, then you
84555 ** can be sure the expressions are the same.  In the places where
84556 ** this routine is used, it does not hurt to get an extra 2 - that
84557 ** just might result in some slightly slower code.  But returning
84558 ** an incorrect 0 or 1 could lead to a malfunction.
84559 */
84560 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
84561   u32 combinedFlags;
84562   if( pA==0 || pB==0 ){
84563     return pB==pA ? 0 : 2;
84564   }
84565   combinedFlags = pA->flags | pB->flags;
84566   if( combinedFlags & EP_IntValue ){
84567     if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
84568       return 0;
84569     }
84570     return 2;
84571   }
84572   if( pA->op!=pB->op ){
84573     if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
84574       return 1;
84575     }
84576     if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
84577       return 1;
84578     }
84579     return 2;
84580   }
84581   if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken ){
84582     if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
84583       return pA->op==TK_COLLATE ? 1 : 2;
84584     }
84585   }
84586   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
84587   if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
84588     if( combinedFlags & EP_xIsSelect ) return 2;
84589     if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
84590     if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
84591     if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
84592     if( ALWAYS((combinedFlags & EP_Reduced)==0) ){
84593       if( pA->iColumn!=pB->iColumn ) return 2;
84594       if( pA->iTable!=pB->iTable
84595        && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
84596     }
84597   }
84598   return 0;
84599 }
84600 
84601 /*
84602 ** Compare two ExprList objects.  Return 0 if they are identical and
84603 ** non-zero if they differ in any way.
84604 **
84605 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
84606 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
84607 **
84608 ** This routine might return non-zero for equivalent ExprLists.  The
84609 ** only consequence will be disabled optimizations.  But this routine
84610 ** must never return 0 if the two ExprList objects are different, or
84611 ** a malfunction will result.
84612 **
84613 ** Two NULL pointers are considered to be the same.  But a NULL pointer
84614 ** always differs from a non-NULL pointer.
84615 */
84616 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
84617   int i;
84618   if( pA==0 && pB==0 ) return 0;
84619   if( pA==0 || pB==0 ) return 1;
84620   if( pA->nExpr!=pB->nExpr ) return 1;
84621   for(i=0; i<pA->nExpr; i++){
84622     Expr *pExprA = pA->a[i].pExpr;
84623     Expr *pExprB = pB->a[i].pExpr;
84624     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
84625     if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
84626   }
84627   return 0;
84628 }
84629 
84630 /*
84631 ** Return true if we can prove the pE2 will always be true if pE1 is
84632 ** true.  Return false if we cannot complete the proof or if pE2 might
84633 ** be false.  Examples:
84634 **
84635 **     pE1: x==5       pE2: x==5             Result: true
84636 **     pE1: x>0        pE2: x==5             Result: false
84637 **     pE1: x=21       pE2: x=21 OR y=43     Result: true
84638 **     pE1: x!=123     pE2: x IS NOT NULL    Result: true
84639 **     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
84640 **     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
84641 **     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
84642 **
84643 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
84644 ** Expr.iTable<0 then assume a table number given by iTab.
84645 **
84646 ** When in doubt, return false.  Returning true might give a performance
84647 ** improvement.  Returning false might cause a performance reduction, but
84648 ** it will always give the correct answer and is hence always safe.
84649 */
84650 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
84651   if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
84652     return 1;
84653   }
84654   if( pE2->op==TK_OR
84655    && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
84656              || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
84657   ){
84658     return 1;
84659   }
84660   if( pE2->op==TK_NOTNULL
84661    && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
84662    && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
84663   ){
84664     return 1;
84665   }
84666   return 0;
84667 }
84668 
84669 /*
84670 ** An instance of the following structure is used by the tree walker
84671 ** to count references to table columns in the arguments of an
84672 ** aggregate function, in order to implement the
84673 ** sqlite3FunctionThisSrc() routine.
84674 */
84675 struct SrcCount {
84676   SrcList *pSrc;   /* One particular FROM clause in a nested query */
84677   int nThis;       /* Number of references to columns in pSrcList */
84678   int nOther;      /* Number of references to columns in other FROM clauses */
84679 };
84680 
84681 /*
84682 ** Count the number of references to columns.
84683 */
84684 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
84685   /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
84686   ** is always called before sqlite3ExprAnalyzeAggregates() and so the
84687   ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
84688   ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
84689   ** NEVER() will need to be removed. */
84690   if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
84691     int i;
84692     struct SrcCount *p = pWalker->u.pSrcCount;
84693     SrcList *pSrc = p->pSrc;
84694     for(i=0; i<pSrc->nSrc; i++){
84695       if( pExpr->iTable==pSrc->a[i].iCursor ) break;
84696     }
84697     if( i<pSrc->nSrc ){
84698       p->nThis++;
84699     }else{
84700       p->nOther++;
84701     }
84702   }
84703   return WRC_Continue;
84704 }
84705 
84706 /*
84707 ** Determine if any of the arguments to the pExpr Function reference
84708 ** pSrcList.  Return true if they do.  Also return true if the function
84709 ** has no arguments or has only constant arguments.  Return false if pExpr
84710 ** references columns but not columns of tables found in pSrcList.
84711 */
84712 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
84713   Walker w;
84714   struct SrcCount cnt;
84715   assert( pExpr->op==TK_AGG_FUNCTION );
84716   memset(&w, 0, sizeof(w));
84717   w.xExprCallback = exprSrcCount;
84718   w.u.pSrcCount = &cnt;
84719   cnt.pSrc = pSrcList;
84720   cnt.nThis = 0;
84721   cnt.nOther = 0;
84722   sqlite3WalkExprList(&w, pExpr->x.pList);
84723   return cnt.nThis>0 || cnt.nOther==0;
84724 }
84725 
84726 /*
84727 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
84728 ** the new element.  Return a negative number if malloc fails.
84729 */
84730 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
84731   int i;
84732   pInfo->aCol = sqlite3ArrayAllocate(
84733        db,
84734        pInfo->aCol,
84735        sizeof(pInfo->aCol[0]),
84736        &pInfo->nColumn,
84737        &i
84738   );
84739   return i;
84740 }
84741 
84742 /*
84743 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
84744 ** the new element.  Return a negative number if malloc fails.
84745 */
84746 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
84747   int i;
84748   pInfo->aFunc = sqlite3ArrayAllocate(
84749        db,
84750        pInfo->aFunc,
84751        sizeof(pInfo->aFunc[0]),
84752        &pInfo->nFunc,
84753        &i
84754   );
84755   return i;
84756 }
84757 
84758 /*
84759 ** This is the xExprCallback for a tree walker.  It is used to
84760 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
84761 ** for additional information.
84762 */
84763 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
84764   int i;
84765   NameContext *pNC = pWalker->u.pNC;
84766   Parse *pParse = pNC->pParse;
84767   SrcList *pSrcList = pNC->pSrcList;
84768   AggInfo *pAggInfo = pNC->pAggInfo;
84769 
84770   switch( pExpr->op ){
84771     case TK_AGG_COLUMN:
84772     case TK_COLUMN: {
84773       testcase( pExpr->op==TK_AGG_COLUMN );
84774       testcase( pExpr->op==TK_COLUMN );
84775       /* Check to see if the column is in one of the tables in the FROM
84776       ** clause of the aggregate query */
84777       if( ALWAYS(pSrcList!=0) ){
84778         struct SrcList_item *pItem = pSrcList->a;
84779         for(i=0; i<pSrcList->nSrc; i++, pItem++){
84780           struct AggInfo_col *pCol;
84781           assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
84782           if( pExpr->iTable==pItem->iCursor ){
84783             /* If we reach this point, it means that pExpr refers to a table
84784             ** that is in the FROM clause of the aggregate query.
84785             **
84786             ** Make an entry for the column in pAggInfo->aCol[] if there
84787             ** is not an entry there already.
84788             */
84789             int k;
84790             pCol = pAggInfo->aCol;
84791             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
84792               if( pCol->iTable==pExpr->iTable &&
84793                   pCol->iColumn==pExpr->iColumn ){
84794                 break;
84795               }
84796             }
84797             if( (k>=pAggInfo->nColumn)
84798              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
84799             ){
84800               pCol = &pAggInfo->aCol[k];
84801               pCol->pTab = pExpr->pTab;
84802               pCol->iTable = pExpr->iTable;
84803               pCol->iColumn = pExpr->iColumn;
84804               pCol->iMem = ++pParse->nMem;
84805               pCol->iSorterColumn = -1;
84806               pCol->pExpr = pExpr;
84807               if( pAggInfo->pGroupBy ){
84808                 int j, n;
84809                 ExprList *pGB = pAggInfo->pGroupBy;
84810                 struct ExprList_item *pTerm = pGB->a;
84811                 n = pGB->nExpr;
84812                 for(j=0; j<n; j++, pTerm++){
84813                   Expr *pE = pTerm->pExpr;
84814                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
84815                       pE->iColumn==pExpr->iColumn ){
84816                     pCol->iSorterColumn = j;
84817                     break;
84818                   }
84819                 }
84820               }
84821               if( pCol->iSorterColumn<0 ){
84822                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
84823               }
84824             }
84825             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
84826             ** because it was there before or because we just created it).
84827             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
84828             ** pAggInfo->aCol[] entry.
84829             */
84830             ExprSetVVAProperty(pExpr, EP_NoReduce);
84831             pExpr->pAggInfo = pAggInfo;
84832             pExpr->op = TK_AGG_COLUMN;
84833             pExpr->iAgg = (i16)k;
84834             break;
84835           } /* endif pExpr->iTable==pItem->iCursor */
84836         } /* end loop over pSrcList */
84837       }
84838       return WRC_Prune;
84839     }
84840     case TK_AGG_FUNCTION: {
84841       if( (pNC->ncFlags & NC_InAggFunc)==0
84842        && pWalker->walkerDepth==pExpr->op2
84843       ){
84844         /* Check to see if pExpr is a duplicate of another aggregate
84845         ** function that is already in the pAggInfo structure
84846         */
84847         struct AggInfo_func *pItem = pAggInfo->aFunc;
84848         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
84849           if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
84850             break;
84851           }
84852         }
84853         if( i>=pAggInfo->nFunc ){
84854           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
84855           */
84856           u8 enc = ENC(pParse->db);
84857           i = addAggInfoFunc(pParse->db, pAggInfo);
84858           if( i>=0 ){
84859             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
84860             pItem = &pAggInfo->aFunc[i];
84861             pItem->pExpr = pExpr;
84862             pItem->iMem = ++pParse->nMem;
84863             assert( !ExprHasProperty(pExpr, EP_IntValue) );
84864             pItem->pFunc = sqlite3FindFunction(pParse->db,
84865                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
84866                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
84867             if( pExpr->flags & EP_Distinct ){
84868               pItem->iDistinct = pParse->nTab++;
84869             }else{
84870               pItem->iDistinct = -1;
84871             }
84872           }
84873         }
84874         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
84875         */
84876         assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
84877         ExprSetVVAProperty(pExpr, EP_NoReduce);
84878         pExpr->iAgg = (i16)i;
84879         pExpr->pAggInfo = pAggInfo;
84880         return WRC_Prune;
84881       }else{
84882         return WRC_Continue;
84883       }
84884     }
84885   }
84886   return WRC_Continue;
84887 }
84888 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
84889   UNUSED_PARAMETER(pWalker);
84890   UNUSED_PARAMETER(pSelect);
84891   return WRC_Continue;
84892 }
84893 
84894 /*
84895 ** Analyze the pExpr expression looking for aggregate functions and
84896 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
84897 ** points to.  Additional entries are made on the AggInfo object as
84898 ** necessary.
84899 **
84900 ** This routine should only be called after the expression has been
84901 ** analyzed by sqlite3ResolveExprNames().
84902 */
84903 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
84904   Walker w;
84905   memset(&w, 0, sizeof(w));
84906   w.xExprCallback = analyzeAggregate;
84907   w.xSelectCallback = analyzeAggregatesInSelect;
84908   w.u.pNC = pNC;
84909   assert( pNC->pSrcList!=0 );
84910   sqlite3WalkExpr(&w, pExpr);
84911 }
84912 
84913 /*
84914 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
84915 ** expression list.  Return the number of errors.
84916 **
84917 ** If an error is found, the analysis is cut short.
84918 */
84919 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
84920   struct ExprList_item *pItem;
84921   int i;
84922   if( pList ){
84923     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
84924       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
84925     }
84926   }
84927 }
84928 
84929 /*
84930 ** Allocate a single new register for use to hold some intermediate result.
84931 */
84932 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
84933   if( pParse->nTempReg==0 ){
84934     return ++pParse->nMem;
84935   }
84936   return pParse->aTempReg[--pParse->nTempReg];
84937 }
84938 
84939 /*
84940 ** Deallocate a register, making available for reuse for some other
84941 ** purpose.
84942 **
84943 ** If a register is currently being used by the column cache, then
84944 ** the deallocation is deferred until the column cache line that uses
84945 ** the register becomes stale.
84946 */
84947 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
84948   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
84949     int i;
84950     struct yColCache *p;
84951     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
84952       if( p->iReg==iReg ){
84953         p->tempReg = 1;
84954         return;
84955       }
84956     }
84957     pParse->aTempReg[pParse->nTempReg++] = iReg;
84958   }
84959 }
84960 
84961 /*
84962 ** Allocate or deallocate a block of nReg consecutive registers
84963 */
84964 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
84965   int i, n;
84966   i = pParse->iRangeReg;
84967   n = pParse->nRangeReg;
84968   if( nReg<=n ){
84969     assert( !usedAsColumnCache(pParse, i, i+n-1) );
84970     pParse->iRangeReg += nReg;
84971     pParse->nRangeReg -= nReg;
84972   }else{
84973     i = pParse->nMem+1;
84974     pParse->nMem += nReg;
84975   }
84976   return i;
84977 }
84978 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
84979   sqlite3ExprCacheRemove(pParse, iReg, nReg);
84980   if( nReg>pParse->nRangeReg ){
84981     pParse->nRangeReg = nReg;
84982     pParse->iRangeReg = iReg;
84983   }
84984 }
84985 
84986 /*
84987 ** Mark all temporary registers as being unavailable for reuse.
84988 */
84989 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
84990   pParse->nTempReg = 0;
84991   pParse->nRangeReg = 0;
84992 }
84993 
84994 /************** End of expr.c ************************************************/
84995 /************** Begin file alter.c *******************************************/
84996 /*
84997 ** 2005 February 15
84998 **
84999 ** The author disclaims copyright to this source code.  In place of
85000 ** a legal notice, here is a blessing:
85001 **
85002 **    May you do good and not evil.
85003 **    May you find forgiveness for yourself and forgive others.
85004 **    May you share freely, never taking more than you give.
85005 **
85006 *************************************************************************
85007 ** This file contains C code routines that used to generate VDBE code
85008 ** that implements the ALTER TABLE command.
85009 */
85010 
85011 /*
85012 ** The code in this file only exists if we are not omitting the
85013 ** ALTER TABLE logic from the build.
85014 */
85015 #ifndef SQLITE_OMIT_ALTERTABLE
85016 
85017 
85018 /*
85019 ** This function is used by SQL generated to implement the
85020 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
85021 ** CREATE INDEX command. The second is a table name. The table name in
85022 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
85023 ** argument and the result returned. Examples:
85024 **
85025 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
85026 **     -> 'CREATE TABLE def(a, b, c)'
85027 **
85028 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
85029 **     -> 'CREATE INDEX i ON def(a, b, c)'
85030 */
85031 static void renameTableFunc(
85032   sqlite3_context *context,
85033   int NotUsed,
85034   sqlite3_value **argv
85035 ){
85036   unsigned char const *zSql = sqlite3_value_text(argv[0]);
85037   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
85038 
85039   int token;
85040   Token tname;
85041   unsigned char const *zCsr = zSql;
85042   int len = 0;
85043   char *zRet;
85044 
85045   sqlite3 *db = sqlite3_context_db_handle(context);
85046 
85047   UNUSED_PARAMETER(NotUsed);
85048 
85049   /* The principle used to locate the table name in the CREATE TABLE
85050   ** statement is that the table name is the first non-space token that
85051   ** is immediately followed by a TK_LP or TK_USING token.
85052   */
85053   if( zSql ){
85054     do {
85055       if( !*zCsr ){
85056         /* Ran out of input before finding an opening bracket. Return NULL. */
85057         return;
85058       }
85059 
85060       /* Store the token that zCsr points to in tname. */
85061       tname.z = (char*)zCsr;
85062       tname.n = len;
85063 
85064       /* Advance zCsr to the next token. Store that token type in 'token',
85065       ** and its length in 'len' (to be used next iteration of this loop).
85066       */
85067       do {
85068         zCsr += len;
85069         len = sqlite3GetToken(zCsr, &token);
85070       } while( token==TK_SPACE );
85071       assert( len>0 );
85072     } while( token!=TK_LP && token!=TK_USING );
85073 
85074     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
85075        zSql, zTableName, tname.z+tname.n);
85076     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
85077   }
85078 }
85079 
85080 /*
85081 ** This C function implements an SQL user function that is used by SQL code
85082 ** generated by the ALTER TABLE ... RENAME command to modify the definition
85083 ** of any foreign key constraints that use the table being renamed as the
85084 ** parent table. It is passed three arguments:
85085 **
85086 **   1) The complete text of the CREATE TABLE statement being modified,
85087 **   2) The old name of the table being renamed, and
85088 **   3) The new name of the table being renamed.
85089 **
85090 ** It returns the new CREATE TABLE statement. For example:
85091 **
85092 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
85093 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
85094 */
85095 #ifndef SQLITE_OMIT_FOREIGN_KEY
85096 static void renameParentFunc(
85097   sqlite3_context *context,
85098   int NotUsed,
85099   sqlite3_value **argv
85100 ){
85101   sqlite3 *db = sqlite3_context_db_handle(context);
85102   char *zOutput = 0;
85103   char *zResult;
85104   unsigned char const *zInput = sqlite3_value_text(argv[0]);
85105   unsigned char const *zOld = sqlite3_value_text(argv[1]);
85106   unsigned char const *zNew = sqlite3_value_text(argv[2]);
85107 
85108   unsigned const char *z;         /* Pointer to token */
85109   int n;                          /* Length of token z */
85110   int token;                      /* Type of token */
85111 
85112   UNUSED_PARAMETER(NotUsed);
85113   if( zInput==0 || zOld==0 ) return;
85114   for(z=zInput; *z; z=z+n){
85115     n = sqlite3GetToken(z, &token);
85116     if( token==TK_REFERENCES ){
85117       char *zParent;
85118       do {
85119         z += n;
85120         n = sqlite3GetToken(z, &token);
85121       }while( token==TK_SPACE );
85122 
85123       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
85124       if( zParent==0 ) break;
85125       sqlite3Dequote(zParent);
85126       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
85127         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
85128             (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
85129         );
85130         sqlite3DbFree(db, zOutput);
85131         zOutput = zOut;
85132         zInput = &z[n];
85133       }
85134       sqlite3DbFree(db, zParent);
85135     }
85136   }
85137 
85138   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
85139   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
85140   sqlite3DbFree(db, zOutput);
85141 }
85142 #endif
85143 
85144 #ifndef SQLITE_OMIT_TRIGGER
85145 /* This function is used by SQL generated to implement the
85146 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
85147 ** statement. The second is a table name. The table name in the CREATE
85148 ** TRIGGER statement is replaced with the third argument and the result
85149 ** returned. This is analagous to renameTableFunc() above, except for CREATE
85150 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
85151 */
85152 static void renameTriggerFunc(
85153   sqlite3_context *context,
85154   int NotUsed,
85155   sqlite3_value **argv
85156 ){
85157   unsigned char const *zSql = sqlite3_value_text(argv[0]);
85158   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
85159 
85160   int token;
85161   Token tname;
85162   int dist = 3;
85163   unsigned char const *zCsr = zSql;
85164   int len = 0;
85165   char *zRet;
85166   sqlite3 *db = sqlite3_context_db_handle(context);
85167 
85168   UNUSED_PARAMETER(NotUsed);
85169 
85170   /* The principle used to locate the table name in the CREATE TRIGGER
85171   ** statement is that the table name is the first token that is immediately
85172   ** preceded by either TK_ON or TK_DOT and immediately followed by one
85173   ** of TK_WHEN, TK_BEGIN or TK_FOR.
85174   */
85175   if( zSql ){
85176     do {
85177 
85178       if( !*zCsr ){
85179         /* Ran out of input before finding the table name. Return NULL. */
85180         return;
85181       }
85182 
85183       /* Store the token that zCsr points to in tname. */
85184       tname.z = (char*)zCsr;
85185       tname.n = len;
85186 
85187       /* Advance zCsr to the next token. Store that token type in 'token',
85188       ** and its length in 'len' (to be used next iteration of this loop).
85189       */
85190       do {
85191         zCsr += len;
85192         len = sqlite3GetToken(zCsr, &token);
85193       }while( token==TK_SPACE );
85194       assert( len>0 );
85195 
85196       /* Variable 'dist' stores the number of tokens read since the most
85197       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
85198       ** token is read and 'dist' equals 2, the condition stated above
85199       ** to be met.
85200       **
85201       ** Note that ON cannot be a database, table or column name, so
85202       ** there is no need to worry about syntax like
85203       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
85204       */
85205       dist++;
85206       if( token==TK_DOT || token==TK_ON ){
85207         dist = 0;
85208       }
85209     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
85210 
85211     /* Variable tname now contains the token that is the old table-name
85212     ** in the CREATE TRIGGER statement.
85213     */
85214     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
85215        zSql, zTableName, tname.z+tname.n);
85216     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
85217   }
85218 }
85219 #endif   /* !SQLITE_OMIT_TRIGGER */
85220 
85221 /*
85222 ** Register built-in functions used to help implement ALTER TABLE
85223 */
85224 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
85225   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
85226     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
85227 #ifndef SQLITE_OMIT_TRIGGER
85228     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
85229 #endif
85230 #ifndef SQLITE_OMIT_FOREIGN_KEY
85231     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
85232 #endif
85233   };
85234   int i;
85235   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
85236   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
85237 
85238   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
85239     sqlite3FuncDefInsert(pHash, &aFunc[i]);
85240   }
85241 }
85242 
85243 /*
85244 ** This function is used to create the text of expressions of the form:
85245 **
85246 **   name=<constant1> OR name=<constant2> OR ...
85247 **
85248 ** If argument zWhere is NULL, then a pointer string containing the text
85249 ** "name=<constant>" is returned, where <constant> is the quoted version
85250 ** of the string passed as argument zConstant. The returned buffer is
85251 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
85252 ** caller to ensure that it is eventually freed.
85253 **
85254 ** If argument zWhere is not NULL, then the string returned is
85255 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
85256 ** In this case zWhere is passed to sqlite3DbFree() before returning.
85257 **
85258 */
85259 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
85260   char *zNew;
85261   if( !zWhere ){
85262     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
85263   }else{
85264     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
85265     sqlite3DbFree(db, zWhere);
85266   }
85267   return zNew;
85268 }
85269 
85270 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
85271 /*
85272 ** Generate the text of a WHERE expression which can be used to select all
85273 ** tables that have foreign key constraints that refer to table pTab (i.e.
85274 ** constraints for which pTab is the parent table) from the sqlite_master
85275 ** table.
85276 */
85277 static char *whereForeignKeys(Parse *pParse, Table *pTab){
85278   FKey *p;
85279   char *zWhere = 0;
85280   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
85281     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
85282   }
85283   return zWhere;
85284 }
85285 #endif
85286 
85287 /*
85288 ** Generate the text of a WHERE expression which can be used to select all
85289 ** temporary triggers on table pTab from the sqlite_temp_master table. If
85290 ** table pTab has no temporary triggers, or is itself stored in the
85291 ** temporary database, NULL is returned.
85292 */
85293 static char *whereTempTriggers(Parse *pParse, Table *pTab){
85294   Trigger *pTrig;
85295   char *zWhere = 0;
85296   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
85297 
85298   /* If the table is not located in the temp-db (in which case NULL is
85299   ** returned, loop through the tables list of triggers. For each trigger
85300   ** that is not part of the temp-db schema, add a clause to the WHERE
85301   ** expression being built up in zWhere.
85302   */
85303   if( pTab->pSchema!=pTempSchema ){
85304     sqlite3 *db = pParse->db;
85305     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
85306       if( pTrig->pSchema==pTempSchema ){
85307         zWhere = whereOrName(db, zWhere, pTrig->zName);
85308       }
85309     }
85310   }
85311   if( zWhere ){
85312     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
85313     sqlite3DbFree(pParse->db, zWhere);
85314     zWhere = zNew;
85315   }
85316   return zWhere;
85317 }
85318 
85319 /*
85320 ** Generate code to drop and reload the internal representation of table
85321 ** pTab from the database, including triggers and temporary triggers.
85322 ** Argument zName is the name of the table in the database schema at
85323 ** the time the generated code is executed. This can be different from
85324 ** pTab->zName if this function is being called to code part of an
85325 ** "ALTER TABLE RENAME TO" statement.
85326 */
85327 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
85328   Vdbe *v;
85329   char *zWhere;
85330   int iDb;                   /* Index of database containing pTab */
85331 #ifndef SQLITE_OMIT_TRIGGER
85332   Trigger *pTrig;
85333 #endif
85334 
85335   v = sqlite3GetVdbe(pParse);
85336   if( NEVER(v==0) ) return;
85337   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
85338   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
85339   assert( iDb>=0 );
85340 
85341 #ifndef SQLITE_OMIT_TRIGGER
85342   /* Drop any table triggers from the internal schema. */
85343   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
85344     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
85345     assert( iTrigDb==iDb || iTrigDb==1 );
85346     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
85347   }
85348 #endif
85349 
85350   /* Drop the table and index from the internal schema.  */
85351   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
85352 
85353   /* Reload the table, index and permanent trigger schemas. */
85354   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
85355   if( !zWhere ) return;
85356   sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
85357 
85358 #ifndef SQLITE_OMIT_TRIGGER
85359   /* Now, if the table is not stored in the temp database, reload any temp
85360   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
85361   */
85362   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
85363     sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
85364   }
85365 #endif
85366 }
85367 
85368 /*
85369 ** Parameter zName is the name of a table that is about to be altered
85370 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
85371 ** If the table is a system table, this function leaves an error message
85372 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
85373 **
85374 ** Or, if zName is not a system table, zero is returned.
85375 */
85376 static int isSystemTable(Parse *pParse, const char *zName){
85377   if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
85378     sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
85379     return 1;
85380   }
85381   return 0;
85382 }
85383 
85384 /*
85385 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
85386 ** command.
85387 */
85388 SQLITE_PRIVATE void sqlite3AlterRenameTable(
85389   Parse *pParse,            /* Parser context. */
85390   SrcList *pSrc,            /* The table to rename. */
85391   Token *pName              /* The new table name. */
85392 ){
85393   int iDb;                  /* Database that contains the table */
85394   char *zDb;                /* Name of database iDb */
85395   Table *pTab;              /* Table being renamed */
85396   char *zName = 0;          /* NULL-terminated version of pName */
85397   sqlite3 *db = pParse->db; /* Database connection */
85398   int nTabName;             /* Number of UTF-8 characters in zTabName */
85399   const char *zTabName;     /* Original name of the table */
85400   Vdbe *v;
85401 #ifndef SQLITE_OMIT_TRIGGER
85402   char *zWhere = 0;         /* Where clause to locate temp triggers */
85403 #endif
85404   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
85405   int savedDbFlags;         /* Saved value of db->flags */
85406 
85407   savedDbFlags = db->flags;
85408   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
85409   assert( pSrc->nSrc==1 );
85410   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
85411 
85412   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
85413   if( !pTab ) goto exit_rename_table;
85414   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
85415   zDb = db->aDb[iDb].zName;
85416   db->flags |= SQLITE_PreferBuiltin;
85417 
85418   /* Get a NULL terminated version of the new table name. */
85419   zName = sqlite3NameFromToken(db, pName);
85420   if( !zName ) goto exit_rename_table;
85421 
85422   /* Check that a table or index named 'zName' does not already exist
85423   ** in database iDb. If so, this is an error.
85424   */
85425   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
85426     sqlite3ErrorMsg(pParse,
85427         "there is already another table or index with this name: %s", zName);
85428     goto exit_rename_table;
85429   }
85430 
85431   /* Make sure it is not a system table being altered, or a reserved name
85432   ** that the table is being renamed to.
85433   */
85434   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
85435     goto exit_rename_table;
85436   }
85437   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
85438     exit_rename_table;
85439   }
85440 
85441 #ifndef SQLITE_OMIT_VIEW
85442   if( pTab->pSelect ){
85443     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
85444     goto exit_rename_table;
85445   }
85446 #endif
85447 
85448 #ifndef SQLITE_OMIT_AUTHORIZATION
85449   /* Invoke the authorization callback. */
85450   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
85451     goto exit_rename_table;
85452   }
85453 #endif
85454 
85455 #ifndef SQLITE_OMIT_VIRTUALTABLE
85456   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
85457     goto exit_rename_table;
85458   }
85459   if( IsVirtual(pTab) ){
85460     pVTab = sqlite3GetVTable(db, pTab);
85461     if( pVTab->pVtab->pModule->xRename==0 ){
85462       pVTab = 0;
85463     }
85464   }
85465 #endif
85466 
85467   /* Begin a transaction for database iDb.
85468   ** Then modify the schema cookie (since the ALTER TABLE modifies the
85469   ** schema). Open a statement transaction if the table is a virtual
85470   ** table.
85471   */
85472   v = sqlite3GetVdbe(pParse);
85473   if( v==0 ){
85474     goto exit_rename_table;
85475   }
85476   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
85477   sqlite3ChangeCookie(pParse, iDb);
85478 
85479   /* If this is a virtual table, invoke the xRename() function if
85480   ** one is defined. The xRename() callback will modify the names
85481   ** of any resources used by the v-table implementation (including other
85482   ** SQLite tables) that are identified by the name of the virtual table.
85483   */
85484 #ifndef SQLITE_OMIT_VIRTUALTABLE
85485   if( pVTab ){
85486     int i = ++pParse->nMem;
85487     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
85488     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
85489     sqlite3MayAbort(pParse);
85490   }
85491 #endif
85492 
85493   /* figure out how many UTF-8 characters are in zName */
85494   zTabName = pTab->zName;
85495   nTabName = sqlite3Utf8CharLen(zTabName, -1);
85496 
85497 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
85498   if( db->flags&SQLITE_ForeignKeys ){
85499     /* If foreign-key support is enabled, rewrite the CREATE TABLE
85500     ** statements corresponding to all child tables of foreign key constraints
85501     ** for which the renamed table is the parent table.  */
85502     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
85503       sqlite3NestedParse(pParse,
85504           "UPDATE \"%w\".%s SET "
85505               "sql = sqlite_rename_parent(sql, %Q, %Q) "
85506               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
85507       sqlite3DbFree(db, zWhere);
85508     }
85509   }
85510 #endif
85511 
85512   /* Modify the sqlite_master table to use the new table name. */
85513   sqlite3NestedParse(pParse,
85514       "UPDATE %Q.%s SET "
85515 #ifdef SQLITE_OMIT_TRIGGER
85516           "sql = sqlite_rename_table(sql, %Q), "
85517 #else
85518           "sql = CASE "
85519             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
85520             "ELSE sqlite_rename_table(sql, %Q) END, "
85521 #endif
85522           "tbl_name = %Q, "
85523           "name = CASE "
85524             "WHEN type='table' THEN %Q "
85525             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
85526              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
85527             "ELSE name END "
85528       "WHERE tbl_name=%Q COLLATE nocase AND "
85529           "(type='table' OR type='index' OR type='trigger');",
85530       zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
85531 #ifndef SQLITE_OMIT_TRIGGER
85532       zName,
85533 #endif
85534       zName, nTabName, zTabName
85535   );
85536 
85537 #ifndef SQLITE_OMIT_AUTOINCREMENT
85538   /* If the sqlite_sequence table exists in this database, then update
85539   ** it with the new table name.
85540   */
85541   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
85542     sqlite3NestedParse(pParse,
85543         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
85544         zDb, zName, pTab->zName);
85545   }
85546 #endif
85547 
85548 #ifndef SQLITE_OMIT_TRIGGER
85549   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
85550   ** table. Don't do this if the table being ALTERed is itself located in
85551   ** the temp database.
85552   */
85553   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
85554     sqlite3NestedParse(pParse,
85555         "UPDATE sqlite_temp_master SET "
85556             "sql = sqlite_rename_trigger(sql, %Q), "
85557             "tbl_name = %Q "
85558             "WHERE %s;", zName, zName, zWhere);
85559     sqlite3DbFree(db, zWhere);
85560   }
85561 #endif
85562 
85563 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
85564   if( db->flags&SQLITE_ForeignKeys ){
85565     FKey *p;
85566     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
85567       Table *pFrom = p->pFrom;
85568       if( pFrom!=pTab ){
85569         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
85570       }
85571     }
85572   }
85573 #endif
85574 
85575   /* Drop and reload the internal table schema. */
85576   reloadTableSchema(pParse, pTab, zName);
85577 
85578 exit_rename_table:
85579   sqlite3SrcListDelete(db, pSrc);
85580   sqlite3DbFree(db, zName);
85581   db->flags = savedDbFlags;
85582 }
85583 
85584 
85585 /*
85586 ** Generate code to make sure the file format number is at least minFormat.
85587 ** The generated code will increase the file format number if necessary.
85588 */
85589 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
85590   Vdbe *v;
85591   v = sqlite3GetVdbe(pParse);
85592   /* The VDBE should have been allocated before this routine is called.
85593   ** If that allocation failed, we would have quit before reaching this
85594   ** point */
85595   if( ALWAYS(v) ){
85596     int r1 = sqlite3GetTempReg(pParse);
85597     int r2 = sqlite3GetTempReg(pParse);
85598     int j1;
85599     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
85600     sqlite3VdbeUsesBtree(v, iDb);
85601     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
85602     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
85603     sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverage(v);
85604     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
85605     sqlite3VdbeJumpHere(v, j1);
85606     sqlite3ReleaseTempReg(pParse, r1);
85607     sqlite3ReleaseTempReg(pParse, r2);
85608   }
85609 }
85610 
85611 /*
85612 ** This function is called after an "ALTER TABLE ... ADD" statement
85613 ** has been parsed. Argument pColDef contains the text of the new
85614 ** column definition.
85615 **
85616 ** The Table structure pParse->pNewTable was extended to include
85617 ** the new column during parsing.
85618 */
85619 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
85620   Table *pNew;              /* Copy of pParse->pNewTable */
85621   Table *pTab;              /* Table being altered */
85622   int iDb;                  /* Database number */
85623   const char *zDb;          /* Database name */
85624   const char *zTab;         /* Table name */
85625   char *zCol;               /* Null-terminated column definition */
85626   Column *pCol;             /* The new column */
85627   Expr *pDflt;              /* Default value for the new column */
85628   sqlite3 *db;              /* The database connection; */
85629 
85630   db = pParse->db;
85631   if( pParse->nErr || db->mallocFailed ) return;
85632   pNew = pParse->pNewTable;
85633   assert( pNew );
85634 
85635   assert( sqlite3BtreeHoldsAllMutexes(db) );
85636   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
85637   zDb = db->aDb[iDb].zName;
85638   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
85639   pCol = &pNew->aCol[pNew->nCol-1];
85640   pDflt = pCol->pDflt;
85641   pTab = sqlite3FindTable(db, zTab, zDb);
85642   assert( pTab );
85643 
85644 #ifndef SQLITE_OMIT_AUTHORIZATION
85645   /* Invoke the authorization callback. */
85646   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
85647     return;
85648   }
85649 #endif
85650 
85651   /* If the default value for the new column was specified with a
85652   ** literal NULL, then set pDflt to 0. This simplifies checking
85653   ** for an SQL NULL default below.
85654   */
85655   if( pDflt && pDflt->op==TK_NULL ){
85656     pDflt = 0;
85657   }
85658 
85659   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
85660   ** If there is a NOT NULL constraint, then the default value for the
85661   ** column must not be NULL.
85662   */
85663   if( pCol->colFlags & COLFLAG_PRIMKEY ){
85664     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
85665     return;
85666   }
85667   if( pNew->pIndex ){
85668     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
85669     return;
85670   }
85671   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
85672     sqlite3ErrorMsg(pParse,
85673         "Cannot add a REFERENCES column with non-NULL default value");
85674     return;
85675   }
85676   if( pCol->notNull && !pDflt ){
85677     sqlite3ErrorMsg(pParse,
85678         "Cannot add a NOT NULL column with default value NULL");
85679     return;
85680   }
85681 
85682   /* Ensure the default expression is something that sqlite3ValueFromExpr()
85683   ** can handle (i.e. not CURRENT_TIME etc.)
85684   */
85685   if( pDflt ){
85686     sqlite3_value *pVal = 0;
85687     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
85688       db->mallocFailed = 1;
85689       return;
85690     }
85691     if( !pVal ){
85692       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
85693       return;
85694     }
85695     sqlite3ValueFree(pVal);
85696   }
85697 
85698   /* Modify the CREATE TABLE statement. */
85699   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
85700   if( zCol ){
85701     char *zEnd = &zCol[pColDef->n-1];
85702     int savedDbFlags = db->flags;
85703     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
85704       *zEnd-- = '\0';
85705     }
85706     db->flags |= SQLITE_PreferBuiltin;
85707     sqlite3NestedParse(pParse,
85708         "UPDATE \"%w\".%s SET "
85709           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
85710         "WHERE type = 'table' AND name = %Q",
85711       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
85712       zTab
85713     );
85714     sqlite3DbFree(db, zCol);
85715     db->flags = savedDbFlags;
85716   }
85717 
85718   /* If the default value of the new column is NULL, then set the file
85719   ** format to 2. If the default value of the new column is not NULL,
85720   ** the file format becomes 3.
85721   */
85722   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
85723 
85724   /* Reload the schema of the modified table. */
85725   reloadTableSchema(pParse, pTab, pTab->zName);
85726 }
85727 
85728 /*
85729 ** This function is called by the parser after the table-name in
85730 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
85731 ** pSrc is the full-name of the table being altered.
85732 **
85733 ** This routine makes a (partial) copy of the Table structure
85734 ** for the table being altered and sets Parse.pNewTable to point
85735 ** to it. Routines called by the parser as the column definition
85736 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
85737 ** the copy. The copy of the Table structure is deleted by tokenize.c
85738 ** after parsing is finished.
85739 **
85740 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
85741 ** coding the "ALTER TABLE ... ADD" statement.
85742 */
85743 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
85744   Table *pNew;
85745   Table *pTab;
85746   Vdbe *v;
85747   int iDb;
85748   int i;
85749   int nAlloc;
85750   sqlite3 *db = pParse->db;
85751 
85752   /* Look up the table being altered. */
85753   assert( pParse->pNewTable==0 );
85754   assert( sqlite3BtreeHoldsAllMutexes(db) );
85755   if( db->mallocFailed ) goto exit_begin_add_column;
85756   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
85757   if( !pTab ) goto exit_begin_add_column;
85758 
85759 #ifndef SQLITE_OMIT_VIRTUALTABLE
85760   if( IsVirtual(pTab) ){
85761     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
85762     goto exit_begin_add_column;
85763   }
85764 #endif
85765 
85766   /* Make sure this is not an attempt to ALTER a view. */
85767   if( pTab->pSelect ){
85768     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
85769     goto exit_begin_add_column;
85770   }
85771   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
85772     goto exit_begin_add_column;
85773   }
85774 
85775   assert( pTab->addColOffset>0 );
85776   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
85777 
85778   /* Put a copy of the Table struct in Parse.pNewTable for the
85779   ** sqlite3AddColumn() function and friends to modify.  But modify
85780   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
85781   ** prefix, we insure that the name will not collide with an existing
85782   ** table because user table are not allowed to have the "sqlite_"
85783   ** prefix on their name.
85784   */
85785   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
85786   if( !pNew ) goto exit_begin_add_column;
85787   pParse->pNewTable = pNew;
85788   pNew->nRef = 1;
85789   pNew->nCol = pTab->nCol;
85790   assert( pNew->nCol>0 );
85791   nAlloc = (((pNew->nCol-1)/8)*8)+8;
85792   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
85793   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
85794   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
85795   if( !pNew->aCol || !pNew->zName ){
85796     db->mallocFailed = 1;
85797     goto exit_begin_add_column;
85798   }
85799   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
85800   for(i=0; i<pNew->nCol; i++){
85801     Column *pCol = &pNew->aCol[i];
85802     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
85803     pCol->zColl = 0;
85804     pCol->zType = 0;
85805     pCol->pDflt = 0;
85806     pCol->zDflt = 0;
85807   }
85808   pNew->pSchema = db->aDb[iDb].pSchema;
85809   pNew->addColOffset = pTab->addColOffset;
85810   pNew->nRef = 1;
85811 
85812   /* Begin a transaction and increment the schema cookie.  */
85813   sqlite3BeginWriteOperation(pParse, 0, iDb);
85814   v = sqlite3GetVdbe(pParse);
85815   if( !v ) goto exit_begin_add_column;
85816   sqlite3ChangeCookie(pParse, iDb);
85817 
85818 exit_begin_add_column:
85819   sqlite3SrcListDelete(db, pSrc);
85820   return;
85821 }
85822 #endif  /* SQLITE_ALTER_TABLE */
85823 
85824 /************** End of alter.c ***********************************************/
85825 /************** Begin file analyze.c *****************************************/
85826 /*
85827 ** 2005-07-08
85828 **
85829 ** The author disclaims copyright to this source code.  In place of
85830 ** a legal notice, here is a blessing:
85831 **
85832 **    May you do good and not evil.
85833 **    May you find forgiveness for yourself and forgive others.
85834 **    May you share freely, never taking more than you give.
85835 **
85836 *************************************************************************
85837 ** This file contains code associated with the ANALYZE command.
85838 **
85839 ** The ANALYZE command gather statistics about the content of tables
85840 ** and indices.  These statistics are made available to the query planner
85841 ** to help it make better decisions about how to perform queries.
85842 **
85843 ** The following system tables are or have been supported:
85844 **
85845 **    CREATE TABLE sqlite_stat1(tbl, idx, stat);
85846 **    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
85847 **    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
85848 **    CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
85849 **
85850 ** Additional tables might be added in future releases of SQLite.
85851 ** The sqlite_stat2 table is not created or used unless the SQLite version
85852 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
85853 ** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
85854 ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
85855 ** created and used by SQLite versions 3.7.9 and later and with
85856 ** SQLITE_ENABLE_STAT3 defined.  The functionality of sqlite_stat3
85857 ** is a superset of sqlite_stat2.  The sqlite_stat4 is an enhanced
85858 ** version of sqlite_stat3 and is only available when compiled with
85859 ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later.  It is
85860 ** not possible to enable both STAT3 and STAT4 at the same time.  If they
85861 ** are both enabled, then STAT4 takes precedence.
85862 **
85863 ** For most applications, sqlite_stat1 provides all the statistics required
85864 ** for the query planner to make good choices.
85865 **
85866 ** Format of sqlite_stat1:
85867 **
85868 ** There is normally one row per index, with the index identified by the
85869 ** name in the idx column.  The tbl column is the name of the table to
85870 ** which the index belongs.  In each such row, the stat column will be
85871 ** a string consisting of a list of integers.  The first integer in this
85872 ** list is the number of rows in the index.  (This is the same as the
85873 ** number of rows in the table, except for partial indices.)  The second
85874 ** integer is the average number of rows in the index that have the same
85875 ** value in the first column of the index.  The third integer is the average
85876 ** number of rows in the index that have the same value for the first two
85877 ** columns.  The N-th integer (for N>1) is the average number of rows in
85878 ** the index which have the same value for the first N-1 columns.  For
85879 ** a K-column index, there will be K+1 integers in the stat column.  If
85880 ** the index is unique, then the last integer will be 1.
85881 **
85882 ** The list of integers in the stat column can optionally be followed
85883 ** by the keyword "unordered".  The "unordered" keyword, if it is present,
85884 ** must be separated from the last integer by a single space.  If the
85885 ** "unordered" keyword is present, then the query planner assumes that
85886 ** the index is unordered and will not use the index for a range query.
85887 **
85888 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
85889 ** column contains a single integer which is the (estimated) number of
85890 ** rows in the table identified by sqlite_stat1.tbl.
85891 **
85892 ** Format of sqlite_stat2:
85893 **
85894 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
85895 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
85896 ** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
85897 ** about the distribution of keys within an index.  The index is identified by
85898 ** the "idx" column and the "tbl" column is the name of the table to which
85899 ** the index belongs.  There are usually 10 rows in the sqlite_stat2
85900 ** table for each index.
85901 **
85902 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
85903 ** inclusive are samples of the left-most key value in the index taken at
85904 ** evenly spaced points along the index.  Let the number of samples be S
85905 ** (10 in the standard build) and let C be the number of rows in the index.
85906 ** Then the sampled rows are given by:
85907 **
85908 **     rownumber = (i*C*2 + C)/(S*2)
85909 **
85910 ** For i between 0 and S-1.  Conceptually, the index space is divided into
85911 ** S uniform buckets and the samples are the middle row from each bucket.
85912 **
85913 ** The format for sqlite_stat2 is recorded here for legacy reference.  This
85914 ** version of SQLite does not support sqlite_stat2.  It neither reads nor
85915 ** writes the sqlite_stat2 table.  This version of SQLite only supports
85916 ** sqlite_stat3.
85917 **
85918 ** Format for sqlite_stat3:
85919 **
85920 ** The sqlite_stat3 format is a subset of sqlite_stat4.  Hence, the
85921 ** sqlite_stat4 format will be described first.  Further information
85922 ** about sqlite_stat3 follows the sqlite_stat4 description.
85923 **
85924 ** Format for sqlite_stat4:
85925 **
85926 ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
85927 ** to aid the query planner in choosing good indices based on the values
85928 ** that indexed columns are compared against in the WHERE clauses of
85929 ** queries.
85930 **
85931 ** The sqlite_stat4 table contains multiple entries for each index.
85932 ** The idx column names the index and the tbl column is the table of the
85933 ** index.  If the idx and tbl columns are the same, then the sample is
85934 ** of the INTEGER PRIMARY KEY.  The sample column is a blob which is the
85935 ** binary encoding of a key from the index.  The nEq column is a
85936 ** list of integers.  The first integer is the approximate number
85937 ** of entries in the index whose left-most column exactly matches
85938 ** the left-most column of the sample.  The second integer in nEq
85939 ** is the approximate number of entries in the index where the
85940 ** first two columns match the first two columns of the sample.
85941 ** And so forth.  nLt is another list of integers that show the approximate
85942 ** number of entries that are strictly less than the sample.  The first
85943 ** integer in nLt contains the number of entries in the index where the
85944 ** left-most column is less than the left-most column of the sample.
85945 ** The K-th integer in the nLt entry is the number of index entries
85946 ** where the first K columns are less than the first K columns of the
85947 ** sample.  The nDLt column is like nLt except that it contains the
85948 ** number of distinct entries in the index that are less than the
85949 ** sample.
85950 **
85951 ** There can be an arbitrary number of sqlite_stat4 entries per index.
85952 ** The ANALYZE command will typically generate sqlite_stat4 tables
85953 ** that contain between 10 and 40 samples which are distributed across
85954 ** the key space, though not uniformly, and which include samples with
85955 ** large nEq values.
85956 **
85957 ** Format for sqlite_stat3 redux:
85958 **
85959 ** The sqlite_stat3 table is like sqlite_stat4 except that it only
85960 ** looks at the left-most column of the index.  The sqlite_stat3.sample
85961 ** column contains the actual value of the left-most column instead
85962 ** of a blob encoding of the complete index key as is found in
85963 ** sqlite_stat4.sample.  The nEq, nLt, and nDLt entries of sqlite_stat3
85964 ** all contain just a single integer which is the same as the first
85965 ** integer in the equivalent columns in sqlite_stat4.
85966 */
85967 #ifndef SQLITE_OMIT_ANALYZE
85968 
85969 #if defined(SQLITE_ENABLE_STAT4)
85970 # define IsStat4     1
85971 # define IsStat3     0
85972 #elif defined(SQLITE_ENABLE_STAT3)
85973 # define IsStat4     0
85974 # define IsStat3     1
85975 #else
85976 # define IsStat4     0
85977 # define IsStat3     0
85978 # undef SQLITE_STAT4_SAMPLES
85979 # define SQLITE_STAT4_SAMPLES 1
85980 #endif
85981 #define IsStat34    (IsStat3+IsStat4)  /* 1 for STAT3 or STAT4. 0 otherwise */
85982 
85983 /*
85984 ** This routine generates code that opens the sqlite_statN tables.
85985 ** The sqlite_stat1 table is always relevant.  sqlite_stat2 is now
85986 ** obsolete.  sqlite_stat3 and sqlite_stat4 are only opened when
85987 ** appropriate compile-time options are provided.
85988 **
85989 ** If the sqlite_statN tables do not previously exist, it is created.
85990 **
85991 ** Argument zWhere may be a pointer to a buffer containing a table name,
85992 ** or it may be a NULL pointer. If it is not NULL, then all entries in
85993 ** the sqlite_statN tables associated with the named table are deleted.
85994 ** If zWhere==0, then code is generated to delete all stat table entries.
85995 */
85996 static void openStatTable(
85997   Parse *pParse,          /* Parsing context */
85998   int iDb,                /* The database we are looking in */
85999   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
86000   const char *zWhere,     /* Delete entries for this table or index */
86001   const char *zWhereType  /* Either "tbl" or "idx" */
86002 ){
86003   static const struct {
86004     const char *zName;
86005     const char *zCols;
86006   } aTable[] = {
86007     { "sqlite_stat1", "tbl,idx,stat" },
86008 #if defined(SQLITE_ENABLE_STAT4)
86009     { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
86010     { "sqlite_stat3", 0 },
86011 #elif defined(SQLITE_ENABLE_STAT3)
86012     { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
86013     { "sqlite_stat4", 0 },
86014 #else
86015     { "sqlite_stat3", 0 },
86016     { "sqlite_stat4", 0 },
86017 #endif
86018   };
86019   int i;
86020   sqlite3 *db = pParse->db;
86021   Db *pDb;
86022   Vdbe *v = sqlite3GetVdbe(pParse);
86023   int aRoot[ArraySize(aTable)];
86024   u8 aCreateTbl[ArraySize(aTable)];
86025 
86026   if( v==0 ) return;
86027   assert( sqlite3BtreeHoldsAllMutexes(db) );
86028   assert( sqlite3VdbeDb(v)==db );
86029   pDb = &db->aDb[iDb];
86030 
86031   /* Create new statistic tables if they do not exist, or clear them
86032   ** if they do already exist.
86033   */
86034   for(i=0; i<ArraySize(aTable); i++){
86035     const char *zTab = aTable[i].zName;
86036     Table *pStat;
86037     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
86038       if( aTable[i].zCols ){
86039         /* The sqlite_statN table does not exist. Create it. Note that a
86040         ** side-effect of the CREATE TABLE statement is to leave the rootpage
86041         ** of the new table in register pParse->regRoot. This is important
86042         ** because the OpenWrite opcode below will be needing it. */
86043         sqlite3NestedParse(pParse,
86044             "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
86045         );
86046         aRoot[i] = pParse->regRoot;
86047         aCreateTbl[i] = OPFLAG_P2ISREG;
86048       }
86049     }else{
86050       /* The table already exists. If zWhere is not NULL, delete all entries
86051       ** associated with the table zWhere. If zWhere is NULL, delete the
86052       ** entire contents of the table. */
86053       aRoot[i] = pStat->tnum;
86054       aCreateTbl[i] = 0;
86055       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
86056       if( zWhere ){
86057         sqlite3NestedParse(pParse,
86058            "DELETE FROM %Q.%s WHERE %s=%Q",
86059            pDb->zName, zTab, zWhereType, zWhere
86060         );
86061       }else{
86062         /* The sqlite_stat[134] table already exists.  Delete all rows. */
86063         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
86064       }
86065     }
86066   }
86067 
86068   /* Open the sqlite_stat[134] tables for writing. */
86069   for(i=0; aTable[i].zCols; i++){
86070     assert( i<ArraySize(aTable) );
86071     sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
86072     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
86073     VdbeComment((v, aTable[i].zName));
86074   }
86075 }
86076 
86077 /*
86078 ** Recommended number of samples for sqlite_stat4
86079 */
86080 #ifndef SQLITE_STAT4_SAMPLES
86081 # define SQLITE_STAT4_SAMPLES 24
86082 #endif
86083 
86084 /*
86085 ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
86086 ** share an instance of the following structure to hold their state
86087 ** information.
86088 */
86089 typedef struct Stat4Accum Stat4Accum;
86090 typedef struct Stat4Sample Stat4Sample;
86091 struct Stat4Sample {
86092   tRowcnt *anEq;                  /* sqlite_stat4.nEq */
86093   tRowcnt *anDLt;                 /* sqlite_stat4.nDLt */
86094 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86095   tRowcnt *anLt;                  /* sqlite_stat4.nLt */
86096   union {
86097     i64 iRowid;                     /* Rowid in main table of the key */
86098     u8 *aRowid;                     /* Key for WITHOUT ROWID tables */
86099   } u;
86100   u32 nRowid;                     /* Sizeof aRowid[] */
86101   u8 isPSample;                   /* True if a periodic sample */
86102   int iCol;                       /* If !isPSample, the reason for inclusion */
86103   u32 iHash;                      /* Tiebreaker hash */
86104 #endif
86105 };
86106 struct Stat4Accum {
86107   tRowcnt nRow;             /* Number of rows in the entire table */
86108   tRowcnt nPSample;         /* How often to do a periodic sample */
86109   int nCol;                 /* Number of columns in index + pk/rowid */
86110   int nKeyCol;              /* Number of index columns w/o the pk/rowid */
86111   int mxSample;             /* Maximum number of samples to accumulate */
86112   Stat4Sample current;      /* Current row as a Stat4Sample */
86113   u32 iPrn;                 /* Pseudo-random number used for sampling */
86114   Stat4Sample *aBest;       /* Array of nCol best samples */
86115   int iMin;                 /* Index in a[] of entry with minimum score */
86116   int nSample;              /* Current number of samples */
86117   int iGet;                 /* Index of current sample accessed by stat_get() */
86118   Stat4Sample *a;           /* Array of mxSample Stat4Sample objects */
86119   sqlite3 *db;              /* Database connection, for malloc() */
86120 };
86121 
86122 /* Reclaim memory used by a Stat4Sample
86123 */
86124 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86125 static void sampleClear(sqlite3 *db, Stat4Sample *p){
86126   assert( db!=0 );
86127   if( p->nRowid ){
86128     sqlite3DbFree(db, p->u.aRowid);
86129     p->nRowid = 0;
86130   }
86131 }
86132 #endif
86133 
86134 /* Initialize the BLOB value of a ROWID
86135 */
86136 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86137 static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
86138   assert( db!=0 );
86139   if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
86140   p->u.aRowid = sqlite3DbMallocRaw(db, n);
86141   if( p->u.aRowid ){
86142     p->nRowid = n;
86143     memcpy(p->u.aRowid, pData, n);
86144   }else{
86145     p->nRowid = 0;
86146   }
86147 }
86148 #endif
86149 
86150 /* Initialize the INTEGER value of a ROWID.
86151 */
86152 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86153 static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
86154   assert( db!=0 );
86155   if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
86156   p->nRowid = 0;
86157   p->u.iRowid = iRowid;
86158 }
86159 #endif
86160 
86161 
86162 /*
86163 ** Copy the contents of object (*pFrom) into (*pTo).
86164 */
86165 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86166 static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
86167   pTo->isPSample = pFrom->isPSample;
86168   pTo->iCol = pFrom->iCol;
86169   pTo->iHash = pFrom->iHash;
86170   memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
86171   memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
86172   memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
86173   if( pFrom->nRowid ){
86174     sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
86175   }else{
86176     sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
86177   }
86178 }
86179 #endif
86180 
86181 /*
86182 ** Reclaim all memory of a Stat4Accum structure.
86183 */
86184 static void stat4Destructor(void *pOld){
86185   Stat4Accum *p = (Stat4Accum*)pOld;
86186 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86187   int i;
86188   for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
86189   for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
86190   sampleClear(p->db, &p->current);
86191 #endif
86192   sqlite3DbFree(p->db, p);
86193 }
86194 
86195 /*
86196 ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
86197 ** are:
86198 **     N:    The number of columns in the index including the rowid/pk (note 1)
86199 **     K:    The number of columns in the index excluding the rowid/pk.
86200 **     C:    The number of rows in the index (note 2)
86201 **
86202 ** Note 1:  In the special case of the covering index that implements a
86203 ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
86204 ** total number of columns in the table.
86205 **
86206 ** Note 2:  C is only used for STAT3 and STAT4.
86207 **
86208 ** For indexes on ordinary rowid tables, N==K+1.  But for indexes on
86209 ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
86210 ** PRIMARY KEY of the table.  The covering index that implements the
86211 ** original WITHOUT ROWID table as N==K as a special case.
86212 **
86213 ** This routine allocates the Stat4Accum object in heap memory. The return
86214 ** value is a pointer to the Stat4Accum object.  The datatype of the
86215 ** return value is BLOB, but it is really just a pointer to the Stat4Accum
86216 ** object.
86217 */
86218 static void statInit(
86219   sqlite3_context *context,
86220   int argc,
86221   sqlite3_value **argv
86222 ){
86223   Stat4Accum *p;
86224   int nCol;                       /* Number of columns in index being sampled */
86225   int nKeyCol;                    /* Number of key columns */
86226   int nColUp;                     /* nCol rounded up for alignment */
86227   int n;                          /* Bytes of space to allocate */
86228   sqlite3 *db;                    /* Database connection */
86229 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86230   int mxSample = SQLITE_STAT4_SAMPLES;
86231 #endif
86232 
86233   /* Decode the three function arguments */
86234   UNUSED_PARAMETER(argc);
86235   nCol = sqlite3_value_int(argv[0]);
86236   assert( nCol>0 );
86237   nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
86238   nKeyCol = sqlite3_value_int(argv[1]);
86239   assert( nKeyCol<=nCol );
86240   assert( nKeyCol>0 );
86241 
86242   /* Allocate the space required for the Stat4Accum object */
86243   n = sizeof(*p)
86244     + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anEq */
86245     + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anDLt */
86246 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86247     + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anLt */
86248     + sizeof(Stat4Sample)*(nCol+mxSample)     /* Stat4Accum.aBest[], a[] */
86249     + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
86250 #endif
86251   ;
86252   db = sqlite3_context_db_handle(context);
86253   p = sqlite3DbMallocZero(db, n);
86254   if( p==0 ){
86255     sqlite3_result_error_nomem(context);
86256     return;
86257   }
86258 
86259   p->db = db;
86260   p->nRow = 0;
86261   p->nCol = nCol;
86262   p->nKeyCol = nKeyCol;
86263   p->current.anDLt = (tRowcnt*)&p[1];
86264   p->current.anEq = &p->current.anDLt[nColUp];
86265 
86266 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86267   {
86268     u8 *pSpace;                     /* Allocated space not yet assigned */
86269     int i;                          /* Used to iterate through p->aSample[] */
86270 
86271     p->iGet = -1;
86272     p->mxSample = mxSample;
86273     p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
86274     p->current.anLt = &p->current.anEq[nColUp];
86275     p->iPrn = nCol*0x689e962d ^ sqlite3_value_int(argv[2])*0xd0944565;
86276 
86277     /* Set up the Stat4Accum.a[] and aBest[] arrays */
86278     p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
86279     p->aBest = &p->a[mxSample];
86280     pSpace = (u8*)(&p->a[mxSample+nCol]);
86281     for(i=0; i<(mxSample+nCol); i++){
86282       p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
86283       p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
86284       p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
86285     }
86286     assert( (pSpace - (u8*)p)==n );
86287 
86288     for(i=0; i<nCol; i++){
86289       p->aBest[i].iCol = i;
86290     }
86291   }
86292 #endif
86293 
86294   /* Return a pointer to the allocated object to the caller.  Note that
86295   ** only the pointer (the 2nd parameter) matters.  The size of the object
86296   ** (given by the 3rd parameter) is never used and can be any positive
86297   ** value. */
86298   sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
86299 }
86300 static const FuncDef statInitFuncdef = {
86301   2+IsStat34,      /* nArg */
86302   SQLITE_UTF8,     /* funcFlags */
86303   0,               /* pUserData */
86304   0,               /* pNext */
86305   statInit,        /* xFunc */
86306   0,               /* xStep */
86307   0,               /* xFinalize */
86308   "stat_init",     /* zName */
86309   0,               /* pHash */
86310   0                /* pDestructor */
86311 };
86312 
86313 #ifdef SQLITE_ENABLE_STAT4
86314 /*
86315 ** pNew and pOld are both candidate non-periodic samples selected for
86316 ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
86317 ** considering only any trailing columns and the sample hash value, this
86318 ** function returns true if sample pNew is to be preferred over pOld.
86319 ** In other words, if we assume that the cardinalities of the selected
86320 ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
86321 **
86322 ** This function assumes that for each argument sample, the contents of
86323 ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
86324 */
86325 static int sampleIsBetterPost(
86326   Stat4Accum *pAccum,
86327   Stat4Sample *pNew,
86328   Stat4Sample *pOld
86329 ){
86330   int nCol = pAccum->nCol;
86331   int i;
86332   assert( pNew->iCol==pOld->iCol );
86333   for(i=pNew->iCol+1; i<nCol; i++){
86334     if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
86335     if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
86336   }
86337   if( pNew->iHash>pOld->iHash ) return 1;
86338   return 0;
86339 }
86340 #endif
86341 
86342 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86343 /*
86344 ** Return true if pNew is to be preferred over pOld.
86345 **
86346 ** This function assumes that for each argument sample, the contents of
86347 ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
86348 */
86349 static int sampleIsBetter(
86350   Stat4Accum *pAccum,
86351   Stat4Sample *pNew,
86352   Stat4Sample *pOld
86353 ){
86354   tRowcnt nEqNew = pNew->anEq[pNew->iCol];
86355   tRowcnt nEqOld = pOld->anEq[pOld->iCol];
86356 
86357   assert( pOld->isPSample==0 && pNew->isPSample==0 );
86358   assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
86359 
86360   if( (nEqNew>nEqOld) ) return 1;
86361 #ifdef SQLITE_ENABLE_STAT4
86362   if( nEqNew==nEqOld ){
86363     if( pNew->iCol<pOld->iCol ) return 1;
86364     return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
86365   }
86366   return 0;
86367 #else
86368   return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
86369 #endif
86370 }
86371 
86372 /*
86373 ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
86374 ** remove the least desirable sample from p->a[] to make room.
86375 */
86376 static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
86377   Stat4Sample *pSample = 0;
86378   int i;
86379 
86380   assert( IsStat4 || nEqZero==0 );
86381 
86382 #ifdef SQLITE_ENABLE_STAT4
86383   if( pNew->isPSample==0 ){
86384     Stat4Sample *pUpgrade = 0;
86385     assert( pNew->anEq[pNew->iCol]>0 );
86386 
86387     /* This sample is being added because the prefix that ends in column
86388     ** iCol occurs many times in the table. However, if we have already
86389     ** added a sample that shares this prefix, there is no need to add
86390     ** this one. Instead, upgrade the priority of the highest priority
86391     ** existing sample that shares this prefix.  */
86392     for(i=p->nSample-1; i>=0; i--){
86393       Stat4Sample *pOld = &p->a[i];
86394       if( pOld->anEq[pNew->iCol]==0 ){
86395         if( pOld->isPSample ) return;
86396         assert( pOld->iCol>pNew->iCol );
86397         assert( sampleIsBetter(p, pNew, pOld) );
86398         if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
86399           pUpgrade = pOld;
86400         }
86401       }
86402     }
86403     if( pUpgrade ){
86404       pUpgrade->iCol = pNew->iCol;
86405       pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
86406       goto find_new_min;
86407     }
86408   }
86409 #endif
86410 
86411   /* If necessary, remove sample iMin to make room for the new sample. */
86412   if( p->nSample>=p->mxSample ){
86413     Stat4Sample *pMin = &p->a[p->iMin];
86414     tRowcnt *anEq = pMin->anEq;
86415     tRowcnt *anLt = pMin->anLt;
86416     tRowcnt *anDLt = pMin->anDLt;
86417     sampleClear(p->db, pMin);
86418     memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
86419     pSample = &p->a[p->nSample-1];
86420     pSample->nRowid = 0;
86421     pSample->anEq = anEq;
86422     pSample->anDLt = anDLt;
86423     pSample->anLt = anLt;
86424     p->nSample = p->mxSample-1;
86425   }
86426 
86427   /* The "rows less-than" for the rowid column must be greater than that
86428   ** for the last sample in the p->a[] array. Otherwise, the samples would
86429   ** be out of order. */
86430 #ifdef SQLITE_ENABLE_STAT4
86431   assert( p->nSample==0
86432        || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
86433 #endif
86434 
86435   /* Insert the new sample */
86436   pSample = &p->a[p->nSample];
86437   sampleCopy(p, pSample, pNew);
86438   p->nSample++;
86439 
86440   /* Zero the first nEqZero entries in the anEq[] array. */
86441   memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
86442 
86443 #ifdef SQLITE_ENABLE_STAT4
86444  find_new_min:
86445 #endif
86446   if( p->nSample>=p->mxSample ){
86447     int iMin = -1;
86448     for(i=0; i<p->mxSample; i++){
86449       if( p->a[i].isPSample ) continue;
86450       if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
86451         iMin = i;
86452       }
86453     }
86454     assert( iMin>=0 );
86455     p->iMin = iMin;
86456   }
86457 }
86458 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
86459 
86460 /*
86461 ** Field iChng of the index being scanned has changed. So at this point
86462 ** p->current contains a sample that reflects the previous row of the
86463 ** index. The value of anEq[iChng] and subsequent anEq[] elements are
86464 ** correct at this point.
86465 */
86466 static void samplePushPrevious(Stat4Accum *p, int iChng){
86467 #ifdef SQLITE_ENABLE_STAT4
86468   int i;
86469 
86470   /* Check if any samples from the aBest[] array should be pushed
86471   ** into IndexSample.a[] at this point.  */
86472   for(i=(p->nCol-2); i>=iChng; i--){
86473     Stat4Sample *pBest = &p->aBest[i];
86474     pBest->anEq[i] = p->current.anEq[i];
86475     if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
86476       sampleInsert(p, pBest, i);
86477     }
86478   }
86479 
86480   /* Update the anEq[] fields of any samples already collected. */
86481   for(i=p->nSample-1; i>=0; i--){
86482     int j;
86483     for(j=iChng; j<p->nCol; j++){
86484       if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
86485     }
86486   }
86487 #endif
86488 
86489 #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
86490   if( iChng==0 ){
86491     tRowcnt nLt = p->current.anLt[0];
86492     tRowcnt nEq = p->current.anEq[0];
86493 
86494     /* Check if this is to be a periodic sample. If so, add it. */
86495     if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
86496       p->current.isPSample = 1;
86497       sampleInsert(p, &p->current, 0);
86498       p->current.isPSample = 0;
86499     }else
86500 
86501     /* Or if it is a non-periodic sample. Add it in this case too. */
86502     if( p->nSample<p->mxSample
86503      || sampleIsBetter(p, &p->current, &p->a[p->iMin])
86504     ){
86505       sampleInsert(p, &p->current, 0);
86506     }
86507   }
86508 #endif
86509 
86510 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
86511   UNUSED_PARAMETER( p );
86512   UNUSED_PARAMETER( iChng );
86513 #endif
86514 }
86515 
86516 /*
86517 ** Implementation of the stat_push SQL function:  stat_push(P,C,R)
86518 ** Arguments:
86519 **
86520 **    P     Pointer to the Stat4Accum object created by stat_init()
86521 **    C     Index of left-most column to differ from previous row
86522 **    R     Rowid for the current row.  Might be a key record for
86523 **          WITHOUT ROWID tables.
86524 **
86525 ** This SQL function always returns NULL.  It's purpose it to accumulate
86526 ** statistical data and/or samples in the Stat4Accum object about the
86527 ** index being analyzed.  The stat_get() SQL function will later be used to
86528 ** extract relevant information for constructing the sqlite_statN tables.
86529 **
86530 ** The R parameter is only used for STAT3 and STAT4
86531 */
86532 static void statPush(
86533   sqlite3_context *context,
86534   int argc,
86535   sqlite3_value **argv
86536 ){
86537   int i;
86538 
86539   /* The three function arguments */
86540   Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
86541   int iChng = sqlite3_value_int(argv[1]);
86542 
86543   UNUSED_PARAMETER( argc );
86544   UNUSED_PARAMETER( context );
86545   assert( p->nCol>0 );
86546   assert( iChng<p->nCol );
86547 
86548   if( p->nRow==0 ){
86549     /* This is the first call to this function. Do initialization. */
86550     for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
86551   }else{
86552     /* Second and subsequent calls get processed here */
86553     samplePushPrevious(p, iChng);
86554 
86555     /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
86556     ** to the current row of the index. */
86557     for(i=0; i<iChng; i++){
86558       p->current.anEq[i]++;
86559     }
86560     for(i=iChng; i<p->nCol; i++){
86561       p->current.anDLt[i]++;
86562 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86563       p->current.anLt[i] += p->current.anEq[i];
86564 #endif
86565       p->current.anEq[i] = 1;
86566     }
86567   }
86568   p->nRow++;
86569 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86570   if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
86571     sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
86572   }else{
86573     sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
86574                                        sqlite3_value_blob(argv[2]));
86575   }
86576   p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
86577 #endif
86578 
86579 #ifdef SQLITE_ENABLE_STAT4
86580   {
86581     tRowcnt nLt = p->current.anLt[p->nCol-1];
86582 
86583     /* Check if this is to be a periodic sample. If so, add it. */
86584     if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
86585       p->current.isPSample = 1;
86586       p->current.iCol = 0;
86587       sampleInsert(p, &p->current, p->nCol-1);
86588       p->current.isPSample = 0;
86589     }
86590 
86591     /* Update the aBest[] array. */
86592     for(i=0; i<(p->nCol-1); i++){
86593       p->current.iCol = i;
86594       if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
86595         sampleCopy(p, &p->aBest[i], &p->current);
86596       }
86597     }
86598   }
86599 #endif
86600 }
86601 static const FuncDef statPushFuncdef = {
86602   2+IsStat34,      /* nArg */
86603   SQLITE_UTF8,     /* funcFlags */
86604   0,               /* pUserData */
86605   0,               /* pNext */
86606   statPush,        /* xFunc */
86607   0,               /* xStep */
86608   0,               /* xFinalize */
86609   "stat_push",     /* zName */
86610   0,               /* pHash */
86611   0                /* pDestructor */
86612 };
86613 
86614 #define STAT_GET_STAT1 0          /* "stat" column of stat1 table */
86615 #define STAT_GET_ROWID 1          /* "rowid" column of stat[34] entry */
86616 #define STAT_GET_NEQ   2          /* "neq" column of stat[34] entry */
86617 #define STAT_GET_NLT   3          /* "nlt" column of stat[34] entry */
86618 #define STAT_GET_NDLT  4          /* "ndlt" column of stat[34] entry */
86619 
86620 /*
86621 ** Implementation of the stat_get(P,J) SQL function.  This routine is
86622 ** used to query statistical information that has been gathered into
86623 ** the Stat4Accum object by prior calls to stat_push().  The P parameter
86624 ** has type BLOB but it is really just a pointer to the Stat4Accum object.
86625 ** The content to returned is determined by the parameter J
86626 ** which is one of the STAT_GET_xxxx values defined above.
86627 **
86628 ** If neither STAT3 nor STAT4 are enabled, then J is always
86629 ** STAT_GET_STAT1 and is hence omitted and this routine becomes
86630 ** a one-parameter function, stat_get(P), that always returns the
86631 ** stat1 table entry information.
86632 */
86633 static void statGet(
86634   sqlite3_context *context,
86635   int argc,
86636   sqlite3_value **argv
86637 ){
86638   Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
86639 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86640   /* STAT3 and STAT4 have a parameter on this routine. */
86641   int eCall = sqlite3_value_int(argv[1]);
86642   assert( argc==2 );
86643   assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
86644        || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
86645        || eCall==STAT_GET_NDLT
86646   );
86647   if( eCall==STAT_GET_STAT1 )
86648 #else
86649   assert( argc==1 );
86650 #endif
86651   {
86652     /* Return the value to store in the "stat" column of the sqlite_stat1
86653     ** table for this index.
86654     **
86655     ** The value is a string composed of a list of integers describing
86656     ** the index. The first integer in the list is the total number of
86657     ** entries in the index. There is one additional integer in the list
86658     ** for each indexed column. This additional integer is an estimate of
86659     ** the number of rows matched by a stabbing query on the index using
86660     ** a key with the corresponding number of fields. In other words,
86661     ** if the index is on columns (a,b) and the sqlite_stat1 value is
86662     ** "100 10 2", then SQLite estimates that:
86663     **
86664     **   * the index contains 100 rows,
86665     **   * "WHERE a=?" matches 10 rows, and
86666     **   * "WHERE a=? AND b=?" matches 2 rows.
86667     **
86668     ** If D is the count of distinct values and K is the total number of
86669     ** rows, then each estimate is computed as:
86670     **
86671     **        I = (K+D-1)/D
86672     */
86673     char *z;
86674     int i;
86675 
86676     char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
86677     if( zRet==0 ){
86678       sqlite3_result_error_nomem(context);
86679       return;
86680     }
86681 
86682     sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
86683     z = zRet + sqlite3Strlen30(zRet);
86684     for(i=0; i<p->nKeyCol; i++){
86685       u64 nDistinct = p->current.anDLt[i] + 1;
86686       u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
86687       sqlite3_snprintf(24, z, " %llu", iVal);
86688       z += sqlite3Strlen30(z);
86689       assert( p->current.anEq[i] );
86690     }
86691     assert( z[0]=='\0' && z>zRet );
86692 
86693     sqlite3_result_text(context, zRet, -1, sqlite3_free);
86694   }
86695 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86696   else if( eCall==STAT_GET_ROWID ){
86697     if( p->iGet<0 ){
86698       samplePushPrevious(p, 0);
86699       p->iGet = 0;
86700     }
86701     if( p->iGet<p->nSample ){
86702       Stat4Sample *pS = p->a + p->iGet;
86703       if( pS->nRowid==0 ){
86704         sqlite3_result_int64(context, pS->u.iRowid);
86705       }else{
86706         sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
86707                             SQLITE_TRANSIENT);
86708       }
86709     }
86710   }else{
86711     tRowcnt *aCnt = 0;
86712 
86713     assert( p->iGet<p->nSample );
86714     switch( eCall ){
86715       case STAT_GET_NEQ:  aCnt = p->a[p->iGet].anEq; break;
86716       case STAT_GET_NLT:  aCnt = p->a[p->iGet].anLt; break;
86717       default: {
86718         aCnt = p->a[p->iGet].anDLt;
86719         p->iGet++;
86720         break;
86721       }
86722     }
86723 
86724     if( IsStat3 ){
86725       sqlite3_result_int64(context, (i64)aCnt[0]);
86726     }else{
86727       char *zRet = sqlite3MallocZero(p->nCol * 25);
86728       if( zRet==0 ){
86729         sqlite3_result_error_nomem(context);
86730       }else{
86731         int i;
86732         char *z = zRet;
86733         for(i=0; i<p->nCol; i++){
86734           sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
86735           z += sqlite3Strlen30(z);
86736         }
86737         assert( z[0]=='\0' && z>zRet );
86738         z[-1] = '\0';
86739         sqlite3_result_text(context, zRet, -1, sqlite3_free);
86740       }
86741     }
86742   }
86743 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
86744 #ifndef SQLITE_DEBUG
86745   UNUSED_PARAMETER( argc );
86746 #endif
86747 }
86748 static const FuncDef statGetFuncdef = {
86749   1+IsStat34,      /* nArg */
86750   SQLITE_UTF8,     /* funcFlags */
86751   0,               /* pUserData */
86752   0,               /* pNext */
86753   statGet,         /* xFunc */
86754   0,               /* xStep */
86755   0,               /* xFinalize */
86756   "stat_get",      /* zName */
86757   0,               /* pHash */
86758   0                /* pDestructor */
86759 };
86760 
86761 static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
86762   assert( regOut!=regStat4 && regOut!=regStat4+1 );
86763 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86764   sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
86765 #elif SQLITE_DEBUG
86766   assert( iParam==STAT_GET_STAT1 );
86767 #else
86768   UNUSED_PARAMETER( iParam );
86769 #endif
86770   sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut);
86771   sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
86772   sqlite3VdbeChangeP5(v, 1 + IsStat34);
86773 }
86774 
86775 /*
86776 ** Generate code to do an analysis of all indices associated with
86777 ** a single table.
86778 */
86779 static void analyzeOneTable(
86780   Parse *pParse,   /* Parser context */
86781   Table *pTab,     /* Table whose indices are to be analyzed */
86782   Index *pOnlyIdx, /* If not NULL, only analyze this one index */
86783   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
86784   int iMem,        /* Available memory locations begin here */
86785   int iTab         /* Next available cursor */
86786 ){
86787   sqlite3 *db = pParse->db;    /* Database handle */
86788   Index *pIdx;                 /* An index to being analyzed */
86789   int iIdxCur;                 /* Cursor open on index being analyzed */
86790   int iTabCur;                 /* Table cursor */
86791   Vdbe *v;                     /* The virtual machine being built up */
86792   int i;                       /* Loop counter */
86793   int jZeroRows = -1;          /* Jump from here if number of rows is zero */
86794   int iDb;                     /* Index of database containing pTab */
86795   u8 needTableCnt = 1;         /* True to count the table */
86796   int regNewRowid = iMem++;    /* Rowid for the inserted record */
86797   int regStat4 = iMem++;       /* Register to hold Stat4Accum object */
86798   int regChng = iMem++;        /* Index of changed index field */
86799 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86800   int regRowid = iMem++;       /* Rowid argument passed to stat_push() */
86801 #endif
86802   int regTemp = iMem++;        /* Temporary use register */
86803   int regTabname = iMem++;     /* Register containing table name */
86804   int regIdxname = iMem++;     /* Register containing index name */
86805   int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */
86806   int regPrev = iMem;          /* MUST BE LAST (see below) */
86807 
86808   pParse->nMem = MAX(pParse->nMem, iMem);
86809   v = sqlite3GetVdbe(pParse);
86810   if( v==0 || NEVER(pTab==0) ){
86811     return;
86812   }
86813   if( pTab->tnum==0 ){
86814     /* Do not gather statistics on views or virtual tables */
86815     return;
86816   }
86817   if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
86818     /* Do not gather statistics on system tables */
86819     return;
86820   }
86821   assert( sqlite3BtreeHoldsAllMutexes(db) );
86822   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
86823   assert( iDb>=0 );
86824   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
86825 #ifndef SQLITE_OMIT_AUTHORIZATION
86826   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
86827       db->aDb[iDb].zName ) ){
86828     return;
86829   }
86830 #endif
86831 
86832   /* Establish a read-lock on the table at the shared-cache level.
86833   ** Open a read-only cursor on the table. Also allocate a cursor number
86834   ** to use for scanning indexes (iIdxCur). No index cursor is opened at
86835   ** this time though.  */
86836   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
86837   iTabCur = iTab++;
86838   iIdxCur = iTab++;
86839   pParse->nTab = MAX(pParse->nTab, iTab);
86840   sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
86841   sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
86842 
86843   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
86844     int nCol;                     /* Number of columns in pIdx. "N" */
86845     int addrRewind;               /* Address of "OP_Rewind iIdxCur" */
86846     int addrNextRow;              /* Address of "next_row:" */
86847     const char *zIdxName;         /* Name of the index */
86848     int nColTest;                 /* Number of columns to test for changes */
86849 
86850     if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
86851     if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
86852     if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
86853       nCol = pIdx->nKeyCol;
86854       zIdxName = pTab->zName;
86855       nColTest = nCol - 1;
86856     }else{
86857       nCol = pIdx->nColumn;
86858       zIdxName = pIdx->zName;
86859       nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
86860     }
86861 
86862     /* Populate the register containing the index name. */
86863     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, zIdxName, 0);
86864     VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
86865 
86866     /*
86867     ** Pseudo-code for loop that calls stat_push():
86868     **
86869     **   Rewind csr
86870     **   if eof(csr) goto end_of_scan;
86871     **   regChng = 0
86872     **   goto chng_addr_0;
86873     **
86874     **  next_row:
86875     **   regChng = 0
86876     **   if( idx(0) != regPrev(0) ) goto chng_addr_0
86877     **   regChng = 1
86878     **   if( idx(1) != regPrev(1) ) goto chng_addr_1
86879     **   ...
86880     **   regChng = N
86881     **   goto chng_addr_N
86882     **
86883     **  chng_addr_0:
86884     **   regPrev(0) = idx(0)
86885     **  chng_addr_1:
86886     **   regPrev(1) = idx(1)
86887     **  ...
86888     **
86889     **  endDistinctTest:
86890     **   regRowid = idx(rowid)
86891     **   stat_push(P, regChng, regRowid)
86892     **   Next csr
86893     **   if !eof(csr) goto next_row;
86894     **
86895     **  end_of_scan:
86896     */
86897 
86898     /* Make sure there are enough memory cells allocated to accommodate
86899     ** the regPrev array and a trailing rowid (the rowid slot is required
86900     ** when building a record to insert into the sample column of
86901     ** the sqlite_stat4 table.  */
86902     pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
86903 
86904     /* Open a read-only cursor on the index being analyzed. */
86905     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
86906     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
86907     sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
86908     VdbeComment((v, "%s", pIdx->zName));
86909 
86910     /* Invoke the stat_init() function. The arguments are:
86911     **
86912     **    (1) the number of columns in the index including the rowid
86913     **        (or for a WITHOUT ROWID table, the number of PK columns),
86914     **    (2) the number of columns in the key without the rowid/pk
86915     **    (3) the number of rows in the index,
86916     **
86917     **
86918     ** The third argument is only used for STAT3 and STAT4
86919     */
86920 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
86921     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
86922 #endif
86923     sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
86924     sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
86925     sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4);
86926     sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
86927     sqlite3VdbeChangeP5(v, 2+IsStat34);
86928 
86929     /* Implementation of the following:
86930     **
86931     **   Rewind csr
86932     **   if eof(csr) goto end_of_scan;
86933     **   regChng = 0
86934     **   goto next_push_0;
86935     **
86936     */
86937     addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
86938     VdbeCoverage(v);
86939     sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
86940     addrNextRow = sqlite3VdbeCurrentAddr(v);
86941 
86942     if( nColTest>0 ){
86943       int endDistinctTest = sqlite3VdbeMakeLabel(v);
86944       int *aGotoChng;               /* Array of jump instruction addresses */
86945       aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*nColTest);
86946       if( aGotoChng==0 ) continue;
86947 
86948       /*
86949       **  next_row:
86950       **   regChng = 0
86951       **   if( idx(0) != regPrev(0) ) goto chng_addr_0
86952       **   regChng = 1
86953       **   if( idx(1) != regPrev(1) ) goto chng_addr_1
86954       **   ...
86955       **   regChng = N
86956       **   goto endDistinctTest
86957       */
86958       sqlite3VdbeAddOp0(v, OP_Goto);
86959       addrNextRow = sqlite3VdbeCurrentAddr(v);
86960       if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
86961         /* For a single-column UNIQUE index, once we have found a non-NULL
86962         ** row, we know that all the rest will be distinct, so skip
86963         ** subsequent distinctness tests. */
86964         sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
86965         VdbeCoverage(v);
86966       }
86967       for(i=0; i<nColTest; i++){
86968         char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
86969         sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
86970         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
86971         aGotoChng[i] =
86972         sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
86973         sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
86974         VdbeCoverage(v);
86975       }
86976       sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
86977       sqlite3VdbeAddOp2(v, OP_Goto, 0, endDistinctTest);
86978 
86979 
86980       /*
86981       **  chng_addr_0:
86982       **   regPrev(0) = idx(0)
86983       **  chng_addr_1:
86984       **   regPrev(1) = idx(1)
86985       **  ...
86986       */
86987       sqlite3VdbeJumpHere(v, addrNextRow-1);
86988       for(i=0; i<nColTest; i++){
86989         sqlite3VdbeJumpHere(v, aGotoChng[i]);
86990         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
86991       }
86992       sqlite3VdbeResolveLabel(v, endDistinctTest);
86993       sqlite3DbFree(db, aGotoChng);
86994     }
86995 
86996     /*
86997     **  chng_addr_N:
86998     **   regRowid = idx(rowid)            // STAT34 only
86999     **   stat_push(P, regChng, regRowid)  // 3rd parameter STAT34 only
87000     **   Next csr
87001     **   if !eof(csr) goto next_row;
87002     */
87003 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87004     assert( regRowid==(regStat4+2) );
87005     if( HasRowid(pTab) ){
87006       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
87007     }else{
87008       Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
87009       int j, k, regKey;
87010       regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
87011       for(j=0; j<pPk->nKeyCol; j++){
87012         k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
87013         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
87014         VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
87015       }
87016       sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
87017       sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
87018     }
87019 #endif
87020     assert( regChng==(regStat4+1) );
87021     sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp);
87022     sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
87023     sqlite3VdbeChangeP5(v, 2+IsStat34);
87024     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
87025 
87026     /* Add the entry to the stat1 table. */
87027     callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
87028     assert( "BBB"[0]==SQLITE_AFF_TEXT );
87029     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
87030     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
87031     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
87032     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
87033 
87034     /* Add the entries to the stat3 or stat4 table. */
87035 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87036     {
87037       int regEq = regStat1;
87038       int regLt = regStat1+1;
87039       int regDLt = regStat1+2;
87040       int regSample = regStat1+3;
87041       int regCol = regStat1+4;
87042       int regSampleRowid = regCol + nCol;
87043       int addrNext;
87044       int addrIsNull;
87045       u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
87046 
87047       pParse->nMem = MAX(pParse->nMem, regCol+nCol);
87048 
87049       addrNext = sqlite3VdbeCurrentAddr(v);
87050       callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
87051       addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
87052       VdbeCoverage(v);
87053       callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
87054       callStatGet(v, regStat4, STAT_GET_NLT, regLt);
87055       callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
87056       sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
87057       /* We know that the regSampleRowid row exists because it was read by
87058       ** the previous loop.  Thus the not-found jump of seekOp will never
87059       ** be taken */
87060       VdbeCoverageNeverTaken(v);
87061 #ifdef SQLITE_ENABLE_STAT3
87062       sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
87063                                       pIdx->aiColumn[0], regSample);
87064 #else
87065       for(i=0; i<nCol; i++){
87066         i16 iCol = pIdx->aiColumn[i];
87067         sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
87068       }
87069       sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
87070 #endif
87071       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
87072       sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
87073       sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
87074       sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
87075       sqlite3VdbeJumpHere(v, addrIsNull);
87076     }
87077 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
87078 
87079     /* End of analysis */
87080     sqlite3VdbeJumpHere(v, addrRewind);
87081   }
87082 
87083 
87084   /* Create a single sqlite_stat1 entry containing NULL as the index
87085   ** name and the row count as the content.
87086   */
87087   if( pOnlyIdx==0 && needTableCnt ){
87088     VdbeComment((v, "%s", pTab->zName));
87089     sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
87090     jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
87091     sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
87092     assert( "BBB"[0]==SQLITE_AFF_TEXT );
87093     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
87094     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
87095     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
87096     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
87097     sqlite3VdbeJumpHere(v, jZeroRows);
87098   }
87099 }
87100 
87101 
87102 /*
87103 ** Generate code that will cause the most recent index analysis to
87104 ** be loaded into internal hash tables where is can be used.
87105 */
87106 static void loadAnalysis(Parse *pParse, int iDb){
87107   Vdbe *v = sqlite3GetVdbe(pParse);
87108   if( v ){
87109     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
87110   }
87111 }
87112 
87113 /*
87114 ** Generate code that will do an analysis of an entire database
87115 */
87116 static void analyzeDatabase(Parse *pParse, int iDb){
87117   sqlite3 *db = pParse->db;
87118   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
87119   HashElem *k;
87120   int iStatCur;
87121   int iMem;
87122   int iTab;
87123 
87124   sqlite3BeginWriteOperation(pParse, 0, iDb);
87125   iStatCur = pParse->nTab;
87126   pParse->nTab += 3;
87127   openStatTable(pParse, iDb, iStatCur, 0, 0);
87128   iMem = pParse->nMem+1;
87129   iTab = pParse->nTab;
87130   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
87131   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
87132     Table *pTab = (Table*)sqliteHashData(k);
87133     analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
87134   }
87135   loadAnalysis(pParse, iDb);
87136 }
87137 
87138 /*
87139 ** Generate code that will do an analysis of a single table in
87140 ** a database.  If pOnlyIdx is not NULL then it is a single index
87141 ** in pTab that should be analyzed.
87142 */
87143 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
87144   int iDb;
87145   int iStatCur;
87146 
87147   assert( pTab!=0 );
87148   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
87149   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
87150   sqlite3BeginWriteOperation(pParse, 0, iDb);
87151   iStatCur = pParse->nTab;
87152   pParse->nTab += 3;
87153   if( pOnlyIdx ){
87154     openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
87155   }else{
87156     openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
87157   }
87158   analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
87159   loadAnalysis(pParse, iDb);
87160 }
87161 
87162 /*
87163 ** Generate code for the ANALYZE command.  The parser calls this routine
87164 ** when it recognizes an ANALYZE command.
87165 **
87166 **        ANALYZE                            -- 1
87167 **        ANALYZE  <database>                -- 2
87168 **        ANALYZE  ?<database>.?<tablename>  -- 3
87169 **
87170 ** Form 1 causes all indices in all attached databases to be analyzed.
87171 ** Form 2 analyzes all indices the single database named.
87172 ** Form 3 analyzes all indices associated with the named table.
87173 */
87174 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
87175   sqlite3 *db = pParse->db;
87176   int iDb;
87177   int i;
87178   char *z, *zDb;
87179   Table *pTab;
87180   Index *pIdx;
87181   Token *pTableName;
87182   Vdbe *v;
87183 
87184   /* Read the database schema. If an error occurs, leave an error message
87185   ** and code in pParse and return NULL. */
87186   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
87187   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
87188     return;
87189   }
87190 
87191   assert( pName2!=0 || pName1==0 );
87192   if( pName1==0 ){
87193     /* Form 1:  Analyze everything */
87194     for(i=0; i<db->nDb; i++){
87195       if( i==1 ) continue;  /* Do not analyze the TEMP database */
87196       analyzeDatabase(pParse, i);
87197     }
87198   }else if( pName2->n==0 ){
87199     /* Form 2:  Analyze the database or table named */
87200     iDb = sqlite3FindDb(db, pName1);
87201     if( iDb>=0 ){
87202       analyzeDatabase(pParse, iDb);
87203     }else{
87204       z = sqlite3NameFromToken(db, pName1);
87205       if( z ){
87206         if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
87207           analyzeTable(pParse, pIdx->pTable, pIdx);
87208         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
87209           analyzeTable(pParse, pTab, 0);
87210         }
87211         sqlite3DbFree(db, z);
87212       }
87213     }
87214   }else{
87215     /* Form 3: Analyze the fully qualified table name */
87216     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
87217     if( iDb>=0 ){
87218       zDb = db->aDb[iDb].zName;
87219       z = sqlite3NameFromToken(db, pTableName);
87220       if( z ){
87221         if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
87222           analyzeTable(pParse, pIdx->pTable, pIdx);
87223         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
87224           analyzeTable(pParse, pTab, 0);
87225         }
87226         sqlite3DbFree(db, z);
87227       }
87228     }
87229   }
87230   v = sqlite3GetVdbe(pParse);
87231   if( v ) sqlite3VdbeAddOp0(v, OP_Expire);
87232 }
87233 
87234 /*
87235 ** Used to pass information from the analyzer reader through to the
87236 ** callback routine.
87237 */
87238 typedef struct analysisInfo analysisInfo;
87239 struct analysisInfo {
87240   sqlite3 *db;
87241   const char *zDatabase;
87242 };
87243 
87244 /*
87245 ** The first argument points to a nul-terminated string containing a
87246 ** list of space separated integers. Read the first nOut of these into
87247 ** the array aOut[].
87248 */
87249 static void decodeIntArray(
87250   char *zIntArray,       /* String containing int array to decode */
87251   int nOut,              /* Number of slots in aOut[] */
87252   tRowcnt *aOut,         /* Store integers here */
87253   LogEst *aLog,          /* Or, if aOut==0, here */
87254   Index *pIndex          /* Handle extra flags for this index, if not NULL */
87255 ){
87256   char *z = zIntArray;
87257   int c;
87258   int i;
87259   tRowcnt v;
87260 
87261 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87262   if( z==0 ) z = "";
87263 #else
87264   assert( z!=0 );
87265 #endif
87266   for(i=0; *z && i<nOut; i++){
87267     v = 0;
87268     while( (c=z[0])>='0' && c<='9' ){
87269       v = v*10 + c - '0';
87270       z++;
87271     }
87272 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87273     if( aOut ) aOut[i] = v;
87274     if( aLog ) aLog[i] = sqlite3LogEst(v);
87275 #else
87276     assert( aOut==0 );
87277     UNUSED_PARAMETER(aOut);
87278     assert( aLog!=0 );
87279     aLog[i] = sqlite3LogEst(v);
87280 #endif
87281     if( *z==' ' ) z++;
87282   }
87283 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
87284   assert( pIndex!=0 );
87285 #else
87286   if( pIndex )
87287 #endif
87288   while( z[0] ){
87289     if( sqlite3_strglob("unordered*", z)==0 ){
87290       pIndex->bUnordered = 1;
87291     }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
87292       pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
87293     }
87294 #ifdef SQLITE_ENABLE_COSTMULT
87295     else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
87296       pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
87297     }
87298 #endif
87299     while( z[0]!=0 && z[0]!=' ' ) z++;
87300     while( z[0]==' ' ) z++;
87301   }
87302 }
87303 
87304 /*
87305 ** This callback is invoked once for each index when reading the
87306 ** sqlite_stat1 table.
87307 **
87308 **     argv[0] = name of the table
87309 **     argv[1] = name of the index (might be NULL)
87310 **     argv[2] = results of analysis - on integer for each column
87311 **
87312 ** Entries for which argv[1]==NULL simply record the number of rows in
87313 ** the table.
87314 */
87315 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
87316   analysisInfo *pInfo = (analysisInfo*)pData;
87317   Index *pIndex;
87318   Table *pTable;
87319   const char *z;
87320 
87321   assert( argc==3 );
87322   UNUSED_PARAMETER2(NotUsed, argc);
87323 
87324   if( argv==0 || argv[0]==0 || argv[2]==0 ){
87325     return 0;
87326   }
87327   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
87328   if( pTable==0 ){
87329     return 0;
87330   }
87331   if( argv[1]==0 ){
87332     pIndex = 0;
87333   }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
87334     pIndex = sqlite3PrimaryKeyIndex(pTable);
87335   }else{
87336     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
87337   }
87338   z = argv[2];
87339 
87340   if( pIndex ){
87341     int nCol = pIndex->nKeyCol+1;
87342 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87343     tRowcnt * const aiRowEst = pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(
87344         sizeof(tRowcnt) * nCol
87345     );
87346     if( aiRowEst==0 ) pInfo->db->mallocFailed = 1;
87347 #else
87348     tRowcnt * const aiRowEst = 0;
87349 #endif
87350     pIndex->bUnordered = 0;
87351     decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
87352     if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
87353   }else{
87354     Index fakeIdx;
87355     fakeIdx.szIdxRow = pTable->szTabRow;
87356 #ifdef SQLITE_ENABLE_COSTMULT
87357     fakeIdx.pTable = pTable;
87358 #endif
87359     decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
87360     pTable->szTabRow = fakeIdx.szIdxRow;
87361   }
87362 
87363   return 0;
87364 }
87365 
87366 /*
87367 ** If the Index.aSample variable is not NULL, delete the aSample[] array
87368 ** and its contents.
87369 */
87370 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
87371 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87372   if( pIdx->aSample ){
87373     int j;
87374     for(j=0; j<pIdx->nSample; j++){
87375       IndexSample *p = &pIdx->aSample[j];
87376       sqlite3DbFree(db, p->p);
87377     }
87378     sqlite3DbFree(db, pIdx->aSample);
87379   }
87380   if( db && db->pnBytesFreed==0 ){
87381     pIdx->nSample = 0;
87382     pIdx->aSample = 0;
87383   }
87384 #else
87385   UNUSED_PARAMETER(db);
87386   UNUSED_PARAMETER(pIdx);
87387 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
87388 }
87389 
87390 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87391 /*
87392 ** Populate the pIdx->aAvgEq[] array based on the samples currently
87393 ** stored in pIdx->aSample[].
87394 */
87395 static void initAvgEq(Index *pIdx){
87396   if( pIdx ){
87397     IndexSample *aSample = pIdx->aSample;
87398     IndexSample *pFinal = &aSample[pIdx->nSample-1];
87399     int iCol;
87400     int nCol = 1;
87401     if( pIdx->nSampleCol>1 ){
87402       /* If this is stat4 data, then calculate aAvgEq[] values for all
87403       ** sample columns except the last. The last is always set to 1, as
87404       ** once the trailing PK fields are considered all index keys are
87405       ** unique.  */
87406       nCol = pIdx->nSampleCol-1;
87407       pIdx->aAvgEq[nCol] = 1;
87408     }
87409     for(iCol=0; iCol<nCol; iCol++){
87410       int nSample = pIdx->nSample;
87411       int i;                    /* Used to iterate through samples */
87412       tRowcnt sumEq = 0;        /* Sum of the nEq values */
87413       tRowcnt avgEq = 0;
87414       tRowcnt nRow;             /* Number of rows in index */
87415       i64 nSum100 = 0;          /* Number of terms contributing to sumEq */
87416       i64 nDist100;             /* Number of distinct values in index */
87417 
87418       if( pIdx->aiRowEst==0 || pIdx->aiRowEst[iCol+1]==0 ){
87419         nRow = pFinal->anLt[iCol];
87420         nDist100 = (i64)100 * pFinal->anDLt[iCol];
87421         nSample--;
87422       }else{
87423         nRow = pIdx->aiRowEst[0];
87424         nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
87425       }
87426 
87427       /* Set nSum to the number of distinct (iCol+1) field prefixes that
87428       ** occur in the stat4 table for this index. Set sumEq to the sum of
87429       ** the nEq values for column iCol for the same set (adding the value
87430       ** only once where there exist duplicate prefixes).  */
87431       for(i=0; i<nSample; i++){
87432         if( i==(pIdx->nSample-1)
87433          || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
87434         ){
87435           sumEq += aSample[i].anEq[iCol];
87436           nSum100 += 100;
87437         }
87438       }
87439 
87440       if( nDist100>nSum100 ){
87441         avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
87442       }
87443       if( avgEq==0 ) avgEq = 1;
87444       pIdx->aAvgEq[iCol] = avgEq;
87445     }
87446   }
87447 }
87448 
87449 /*
87450 ** Look up an index by name.  Or, if the name of a WITHOUT ROWID table
87451 ** is supplied instead, find the PRIMARY KEY index for that table.
87452 */
87453 static Index *findIndexOrPrimaryKey(
87454   sqlite3 *db,
87455   const char *zName,
87456   const char *zDb
87457 ){
87458   Index *pIdx = sqlite3FindIndex(db, zName, zDb);
87459   if( pIdx==0 ){
87460     Table *pTab = sqlite3FindTable(db, zName, zDb);
87461     if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
87462   }
87463   return pIdx;
87464 }
87465 
87466 /*
87467 ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
87468 ** into the relevant Index.aSample[] arrays.
87469 **
87470 ** Arguments zSql1 and zSql2 must point to SQL statements that return
87471 ** data equivalent to the following (statements are different for stat3,
87472 ** see the caller of this function for details):
87473 **
87474 **    zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
87475 **    zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
87476 **
87477 ** where %Q is replaced with the database name before the SQL is executed.
87478 */
87479 static int loadStatTbl(
87480   sqlite3 *db,                  /* Database handle */
87481   int bStat3,                   /* Assume single column records only */
87482   const char *zSql1,            /* SQL statement 1 (see above) */
87483   const char *zSql2,            /* SQL statement 2 (see above) */
87484   const char *zDb               /* Database name (e.g. "main") */
87485 ){
87486   int rc;                       /* Result codes from subroutines */
87487   sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
87488   char *zSql;                   /* Text of the SQL statement */
87489   Index *pPrevIdx = 0;          /* Previous index in the loop */
87490   IndexSample *pSample;         /* A slot in pIdx->aSample[] */
87491 
87492   assert( db->lookaside.bEnabled==0 );
87493   zSql = sqlite3MPrintf(db, zSql1, zDb);
87494   if( !zSql ){
87495     return SQLITE_NOMEM;
87496   }
87497   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
87498   sqlite3DbFree(db, zSql);
87499   if( rc ) return rc;
87500 
87501   while( sqlite3_step(pStmt)==SQLITE_ROW ){
87502     int nIdxCol = 1;              /* Number of columns in stat4 records */
87503 
87504     char *zIndex;   /* Index name */
87505     Index *pIdx;    /* Pointer to the index object */
87506     int nSample;    /* Number of samples */
87507     int nByte;      /* Bytes of space required */
87508     int i;          /* Bytes of space required */
87509     tRowcnt *pSpace;
87510 
87511     zIndex = (char *)sqlite3_column_text(pStmt, 0);
87512     if( zIndex==0 ) continue;
87513     nSample = sqlite3_column_int(pStmt, 1);
87514     pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
87515     assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
87516     /* Index.nSample is non-zero at this point if data has already been
87517     ** loaded from the stat4 table. In this case ignore stat3 data.  */
87518     if( pIdx==0 || pIdx->nSample ) continue;
87519     if( bStat3==0 ){
87520       assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
87521       if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
87522         nIdxCol = pIdx->nKeyCol;
87523       }else{
87524         nIdxCol = pIdx->nColumn;
87525       }
87526     }
87527     pIdx->nSampleCol = nIdxCol;
87528     nByte = sizeof(IndexSample) * nSample;
87529     nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
87530     nByte += nIdxCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */
87531 
87532     pIdx->aSample = sqlite3DbMallocZero(db, nByte);
87533     if( pIdx->aSample==0 ){
87534       sqlite3_finalize(pStmt);
87535       return SQLITE_NOMEM;
87536     }
87537     pSpace = (tRowcnt*)&pIdx->aSample[nSample];
87538     pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
87539     for(i=0; i<nSample; i++){
87540       pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
87541       pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
87542       pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
87543     }
87544     assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
87545   }
87546   rc = sqlite3_finalize(pStmt);
87547   if( rc ) return rc;
87548 
87549   zSql = sqlite3MPrintf(db, zSql2, zDb);
87550   if( !zSql ){
87551     return SQLITE_NOMEM;
87552   }
87553   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
87554   sqlite3DbFree(db, zSql);
87555   if( rc ) return rc;
87556 
87557   while( sqlite3_step(pStmt)==SQLITE_ROW ){
87558     char *zIndex;                 /* Index name */
87559     Index *pIdx;                  /* Pointer to the index object */
87560     int nCol = 1;                 /* Number of columns in index */
87561 
87562     zIndex = (char *)sqlite3_column_text(pStmt, 0);
87563     if( zIndex==0 ) continue;
87564     pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
87565     if( pIdx==0 ) continue;
87566     /* This next condition is true if data has already been loaded from
87567     ** the sqlite_stat4 table. In this case ignore stat3 data.  */
87568     nCol = pIdx->nSampleCol;
87569     if( bStat3 && nCol>1 ) continue;
87570     if( pIdx!=pPrevIdx ){
87571       initAvgEq(pPrevIdx);
87572       pPrevIdx = pIdx;
87573     }
87574     pSample = &pIdx->aSample[pIdx->nSample];
87575     decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
87576     decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
87577     decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
87578 
87579     /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
87580     ** This is in case the sample record is corrupted. In that case, the
87581     ** sqlite3VdbeRecordCompare() may read up to two varints past the
87582     ** end of the allocated buffer before it realizes it is dealing with
87583     ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
87584     ** a buffer overread.  */
87585     pSample->n = sqlite3_column_bytes(pStmt, 4);
87586     pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
87587     if( pSample->p==0 ){
87588       sqlite3_finalize(pStmt);
87589       return SQLITE_NOMEM;
87590     }
87591     memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
87592     pIdx->nSample++;
87593   }
87594   rc = sqlite3_finalize(pStmt);
87595   if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
87596   return rc;
87597 }
87598 
87599 /*
87600 ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
87601 ** the Index.aSample[] arrays of all indices.
87602 */
87603 static int loadStat4(sqlite3 *db, const char *zDb){
87604   int rc = SQLITE_OK;             /* Result codes from subroutines */
87605 
87606   assert( db->lookaside.bEnabled==0 );
87607   if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
87608     rc = loadStatTbl(db, 0,
87609       "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
87610       "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
87611       zDb
87612     );
87613   }
87614 
87615   if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
87616     rc = loadStatTbl(db, 1,
87617       "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
87618       "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
87619       zDb
87620     );
87621   }
87622 
87623   return rc;
87624 }
87625 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
87626 
87627 /*
87628 ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
87629 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
87630 ** arrays. The contents of sqlite_stat3/4 are used to populate the
87631 ** Index.aSample[] arrays.
87632 **
87633 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
87634 ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
87635 ** during compilation and the sqlite_stat3/4 table is present, no data is
87636 ** read from it.
87637 **
87638 ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
87639 ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
87640 ** returned. However, in this case, data is read from the sqlite_stat1
87641 ** table (if it is present) before returning.
87642 **
87643 ** If an OOM error occurs, this function always sets db->mallocFailed.
87644 ** This means if the caller does not care about other errors, the return
87645 ** code may be ignored.
87646 */
87647 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
87648   analysisInfo sInfo;
87649   HashElem *i;
87650   char *zSql;
87651   int rc;
87652 
87653   assert( iDb>=0 && iDb<db->nDb );
87654   assert( db->aDb[iDb].pBt!=0 );
87655 
87656   /* Clear any prior statistics */
87657   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
87658   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
87659     Index *pIdx = sqliteHashData(i);
87660     sqlite3DefaultRowEst(pIdx);
87661 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87662     sqlite3DeleteIndexSamples(db, pIdx);
87663     pIdx->aSample = 0;
87664 #endif
87665   }
87666 
87667   /* Check to make sure the sqlite_stat1 table exists */
87668   sInfo.db = db;
87669   sInfo.zDatabase = db->aDb[iDb].zName;
87670   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
87671     return SQLITE_ERROR;
87672   }
87673 
87674   /* Load new statistics out of the sqlite_stat1 table */
87675   zSql = sqlite3MPrintf(db,
87676       "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
87677   if( zSql==0 ){
87678     rc = SQLITE_NOMEM;
87679   }else{
87680     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
87681     sqlite3DbFree(db, zSql);
87682   }
87683 
87684 
87685   /* Load the statistics from the sqlite_stat4 table. */
87686 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87687   if( rc==SQLITE_OK ){
87688     int lookasideEnabled = db->lookaside.bEnabled;
87689     db->lookaside.bEnabled = 0;
87690     rc = loadStat4(db, sInfo.zDatabase);
87691     db->lookaside.bEnabled = lookasideEnabled;
87692   }
87693   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
87694     Index *pIdx = sqliteHashData(i);
87695     sqlite3_free(pIdx->aiRowEst);
87696     pIdx->aiRowEst = 0;
87697   }
87698 #endif
87699 
87700   if( rc==SQLITE_NOMEM ){
87701     db->mallocFailed = 1;
87702   }
87703   return rc;
87704 }
87705 
87706 
87707 #endif /* SQLITE_OMIT_ANALYZE */
87708 
87709 /************** End of analyze.c *********************************************/
87710 /************** Begin file attach.c ******************************************/
87711 /*
87712 ** 2003 April 6
87713 **
87714 ** The author disclaims copyright to this source code.  In place of
87715 ** a legal notice, here is a blessing:
87716 **
87717 **    May you do good and not evil.
87718 **    May you find forgiveness for yourself and forgive others.
87719 **    May you share freely, never taking more than you give.
87720 **
87721 *************************************************************************
87722 ** This file contains code used to implement the ATTACH and DETACH commands.
87723 */
87724 
87725 #ifndef SQLITE_OMIT_ATTACH
87726 /*
87727 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
87728 ** is slightly different from resolving a normal SQL expression, because simple
87729 ** identifiers are treated as strings, not possible column names or aliases.
87730 **
87731 ** i.e. if the parser sees:
87732 **
87733 **     ATTACH DATABASE abc AS def
87734 **
87735 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
87736 ** looking for columns of the same name.
87737 **
87738 ** This only applies to the root node of pExpr, so the statement:
87739 **
87740 **     ATTACH DATABASE abc||def AS 'db2'
87741 **
87742 ** will fail because neither abc or def can be resolved.
87743 */
87744 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
87745 {
87746   int rc = SQLITE_OK;
87747   if( pExpr ){
87748     if( pExpr->op!=TK_ID ){
87749       rc = sqlite3ResolveExprNames(pName, pExpr);
87750     }else{
87751       pExpr->op = TK_STRING;
87752     }
87753   }
87754   return rc;
87755 }
87756 
87757 /*
87758 ** An SQL user-function registered to do the work of an ATTACH statement. The
87759 ** three arguments to the function come directly from an attach statement:
87760 **
87761 **     ATTACH DATABASE x AS y KEY z
87762 **
87763 **     SELECT sqlite_attach(x, y, z)
87764 **
87765 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
87766 ** third argument.
87767 */
87768 static void attachFunc(
87769   sqlite3_context *context,
87770   int NotUsed,
87771   sqlite3_value **argv
87772 ){
87773   int i;
87774   int rc = 0;
87775   sqlite3 *db = sqlite3_context_db_handle(context);
87776   const char *zName;
87777   const char *zFile;
87778   char *zPath = 0;
87779   char *zErr = 0;
87780   unsigned int flags;
87781   Db *aNew;
87782   char *zErrDyn = 0;
87783   sqlite3_vfs *pVfs;
87784 
87785   UNUSED_PARAMETER(NotUsed);
87786 
87787   zFile = (const char *)sqlite3_value_text(argv[0]);
87788   zName = (const char *)sqlite3_value_text(argv[1]);
87789   if( zFile==0 ) zFile = "";
87790   if( zName==0 ) zName = "";
87791 
87792   /* Check for the following errors:
87793   **
87794   **     * Too many attached databases,
87795   **     * Transaction currently open
87796   **     * Specified database name already being used.
87797   */
87798   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
87799     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
87800       db->aLimit[SQLITE_LIMIT_ATTACHED]
87801     );
87802     goto attach_error;
87803   }
87804   if( !db->autoCommit ){
87805     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
87806     goto attach_error;
87807   }
87808   for(i=0; i<db->nDb; i++){
87809     char *z = db->aDb[i].zName;
87810     assert( z && zName );
87811     if( sqlite3StrICmp(z, zName)==0 ){
87812       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
87813       goto attach_error;
87814     }
87815   }
87816 
87817   /* Allocate the new entry in the db->aDb[] array and initialize the schema
87818   ** hash tables.
87819   */
87820   if( db->aDb==db->aDbStatic ){
87821     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
87822     if( aNew==0 ) return;
87823     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
87824   }else{
87825     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
87826     if( aNew==0 ) return;
87827   }
87828   db->aDb = aNew;
87829   aNew = &db->aDb[db->nDb];
87830   memset(aNew, 0, sizeof(*aNew));
87831 
87832   /* Open the database file. If the btree is successfully opened, use
87833   ** it to obtain the database schema. At this point the schema may
87834   ** or may not be initialized.
87835   */
87836   flags = db->openFlags;
87837   rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
87838   if( rc!=SQLITE_OK ){
87839     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
87840     sqlite3_result_error(context, zErr, -1);
87841     sqlite3_free(zErr);
87842     return;
87843   }
87844   assert( pVfs );
87845   flags |= SQLITE_OPEN_MAIN_DB;
87846   rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
87847   sqlite3_free( zPath );
87848   db->nDb++;
87849   if( rc==SQLITE_CONSTRAINT ){
87850     rc = SQLITE_ERROR;
87851     zErrDyn = sqlite3MPrintf(db, "database is already attached");
87852   }else if( rc==SQLITE_OK ){
87853     Pager *pPager;
87854     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
87855     if( !aNew->pSchema ){
87856       rc = SQLITE_NOMEM;
87857     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
87858       zErrDyn = sqlite3MPrintf(db,
87859         "attached databases must use the same text encoding as main database");
87860       rc = SQLITE_ERROR;
87861     }
87862     pPager = sqlite3BtreePager(aNew->pBt);
87863     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
87864     sqlite3BtreeSecureDelete(aNew->pBt,
87865                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
87866 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
87867     sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
87868 #endif
87869   }
87870   aNew->safety_level = 3;
87871   aNew->zName = sqlite3DbStrDup(db, zName);
87872   if( rc==SQLITE_OK && aNew->zName==0 ){
87873     rc = SQLITE_NOMEM;
87874   }
87875 
87876 
87877 #ifdef SQLITE_HAS_CODEC
87878   if( rc==SQLITE_OK ){
87879     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
87880     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
87881     int nKey;
87882     char *zKey;
87883     int t = sqlite3_value_type(argv[2]);
87884     switch( t ){
87885       case SQLITE_INTEGER:
87886       case SQLITE_FLOAT:
87887         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
87888         rc = SQLITE_ERROR;
87889         break;
87890 
87891       case SQLITE_TEXT:
87892       case SQLITE_BLOB:
87893         nKey = sqlite3_value_bytes(argv[2]);
87894         zKey = (char *)sqlite3_value_blob(argv[2]);
87895         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
87896         break;
87897 
87898       case SQLITE_NULL:
87899         /* No key specified.  Use the key from the main database */
87900         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
87901         if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
87902           rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
87903         }
87904         break;
87905     }
87906   }
87907 #endif
87908 
87909   /* If the file was opened successfully, read the schema for the new database.
87910   ** If this fails, or if opening the file failed, then close the file and
87911   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
87912   ** we found it.
87913   */
87914   if( rc==SQLITE_OK ){
87915     sqlite3BtreeEnterAll(db);
87916     rc = sqlite3Init(db, &zErrDyn);
87917     sqlite3BtreeLeaveAll(db);
87918   }
87919 #ifdef SQLITE_USER_AUTHENTICATION
87920   if( rc==SQLITE_OK ){
87921     u8 newAuth = 0;
87922     rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
87923     if( newAuth<db->auth.authLevel ){
87924       rc = SQLITE_AUTH_USER;
87925     }
87926   }
87927 #endif
87928   if( rc ){
87929     int iDb = db->nDb - 1;
87930     assert( iDb>=2 );
87931     if( db->aDb[iDb].pBt ){
87932       sqlite3BtreeClose(db->aDb[iDb].pBt);
87933       db->aDb[iDb].pBt = 0;
87934       db->aDb[iDb].pSchema = 0;
87935     }
87936     sqlite3ResetAllSchemasOfConnection(db);
87937     db->nDb = iDb;
87938     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
87939       db->mallocFailed = 1;
87940       sqlite3DbFree(db, zErrDyn);
87941       zErrDyn = sqlite3MPrintf(db, "out of memory");
87942     }else if( zErrDyn==0 ){
87943       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
87944     }
87945     goto attach_error;
87946   }
87947 
87948   return;
87949 
87950 attach_error:
87951   /* Return an error if we get here */
87952   if( zErrDyn ){
87953     sqlite3_result_error(context, zErrDyn, -1);
87954     sqlite3DbFree(db, zErrDyn);
87955   }
87956   if( rc ) sqlite3_result_error_code(context, rc);
87957 }
87958 
87959 /*
87960 ** An SQL user-function registered to do the work of an DETACH statement. The
87961 ** three arguments to the function come directly from a detach statement:
87962 **
87963 **     DETACH DATABASE x
87964 **
87965 **     SELECT sqlite_detach(x)
87966 */
87967 static void detachFunc(
87968   sqlite3_context *context,
87969   int NotUsed,
87970   sqlite3_value **argv
87971 ){
87972   const char *zName = (const char *)sqlite3_value_text(argv[0]);
87973   sqlite3 *db = sqlite3_context_db_handle(context);
87974   int i;
87975   Db *pDb = 0;
87976   char zErr[128];
87977 
87978   UNUSED_PARAMETER(NotUsed);
87979 
87980   if( zName==0 ) zName = "";
87981   for(i=0; i<db->nDb; i++){
87982     pDb = &db->aDb[i];
87983     if( pDb->pBt==0 ) continue;
87984     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
87985   }
87986 
87987   if( i>=db->nDb ){
87988     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
87989     goto detach_error;
87990   }
87991   if( i<2 ){
87992     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
87993     goto detach_error;
87994   }
87995   if( !db->autoCommit ){
87996     sqlite3_snprintf(sizeof(zErr), zErr,
87997                      "cannot DETACH database within transaction");
87998     goto detach_error;
87999   }
88000   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
88001     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
88002     goto detach_error;
88003   }
88004 
88005   sqlite3BtreeClose(pDb->pBt);
88006   pDb->pBt = 0;
88007   pDb->pSchema = 0;
88008   sqlite3ResetAllSchemasOfConnection(db);
88009   return;
88010 
88011 detach_error:
88012   sqlite3_result_error(context, zErr, -1);
88013 }
88014 
88015 /*
88016 ** This procedure generates VDBE code for a single invocation of either the
88017 ** sqlite_detach() or sqlite_attach() SQL user functions.
88018 */
88019 static void codeAttach(
88020   Parse *pParse,       /* The parser context */
88021   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
88022   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
88023   Expr *pAuthArg,      /* Expression to pass to authorization callback */
88024   Expr *pFilename,     /* Name of database file */
88025   Expr *pDbname,       /* Name of the database to use internally */
88026   Expr *pKey           /* Database key for encryption extension */
88027 ){
88028   int rc;
88029   NameContext sName;
88030   Vdbe *v;
88031   sqlite3* db = pParse->db;
88032   int regArgs;
88033 
88034   memset(&sName, 0, sizeof(NameContext));
88035   sName.pParse = pParse;
88036 
88037   if(
88038       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
88039       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
88040       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
88041   ){
88042     pParse->nErr++;
88043     goto attach_end;
88044   }
88045 
88046 #ifndef SQLITE_OMIT_AUTHORIZATION
88047   if( pAuthArg ){
88048     char *zAuthArg;
88049     if( pAuthArg->op==TK_STRING ){
88050       zAuthArg = pAuthArg->u.zToken;
88051     }else{
88052       zAuthArg = 0;
88053     }
88054     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
88055     if(rc!=SQLITE_OK ){
88056       goto attach_end;
88057     }
88058   }
88059 #endif /* SQLITE_OMIT_AUTHORIZATION */
88060 
88061 
88062   v = sqlite3GetVdbe(pParse);
88063   regArgs = sqlite3GetTempRange(pParse, 4);
88064   sqlite3ExprCode(pParse, pFilename, regArgs);
88065   sqlite3ExprCode(pParse, pDbname, regArgs+1);
88066   sqlite3ExprCode(pParse, pKey, regArgs+2);
88067 
88068   assert( v || db->mallocFailed );
88069   if( v ){
88070     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
88071     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
88072     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
88073     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
88074 
88075     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
88076     ** statement only). For DETACH, set it to false (expire all existing
88077     ** statements).
88078     */
88079     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
88080   }
88081 
88082 attach_end:
88083   sqlite3ExprDelete(db, pFilename);
88084   sqlite3ExprDelete(db, pDbname);
88085   sqlite3ExprDelete(db, pKey);
88086 }
88087 
88088 /*
88089 ** Called by the parser to compile a DETACH statement.
88090 **
88091 **     DETACH pDbname
88092 */
88093 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
88094   static const FuncDef detach_func = {
88095     1,                /* nArg */
88096     SQLITE_UTF8,      /* funcFlags */
88097     0,                /* pUserData */
88098     0,                /* pNext */
88099     detachFunc,       /* xFunc */
88100     0,                /* xStep */
88101     0,                /* xFinalize */
88102     "sqlite_detach",  /* zName */
88103     0,                /* pHash */
88104     0                 /* pDestructor */
88105   };
88106   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
88107 }
88108 
88109 /*
88110 ** Called by the parser to compile an ATTACH statement.
88111 **
88112 **     ATTACH p AS pDbname KEY pKey
88113 */
88114 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
88115   static const FuncDef attach_func = {
88116     3,                /* nArg */
88117     SQLITE_UTF8,      /* funcFlags */
88118     0,                /* pUserData */
88119     0,                /* pNext */
88120     attachFunc,       /* xFunc */
88121     0,                /* xStep */
88122     0,                /* xFinalize */
88123     "sqlite_attach",  /* zName */
88124     0,                /* pHash */
88125     0                 /* pDestructor */
88126   };
88127   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
88128 }
88129 #endif /* SQLITE_OMIT_ATTACH */
88130 
88131 /*
88132 ** Initialize a DbFixer structure.  This routine must be called prior
88133 ** to passing the structure to one of the sqliteFixAAAA() routines below.
88134 */
88135 SQLITE_PRIVATE void sqlite3FixInit(
88136   DbFixer *pFix,      /* The fixer to be initialized */
88137   Parse *pParse,      /* Error messages will be written here */
88138   int iDb,            /* This is the database that must be used */
88139   const char *zType,  /* "view", "trigger", or "index" */
88140   const Token *pName  /* Name of the view, trigger, or index */
88141 ){
88142   sqlite3 *db;
88143 
88144   db = pParse->db;
88145   assert( db->nDb>iDb );
88146   pFix->pParse = pParse;
88147   pFix->zDb = db->aDb[iDb].zName;
88148   pFix->pSchema = db->aDb[iDb].pSchema;
88149   pFix->zType = zType;
88150   pFix->pName = pName;
88151   pFix->bVarOnly = (iDb==1);
88152 }
88153 
88154 /*
88155 ** The following set of routines walk through the parse tree and assign
88156 ** a specific database to all table references where the database name
88157 ** was left unspecified in the original SQL statement.  The pFix structure
88158 ** must have been initialized by a prior call to sqlite3FixInit().
88159 **
88160 ** These routines are used to make sure that an index, trigger, or
88161 ** view in one database does not refer to objects in a different database.
88162 ** (Exception: indices, triggers, and views in the TEMP database are
88163 ** allowed to refer to anything.)  If a reference is explicitly made
88164 ** to an object in a different database, an error message is added to
88165 ** pParse->zErrMsg and these routines return non-zero.  If everything
88166 ** checks out, these routines return 0.
88167 */
88168 SQLITE_PRIVATE int sqlite3FixSrcList(
88169   DbFixer *pFix,       /* Context of the fixation */
88170   SrcList *pList       /* The Source list to check and modify */
88171 ){
88172   int i;
88173   const char *zDb;
88174   struct SrcList_item *pItem;
88175 
88176   if( NEVER(pList==0) ) return 0;
88177   zDb = pFix->zDb;
88178   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
88179     if( pFix->bVarOnly==0 ){
88180       if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
88181         sqlite3ErrorMsg(pFix->pParse,
88182             "%s %T cannot reference objects in database %s",
88183             pFix->zType, pFix->pName, pItem->zDatabase);
88184         return 1;
88185       }
88186       sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
88187       pItem->zDatabase = 0;
88188       pItem->pSchema = pFix->pSchema;
88189     }
88190 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
88191     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
88192     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
88193 #endif
88194   }
88195   return 0;
88196 }
88197 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
88198 SQLITE_PRIVATE int sqlite3FixSelect(
88199   DbFixer *pFix,       /* Context of the fixation */
88200   Select *pSelect      /* The SELECT statement to be fixed to one database */
88201 ){
88202   while( pSelect ){
88203     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
88204       return 1;
88205     }
88206     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
88207       return 1;
88208     }
88209     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
88210       return 1;
88211     }
88212     if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
88213       return 1;
88214     }
88215     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
88216       return 1;
88217     }
88218     if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
88219       return 1;
88220     }
88221     if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
88222       return 1;
88223     }
88224     if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
88225       return 1;
88226     }
88227     pSelect = pSelect->pPrior;
88228   }
88229   return 0;
88230 }
88231 SQLITE_PRIVATE int sqlite3FixExpr(
88232   DbFixer *pFix,     /* Context of the fixation */
88233   Expr *pExpr        /* The expression to be fixed to one database */
88234 ){
88235   while( pExpr ){
88236     if( pExpr->op==TK_VARIABLE ){
88237       if( pFix->pParse->db->init.busy ){
88238         pExpr->op = TK_NULL;
88239       }else{
88240         sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
88241         return 1;
88242       }
88243     }
88244     if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
88245     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
88246       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
88247     }else{
88248       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
88249     }
88250     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
88251       return 1;
88252     }
88253     pExpr = pExpr->pLeft;
88254   }
88255   return 0;
88256 }
88257 SQLITE_PRIVATE int sqlite3FixExprList(
88258   DbFixer *pFix,     /* Context of the fixation */
88259   ExprList *pList    /* The expression to be fixed to one database */
88260 ){
88261   int i;
88262   struct ExprList_item *pItem;
88263   if( pList==0 ) return 0;
88264   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
88265     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
88266       return 1;
88267     }
88268   }
88269   return 0;
88270 }
88271 #endif
88272 
88273 #ifndef SQLITE_OMIT_TRIGGER
88274 SQLITE_PRIVATE int sqlite3FixTriggerStep(
88275   DbFixer *pFix,     /* Context of the fixation */
88276   TriggerStep *pStep /* The trigger step be fixed to one database */
88277 ){
88278   while( pStep ){
88279     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
88280       return 1;
88281     }
88282     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
88283       return 1;
88284     }
88285     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
88286       return 1;
88287     }
88288     pStep = pStep->pNext;
88289   }
88290   return 0;
88291 }
88292 #endif
88293 
88294 /************** End of attach.c **********************************************/
88295 /************** Begin file auth.c ********************************************/
88296 /*
88297 ** 2003 January 11
88298 **
88299 ** The author disclaims copyright to this source code.  In place of
88300 ** a legal notice, here is a blessing:
88301 **
88302 **    May you do good and not evil.
88303 **    May you find forgiveness for yourself and forgive others.
88304 **    May you share freely, never taking more than you give.
88305 **
88306 *************************************************************************
88307 ** This file contains code used to implement the sqlite3_set_authorizer()
88308 ** API.  This facility is an optional feature of the library.  Embedded
88309 ** systems that do not need this facility may omit it by recompiling
88310 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
88311 */
88312 
88313 /*
88314 ** All of the code in this file may be omitted by defining a single
88315 ** macro.
88316 */
88317 #ifndef SQLITE_OMIT_AUTHORIZATION
88318 
88319 /*
88320 ** Set or clear the access authorization function.
88321 **
88322 ** The access authorization function is be called during the compilation
88323 ** phase to verify that the user has read and/or write access permission on
88324 ** various fields of the database.  The first argument to the auth function
88325 ** is a copy of the 3rd argument to this routine.  The second argument
88326 ** to the auth function is one of these constants:
88327 **
88328 **       SQLITE_CREATE_INDEX
88329 **       SQLITE_CREATE_TABLE
88330 **       SQLITE_CREATE_TEMP_INDEX
88331 **       SQLITE_CREATE_TEMP_TABLE
88332 **       SQLITE_CREATE_TEMP_TRIGGER
88333 **       SQLITE_CREATE_TEMP_VIEW
88334 **       SQLITE_CREATE_TRIGGER
88335 **       SQLITE_CREATE_VIEW
88336 **       SQLITE_DELETE
88337 **       SQLITE_DROP_INDEX
88338 **       SQLITE_DROP_TABLE
88339 **       SQLITE_DROP_TEMP_INDEX
88340 **       SQLITE_DROP_TEMP_TABLE
88341 **       SQLITE_DROP_TEMP_TRIGGER
88342 **       SQLITE_DROP_TEMP_VIEW
88343 **       SQLITE_DROP_TRIGGER
88344 **       SQLITE_DROP_VIEW
88345 **       SQLITE_INSERT
88346 **       SQLITE_PRAGMA
88347 **       SQLITE_READ
88348 **       SQLITE_SELECT
88349 **       SQLITE_TRANSACTION
88350 **       SQLITE_UPDATE
88351 **
88352 ** The third and fourth arguments to the auth function are the name of
88353 ** the table and the column that are being accessed.  The auth function
88354 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
88355 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
88356 ** means that the SQL statement will never-run - the sqlite3_exec() call
88357 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
88358 ** should run but attempts to read the specified column will return NULL
88359 ** and attempts to write the column will be ignored.
88360 **
88361 ** Setting the auth function to NULL disables this hook.  The default
88362 ** setting of the auth function is NULL.
88363 */
88364 SQLITE_API int sqlite3_set_authorizer(
88365   sqlite3 *db,
88366   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
88367   void *pArg
88368 ){
88369   sqlite3_mutex_enter(db->mutex);
88370   db->xAuth = (sqlite3_xauth)xAuth;
88371   db->pAuthArg = pArg;
88372   sqlite3ExpirePreparedStatements(db);
88373   sqlite3_mutex_leave(db->mutex);
88374   return SQLITE_OK;
88375 }
88376 
88377 /*
88378 ** Write an error message into pParse->zErrMsg that explains that the
88379 ** user-supplied authorization function returned an illegal value.
88380 */
88381 static void sqliteAuthBadReturnCode(Parse *pParse){
88382   sqlite3ErrorMsg(pParse, "authorizer malfunction");
88383   pParse->rc = SQLITE_ERROR;
88384 }
88385 
88386 /*
88387 ** Invoke the authorization callback for permission to read column zCol from
88388 ** table zTab in database zDb. This function assumes that an authorization
88389 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
88390 **
88391 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
88392 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
88393 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
88394 */
88395 SQLITE_PRIVATE int sqlite3AuthReadCol(
88396   Parse *pParse,                  /* The parser context */
88397   const char *zTab,               /* Table name */
88398   const char *zCol,               /* Column name */
88399   int iDb                         /* Index of containing database. */
88400 ){
88401   sqlite3 *db = pParse->db;       /* Database handle */
88402   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
88403   int rc;                         /* Auth callback return code */
88404 
88405   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
88406 #ifdef SQLITE_USER_AUTHENTICATION
88407                  ,db->auth.zAuthUser
88408 #endif
88409                 );
88410   if( rc==SQLITE_DENY ){
88411     if( db->nDb>2 || iDb!=0 ){
88412       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
88413     }else{
88414       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
88415     }
88416     pParse->rc = SQLITE_AUTH;
88417   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
88418     sqliteAuthBadReturnCode(pParse);
88419   }
88420   return rc;
88421 }
88422 
88423 /*
88424 ** The pExpr should be a TK_COLUMN expression.  The table referred to
88425 ** is in pTabList or else it is the NEW or OLD table of a trigger.
88426 ** Check to see if it is OK to read this particular column.
88427 **
88428 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
88429 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
88430 ** then generate an error.
88431 */
88432 SQLITE_PRIVATE void sqlite3AuthRead(
88433   Parse *pParse,        /* The parser context */
88434   Expr *pExpr,          /* The expression to check authorization on */
88435   Schema *pSchema,      /* The schema of the expression */
88436   SrcList *pTabList     /* All table that pExpr might refer to */
88437 ){
88438   sqlite3 *db = pParse->db;
88439   Table *pTab = 0;      /* The table being read */
88440   const char *zCol;     /* Name of the column of the table */
88441   int iSrc;             /* Index in pTabList->a[] of table being read */
88442   int iDb;              /* The index of the database the expression refers to */
88443   int iCol;             /* Index of column in table */
88444 
88445   if( db->xAuth==0 ) return;
88446   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
88447   if( iDb<0 ){
88448     /* An attempt to read a column out of a subquery or other
88449     ** temporary table. */
88450     return;
88451   }
88452 
88453   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
88454   if( pExpr->op==TK_TRIGGER ){
88455     pTab = pParse->pTriggerTab;
88456   }else{
88457     assert( pTabList );
88458     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
88459       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
88460         pTab = pTabList->a[iSrc].pTab;
88461         break;
88462       }
88463     }
88464   }
88465   iCol = pExpr->iColumn;
88466   if( NEVER(pTab==0) ) return;
88467 
88468   if( iCol>=0 ){
88469     assert( iCol<pTab->nCol );
88470     zCol = pTab->aCol[iCol].zName;
88471   }else if( pTab->iPKey>=0 ){
88472     assert( pTab->iPKey<pTab->nCol );
88473     zCol = pTab->aCol[pTab->iPKey].zName;
88474   }else{
88475     zCol = "ROWID";
88476   }
88477   assert( iDb>=0 && iDb<db->nDb );
88478   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
88479     pExpr->op = TK_NULL;
88480   }
88481 }
88482 
88483 /*
88484 ** Do an authorization check using the code and arguments given.  Return
88485 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
88486 ** is returned, then the error count and error message in pParse are
88487 ** modified appropriately.
88488 */
88489 SQLITE_PRIVATE int sqlite3AuthCheck(
88490   Parse *pParse,
88491   int code,
88492   const char *zArg1,
88493   const char *zArg2,
88494   const char *zArg3
88495 ){
88496   sqlite3 *db = pParse->db;
88497   int rc;
88498 
88499   /* Don't do any authorization checks if the database is initialising
88500   ** or if the parser is being invoked from within sqlite3_declare_vtab.
88501   */
88502   if( db->init.busy || IN_DECLARE_VTAB ){
88503     return SQLITE_OK;
88504   }
88505 
88506   if( db->xAuth==0 ){
88507     return SQLITE_OK;
88508   }
88509   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
88510 #ifdef SQLITE_USER_AUTHENTICATION
88511                  ,db->auth.zAuthUser
88512 #endif
88513                 );
88514   if( rc==SQLITE_DENY ){
88515     sqlite3ErrorMsg(pParse, "not authorized");
88516     pParse->rc = SQLITE_AUTH;
88517   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
88518     rc = SQLITE_DENY;
88519     sqliteAuthBadReturnCode(pParse);
88520   }
88521   return rc;
88522 }
88523 
88524 /*
88525 ** Push an authorization context.  After this routine is called, the
88526 ** zArg3 argument to authorization callbacks will be zContext until
88527 ** popped.  Or if pParse==0, this routine is a no-op.
88528 */
88529 SQLITE_PRIVATE void sqlite3AuthContextPush(
88530   Parse *pParse,
88531   AuthContext *pContext,
88532   const char *zContext
88533 ){
88534   assert( pParse );
88535   pContext->pParse = pParse;
88536   pContext->zAuthContext = pParse->zAuthContext;
88537   pParse->zAuthContext = zContext;
88538 }
88539 
88540 /*
88541 ** Pop an authorization context that was previously pushed
88542 ** by sqlite3AuthContextPush
88543 */
88544 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
88545   if( pContext->pParse ){
88546     pContext->pParse->zAuthContext = pContext->zAuthContext;
88547     pContext->pParse = 0;
88548   }
88549 }
88550 
88551 #endif /* SQLITE_OMIT_AUTHORIZATION */
88552 
88553 /************** End of auth.c ************************************************/
88554 /************** Begin file build.c *******************************************/
88555 /*
88556 ** 2001 September 15
88557 **
88558 ** The author disclaims copyright to this source code.  In place of
88559 ** a legal notice, here is a blessing:
88560 **
88561 **    May you do good and not evil.
88562 **    May you find forgiveness for yourself and forgive others.
88563 **    May you share freely, never taking more than you give.
88564 **
88565 *************************************************************************
88566 ** This file contains C code routines that are called by the SQLite parser
88567 ** when syntax rules are reduced.  The routines in this file handle the
88568 ** following kinds of SQL syntax:
88569 **
88570 **     CREATE TABLE
88571 **     DROP TABLE
88572 **     CREATE INDEX
88573 **     DROP INDEX
88574 **     creating ID lists
88575 **     BEGIN TRANSACTION
88576 **     COMMIT
88577 **     ROLLBACK
88578 */
88579 
88580 /*
88581 ** This routine is called when a new SQL statement is beginning to
88582 ** be parsed.  Initialize the pParse structure as needed.
88583 */
88584 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
88585   pParse->explain = (u8)explainFlag;
88586   pParse->nVar = 0;
88587 }
88588 
88589 #ifndef SQLITE_OMIT_SHARED_CACHE
88590 /*
88591 ** The TableLock structure is only used by the sqlite3TableLock() and
88592 ** codeTableLocks() functions.
88593 */
88594 struct TableLock {
88595   int iDb;             /* The database containing the table to be locked */
88596   int iTab;            /* The root page of the table to be locked */
88597   u8 isWriteLock;      /* True for write lock.  False for a read lock */
88598   const char *zName;   /* Name of the table */
88599 };
88600 
88601 /*
88602 ** Record the fact that we want to lock a table at run-time.
88603 **
88604 ** The table to be locked has root page iTab and is found in database iDb.
88605 ** A read or a write lock can be taken depending on isWritelock.
88606 **
88607 ** This routine just records the fact that the lock is desired.  The
88608 ** code to make the lock occur is generated by a later call to
88609 ** codeTableLocks() which occurs during sqlite3FinishCoding().
88610 */
88611 SQLITE_PRIVATE void sqlite3TableLock(
88612   Parse *pParse,     /* Parsing context */
88613   int iDb,           /* Index of the database containing the table to lock */
88614   int iTab,          /* Root page number of the table to be locked */
88615   u8 isWriteLock,    /* True for a write lock */
88616   const char *zName  /* Name of the table to be locked */
88617 ){
88618   Parse *pToplevel = sqlite3ParseToplevel(pParse);
88619   int i;
88620   int nBytes;
88621   TableLock *p;
88622   assert( iDb>=0 );
88623 
88624   for(i=0; i<pToplevel->nTableLock; i++){
88625     p = &pToplevel->aTableLock[i];
88626     if( p->iDb==iDb && p->iTab==iTab ){
88627       p->isWriteLock = (p->isWriteLock || isWriteLock);
88628       return;
88629     }
88630   }
88631 
88632   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
88633   pToplevel->aTableLock =
88634       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
88635   if( pToplevel->aTableLock ){
88636     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
88637     p->iDb = iDb;
88638     p->iTab = iTab;
88639     p->isWriteLock = isWriteLock;
88640     p->zName = zName;
88641   }else{
88642     pToplevel->nTableLock = 0;
88643     pToplevel->db->mallocFailed = 1;
88644   }
88645 }
88646 
88647 /*
88648 ** Code an OP_TableLock instruction for each table locked by the
88649 ** statement (configured by calls to sqlite3TableLock()).
88650 */
88651 static void codeTableLocks(Parse *pParse){
88652   int i;
88653   Vdbe *pVdbe;
88654 
88655   pVdbe = sqlite3GetVdbe(pParse);
88656   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
88657 
88658   for(i=0; i<pParse->nTableLock; i++){
88659     TableLock *p = &pParse->aTableLock[i];
88660     int p1 = p->iDb;
88661     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
88662                       p->zName, P4_STATIC);
88663   }
88664 }
88665 #else
88666   #define codeTableLocks(x)
88667 #endif
88668 
88669 /*
88670 ** Return TRUE if the given yDbMask object is empty - if it contains no
88671 ** 1 bits.  This routine is used by the DbMaskAllZero() and DbMaskNotZero()
88672 ** macros when SQLITE_MAX_ATTACHED is greater than 30.
88673 */
88674 #if SQLITE_MAX_ATTACHED>30
88675 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
88676   int i;
88677   for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
88678   return 1;
88679 }
88680 #endif
88681 
88682 /*
88683 ** This routine is called after a single SQL statement has been
88684 ** parsed and a VDBE program to execute that statement has been
88685 ** prepared.  This routine puts the finishing touches on the
88686 ** VDBE program and resets the pParse structure for the next
88687 ** parse.
88688 **
88689 ** Note that if an error occurred, it might be the case that
88690 ** no VDBE code was generated.
88691 */
88692 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
88693   sqlite3 *db;
88694   Vdbe *v;
88695 
88696   assert( pParse->pToplevel==0 );
88697   db = pParse->db;
88698   if( db->mallocFailed ) return;
88699   if( pParse->nested ) return;
88700   if( pParse->nErr ) return;
88701 
88702   /* Begin by generating some termination code at the end of the
88703   ** vdbe program
88704   */
88705   v = sqlite3GetVdbe(pParse);
88706   assert( !pParse->isMultiWrite
88707        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
88708   if( v ){
88709     while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
88710     sqlite3VdbeAddOp0(v, OP_Halt);
88711 
88712 #if SQLITE_USER_AUTHENTICATION
88713     if( pParse->nTableLock>0 && db->init.busy==0 ){
88714       sqlite3UserAuthInit(db);
88715       if( db->auth.authLevel<UAUTH_User ){
88716         pParse->rc = SQLITE_AUTH_USER;
88717         sqlite3ErrorMsg(pParse, "user not authenticated");
88718         return;
88719       }
88720     }
88721 #endif
88722 
88723     /* The cookie mask contains one bit for each database file open.
88724     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
88725     ** set for each database that is used.  Generate code to start a
88726     ** transaction on each used database and to verify the schema cookie
88727     ** on each used database.
88728     */
88729     if( db->mallocFailed==0
88730      && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
88731     ){
88732       int iDb, i;
88733       assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
88734       sqlite3VdbeJumpHere(v, 0);
88735       for(iDb=0; iDb<db->nDb; iDb++){
88736         if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
88737         sqlite3VdbeUsesBtree(v, iDb);
88738         sqlite3VdbeAddOp4Int(v,
88739           OP_Transaction,                    /* Opcode */
88740           iDb,                               /* P1 */
88741           DbMaskTest(pParse->writeMask,iDb), /* P2 */
88742           pParse->cookieValue[iDb],          /* P3 */
88743           db->aDb[iDb].pSchema->iGeneration  /* P4 */
88744         );
88745         if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
88746       }
88747 #ifndef SQLITE_OMIT_VIRTUALTABLE
88748       for(i=0; i<pParse->nVtabLock; i++){
88749         char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
88750         sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
88751       }
88752       pParse->nVtabLock = 0;
88753 #endif
88754 
88755       /* Once all the cookies have been verified and transactions opened,
88756       ** obtain the required table-locks. This is a no-op unless the
88757       ** shared-cache feature is enabled.
88758       */
88759       codeTableLocks(pParse);
88760 
88761       /* Initialize any AUTOINCREMENT data structures required.
88762       */
88763       sqlite3AutoincrementBegin(pParse);
88764 
88765       /* Code constant expressions that where factored out of inner loops */
88766       if( pParse->pConstExpr ){
88767         ExprList *pEL = pParse->pConstExpr;
88768         pParse->okConstFactor = 0;
88769         for(i=0; i<pEL->nExpr; i++){
88770           sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
88771         }
88772       }
88773 
88774       /* Finally, jump back to the beginning of the executable code. */
88775       sqlite3VdbeAddOp2(v, OP_Goto, 0, 1);
88776     }
88777   }
88778 
88779 
88780   /* Get the VDBE program ready for execution
88781   */
88782   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
88783     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
88784     /* A minimum of one cursor is required if autoincrement is used
88785     *  See ticket [a696379c1f08866] */
88786     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
88787     sqlite3VdbeMakeReady(v, pParse);
88788     pParse->rc = SQLITE_DONE;
88789     pParse->colNamesSet = 0;
88790   }else{
88791     pParse->rc = SQLITE_ERROR;
88792   }
88793   pParse->nTab = 0;
88794   pParse->nMem = 0;
88795   pParse->nSet = 0;
88796   pParse->nVar = 0;
88797   DbMaskZero(pParse->cookieMask);
88798 }
88799 
88800 /*
88801 ** Run the parser and code generator recursively in order to generate
88802 ** code for the SQL statement given onto the end of the pParse context
88803 ** currently under construction.  When the parser is run recursively
88804 ** this way, the final OP_Halt is not appended and other initialization
88805 ** and finalization steps are omitted because those are handling by the
88806 ** outermost parser.
88807 **
88808 ** Not everything is nestable.  This facility is designed to permit
88809 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
88810 ** care if you decide to try to use this routine for some other purposes.
88811 */
88812 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
88813   va_list ap;
88814   char *zSql;
88815   char *zErrMsg = 0;
88816   sqlite3 *db = pParse->db;
88817 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
88818   char saveBuf[SAVE_SZ];
88819 
88820   if( pParse->nErr ) return;
88821   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
88822   va_start(ap, zFormat);
88823   zSql = sqlite3VMPrintf(db, zFormat, ap);
88824   va_end(ap);
88825   if( zSql==0 ){
88826     return;   /* A malloc must have failed */
88827   }
88828   pParse->nested++;
88829   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
88830   memset(&pParse->nVar, 0, SAVE_SZ);
88831   sqlite3RunParser(pParse, zSql, &zErrMsg);
88832   sqlite3DbFree(db, zErrMsg);
88833   sqlite3DbFree(db, zSql);
88834   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
88835   pParse->nested--;
88836 }
88837 
88838 #if SQLITE_USER_AUTHENTICATION
88839 /*
88840 ** Return TRUE if zTable is the name of the system table that stores the
88841 ** list of users and their access credentials.
88842 */
88843 SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
88844   return sqlite3_stricmp(zTable, "sqlite_user")==0;
88845 }
88846 #endif
88847 
88848 /*
88849 ** Locate the in-memory structure that describes a particular database
88850 ** table given the name of that table and (optionally) the name of the
88851 ** database containing the table.  Return NULL if not found.
88852 **
88853 ** If zDatabase is 0, all databases are searched for the table and the
88854 ** first matching table is returned.  (No checking for duplicate table
88855 ** names is done.)  The search order is TEMP first, then MAIN, then any
88856 ** auxiliary databases added using the ATTACH command.
88857 **
88858 ** See also sqlite3LocateTable().
88859 */
88860 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
88861   Table *p = 0;
88862   int i;
88863   assert( zName!=0 );
88864   /* All mutexes are required for schema access.  Make sure we hold them. */
88865   assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
88866 #if SQLITE_USER_AUTHENTICATION
88867   /* Only the admin user is allowed to know that the sqlite_user table
88868   ** exists */
88869   if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
88870     return 0;
88871   }
88872 #endif
88873   for(i=OMIT_TEMPDB; i<db->nDb; i++){
88874     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
88875     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
88876     assert( sqlite3SchemaMutexHeld(db, j, 0) );
88877     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
88878     if( p ) break;
88879   }
88880   return p;
88881 }
88882 
88883 /*
88884 ** Locate the in-memory structure that describes a particular database
88885 ** table given the name of that table and (optionally) the name of the
88886 ** database containing the table.  Return NULL if not found.  Also leave an
88887 ** error message in pParse->zErrMsg.
88888 **
88889 ** The difference between this routine and sqlite3FindTable() is that this
88890 ** routine leaves an error message in pParse->zErrMsg where
88891 ** sqlite3FindTable() does not.
88892 */
88893 SQLITE_PRIVATE Table *sqlite3LocateTable(
88894   Parse *pParse,         /* context in which to report errors */
88895   int isView,            /* True if looking for a VIEW rather than a TABLE */
88896   const char *zName,     /* Name of the table we are looking for */
88897   const char *zDbase     /* Name of the database.  Might be NULL */
88898 ){
88899   Table *p;
88900 
88901   /* Read the database schema. If an error occurs, leave an error message
88902   ** and code in pParse and return NULL. */
88903   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
88904     return 0;
88905   }
88906 
88907   p = sqlite3FindTable(pParse->db, zName, zDbase);
88908   if( p==0 ){
88909     const char *zMsg = isView ? "no such view" : "no such table";
88910     if( zDbase ){
88911       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
88912     }else{
88913       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
88914     }
88915     pParse->checkSchema = 1;
88916   }
88917 #if SQLITE_USER_AUTHENICATION
88918   else if( pParse->db->auth.authLevel<UAUTH_User ){
88919     sqlite3ErrorMsg(pParse, "user not authenticated");
88920     p = 0;
88921   }
88922 #endif
88923   return p;
88924 }
88925 
88926 /*
88927 ** Locate the table identified by *p.
88928 **
88929 ** This is a wrapper around sqlite3LocateTable(). The difference between
88930 ** sqlite3LocateTable() and this function is that this function restricts
88931 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
88932 ** non-NULL if it is part of a view or trigger program definition. See
88933 ** sqlite3FixSrcList() for details.
88934 */
88935 SQLITE_PRIVATE Table *sqlite3LocateTableItem(
88936   Parse *pParse,
88937   int isView,
88938   struct SrcList_item *p
88939 ){
88940   const char *zDb;
88941   assert( p->pSchema==0 || p->zDatabase==0 );
88942   if( p->pSchema ){
88943     int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
88944     zDb = pParse->db->aDb[iDb].zName;
88945   }else{
88946     zDb = p->zDatabase;
88947   }
88948   return sqlite3LocateTable(pParse, isView, p->zName, zDb);
88949 }
88950 
88951 /*
88952 ** Locate the in-memory structure that describes
88953 ** a particular index given the name of that index
88954 ** and the name of the database that contains the index.
88955 ** Return NULL if not found.
88956 **
88957 ** If zDatabase is 0, all databases are searched for the
88958 ** table and the first matching index is returned.  (No checking
88959 ** for duplicate index names is done.)  The search order is
88960 ** TEMP first, then MAIN, then any auxiliary databases added
88961 ** using the ATTACH command.
88962 */
88963 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
88964   Index *p = 0;
88965   int i;
88966   /* All mutexes are required for schema access.  Make sure we hold them. */
88967   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
88968   for(i=OMIT_TEMPDB; i<db->nDb; i++){
88969     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
88970     Schema *pSchema = db->aDb[j].pSchema;
88971     assert( pSchema );
88972     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
88973     assert( sqlite3SchemaMutexHeld(db, j, 0) );
88974     p = sqlite3HashFind(&pSchema->idxHash, zName);
88975     if( p ) break;
88976   }
88977   return p;
88978 }
88979 
88980 /*
88981 ** Reclaim the memory used by an index
88982 */
88983 static void freeIndex(sqlite3 *db, Index *p){
88984 #ifndef SQLITE_OMIT_ANALYZE
88985   sqlite3DeleteIndexSamples(db, p);
88986 #endif
88987   if( db==0 || db->pnBytesFreed==0 ) sqlite3KeyInfoUnref(p->pKeyInfo);
88988   sqlite3ExprDelete(db, p->pPartIdxWhere);
88989   sqlite3DbFree(db, p->zColAff);
88990   if( p->isResized ) sqlite3DbFree(db, p->azColl);
88991 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88992   sqlite3_free(p->aiRowEst);
88993 #endif
88994   sqlite3DbFree(db, p);
88995 }
88996 
88997 /*
88998 ** For the index called zIdxName which is found in the database iDb,
88999 ** unlike that index from its Table then remove the index from
89000 ** the index hash table and free all memory structures associated
89001 ** with the index.
89002 */
89003 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
89004   Index *pIndex;
89005   Hash *pHash;
89006 
89007   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89008   pHash = &db->aDb[iDb].pSchema->idxHash;
89009   pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
89010   if( ALWAYS(pIndex) ){
89011     if( pIndex->pTable->pIndex==pIndex ){
89012       pIndex->pTable->pIndex = pIndex->pNext;
89013     }else{
89014       Index *p;
89015       /* Justification of ALWAYS();  The index must be on the list of
89016       ** indices. */
89017       p = pIndex->pTable->pIndex;
89018       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
89019       if( ALWAYS(p && p->pNext==pIndex) ){
89020         p->pNext = pIndex->pNext;
89021       }
89022     }
89023     freeIndex(db, pIndex);
89024   }
89025   db->flags |= SQLITE_InternChanges;
89026 }
89027 
89028 /*
89029 ** Look through the list of open database files in db->aDb[] and if
89030 ** any have been closed, remove them from the list.  Reallocate the
89031 ** db->aDb[] structure to a smaller size, if possible.
89032 **
89033 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
89034 ** are never candidates for being collapsed.
89035 */
89036 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
89037   int i, j;
89038   for(i=j=2; i<db->nDb; i++){
89039     struct Db *pDb = &db->aDb[i];
89040     if( pDb->pBt==0 ){
89041       sqlite3DbFree(db, pDb->zName);
89042       pDb->zName = 0;
89043       continue;
89044     }
89045     if( j<i ){
89046       db->aDb[j] = db->aDb[i];
89047     }
89048     j++;
89049   }
89050   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
89051   db->nDb = j;
89052   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
89053     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
89054     sqlite3DbFree(db, db->aDb);
89055     db->aDb = db->aDbStatic;
89056   }
89057 }
89058 
89059 /*
89060 ** Reset the schema for the database at index iDb.  Also reset the
89061 ** TEMP schema.
89062 */
89063 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
89064   Db *pDb;
89065   assert( iDb<db->nDb );
89066 
89067   /* Case 1:  Reset the single schema identified by iDb */
89068   pDb = &db->aDb[iDb];
89069   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89070   assert( pDb->pSchema!=0 );
89071   sqlite3SchemaClear(pDb->pSchema);
89072 
89073   /* If any database other than TEMP is reset, then also reset TEMP
89074   ** since TEMP might be holding triggers that reference tables in the
89075   ** other database.
89076   */
89077   if( iDb!=1 ){
89078     pDb = &db->aDb[1];
89079     assert( pDb->pSchema!=0 );
89080     sqlite3SchemaClear(pDb->pSchema);
89081   }
89082   return;
89083 }
89084 
89085 /*
89086 ** Erase all schema information from all attached databases (including
89087 ** "main" and "temp") for a single database connection.
89088 */
89089 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
89090   int i;
89091   sqlite3BtreeEnterAll(db);
89092   for(i=0; i<db->nDb; i++){
89093     Db *pDb = &db->aDb[i];
89094     if( pDb->pSchema ){
89095       sqlite3SchemaClear(pDb->pSchema);
89096     }
89097   }
89098   db->flags &= ~SQLITE_InternChanges;
89099   sqlite3VtabUnlockList(db);
89100   sqlite3BtreeLeaveAll(db);
89101   sqlite3CollapseDatabaseArray(db);
89102 }
89103 
89104 /*
89105 ** This routine is called when a commit occurs.
89106 */
89107 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
89108   db->flags &= ~SQLITE_InternChanges;
89109 }
89110 
89111 /*
89112 ** Delete memory allocated for the column names of a table or view (the
89113 ** Table.aCol[] array).
89114 */
89115 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
89116   int i;
89117   Column *pCol;
89118   assert( pTable!=0 );
89119   if( (pCol = pTable->aCol)!=0 ){
89120     for(i=0; i<pTable->nCol; i++, pCol++){
89121       sqlite3DbFree(db, pCol->zName);
89122       sqlite3ExprDelete(db, pCol->pDflt);
89123       sqlite3DbFree(db, pCol->zDflt);
89124       sqlite3DbFree(db, pCol->zType);
89125       sqlite3DbFree(db, pCol->zColl);
89126     }
89127     sqlite3DbFree(db, pTable->aCol);
89128   }
89129 }
89130 
89131 /*
89132 ** Remove the memory data structures associated with the given
89133 ** Table.  No changes are made to disk by this routine.
89134 **
89135 ** This routine just deletes the data structure.  It does not unlink
89136 ** the table data structure from the hash table.  But it does destroy
89137 ** memory structures of the indices and foreign keys associated with
89138 ** the table.
89139 **
89140 ** The db parameter is optional.  It is needed if the Table object
89141 ** contains lookaside memory.  (Table objects in the schema do not use
89142 ** lookaside memory, but some ephemeral Table objects do.)  Or the
89143 ** db parameter can be used with db->pnBytesFreed to measure the memory
89144 ** used by the Table object.
89145 */
89146 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
89147   Index *pIndex, *pNext;
89148   TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
89149 
89150   assert( !pTable || pTable->nRef>0 );
89151 
89152   /* Do not delete the table until the reference count reaches zero. */
89153   if( !pTable ) return;
89154   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
89155 
89156   /* Record the number of outstanding lookaside allocations in schema Tables
89157   ** prior to doing any free() operations.  Since schema Tables do not use
89158   ** lookaside, this number should not change. */
89159   TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
89160                          db->lookaside.nOut : 0 );
89161 
89162   /* Delete all indices associated with this table. */
89163   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
89164     pNext = pIndex->pNext;
89165     assert( pIndex->pSchema==pTable->pSchema );
89166     if( !db || db->pnBytesFreed==0 ){
89167       char *zName = pIndex->zName;
89168       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
89169          &pIndex->pSchema->idxHash, zName, 0
89170       );
89171       assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
89172       assert( pOld==pIndex || pOld==0 );
89173     }
89174     freeIndex(db, pIndex);
89175   }
89176 
89177   /* Delete any foreign keys attached to this table. */
89178   sqlite3FkDelete(db, pTable);
89179 
89180   /* Delete the Table structure itself.
89181   */
89182   sqliteDeleteColumnNames(db, pTable);
89183   sqlite3DbFree(db, pTable->zName);
89184   sqlite3DbFree(db, pTable->zColAff);
89185   sqlite3SelectDelete(db, pTable->pSelect);
89186 #ifndef SQLITE_OMIT_CHECK
89187   sqlite3ExprListDelete(db, pTable->pCheck);
89188 #endif
89189 #ifndef SQLITE_OMIT_VIRTUALTABLE
89190   sqlite3VtabClear(db, pTable);
89191 #endif
89192   sqlite3DbFree(db, pTable);
89193 
89194   /* Verify that no lookaside memory was used by schema tables */
89195   assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
89196 }
89197 
89198 /*
89199 ** Unlink the given table from the hash tables and the delete the
89200 ** table structure with all its indices and foreign keys.
89201 */
89202 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
89203   Table *p;
89204   Db *pDb;
89205 
89206   assert( db!=0 );
89207   assert( iDb>=0 && iDb<db->nDb );
89208   assert( zTabName );
89209   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89210   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
89211   pDb = &db->aDb[iDb];
89212   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
89213   sqlite3DeleteTable(db, p);
89214   db->flags |= SQLITE_InternChanges;
89215 }
89216 
89217 /*
89218 ** Given a token, return a string that consists of the text of that
89219 ** token.  Space to hold the returned string
89220 ** is obtained from sqliteMalloc() and must be freed by the calling
89221 ** function.
89222 **
89223 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
89224 ** surround the body of the token are removed.
89225 **
89226 ** Tokens are often just pointers into the original SQL text and so
89227 ** are not \000 terminated and are not persistent.  The returned string
89228 ** is \000 terminated and is persistent.
89229 */
89230 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
89231   char *zName;
89232   if( pName ){
89233     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
89234     sqlite3Dequote(zName);
89235   }else{
89236     zName = 0;
89237   }
89238   return zName;
89239 }
89240 
89241 /*
89242 ** Open the sqlite_master table stored in database number iDb for
89243 ** writing. The table is opened using cursor 0.
89244 */
89245 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
89246   Vdbe *v = sqlite3GetVdbe(p);
89247   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
89248   sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
89249   if( p->nTab==0 ){
89250     p->nTab = 1;
89251   }
89252 }
89253 
89254 /*
89255 ** Parameter zName points to a nul-terminated buffer containing the name
89256 ** of a database ("main", "temp" or the name of an attached db). This
89257 ** function returns the index of the named database in db->aDb[], or
89258 ** -1 if the named db cannot be found.
89259 */
89260 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
89261   int i = -1;         /* Database number */
89262   if( zName ){
89263     Db *pDb;
89264     int n = sqlite3Strlen30(zName);
89265     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
89266       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
89267           0==sqlite3StrICmp(pDb->zName, zName) ){
89268         break;
89269       }
89270     }
89271   }
89272   return i;
89273 }
89274 
89275 /*
89276 ** The token *pName contains the name of a database (either "main" or
89277 ** "temp" or the name of an attached db). This routine returns the
89278 ** index of the named database in db->aDb[], or -1 if the named db
89279 ** does not exist.
89280 */
89281 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
89282   int i;                               /* Database number */
89283   char *zName;                         /* Name we are searching for */
89284   zName = sqlite3NameFromToken(db, pName);
89285   i = sqlite3FindDbName(db, zName);
89286   sqlite3DbFree(db, zName);
89287   return i;
89288 }
89289 
89290 /* The table or view or trigger name is passed to this routine via tokens
89291 ** pName1 and pName2. If the table name was fully qualified, for example:
89292 **
89293 ** CREATE TABLE xxx.yyy (...);
89294 **
89295 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
89296 ** the table name is not fully qualified, i.e.:
89297 **
89298 ** CREATE TABLE yyy(...);
89299 **
89300 ** Then pName1 is set to "yyy" and pName2 is "".
89301 **
89302 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
89303 ** pName2) that stores the unqualified table name.  The index of the
89304 ** database "xxx" is returned.
89305 */
89306 SQLITE_PRIVATE int sqlite3TwoPartName(
89307   Parse *pParse,      /* Parsing and code generating context */
89308   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
89309   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
89310   Token **pUnqual     /* Write the unqualified object name here */
89311 ){
89312   int iDb;                    /* Database holding the object */
89313   sqlite3 *db = pParse->db;
89314 
89315   if( ALWAYS(pName2!=0) && pName2->n>0 ){
89316     if( db->init.busy ) {
89317       sqlite3ErrorMsg(pParse, "corrupt database");
89318       pParse->nErr++;
89319       return -1;
89320     }
89321     *pUnqual = pName2;
89322     iDb = sqlite3FindDb(db, pName1);
89323     if( iDb<0 ){
89324       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
89325       pParse->nErr++;
89326       return -1;
89327     }
89328   }else{
89329     assert( db->init.iDb==0 || db->init.busy );
89330     iDb = db->init.iDb;
89331     *pUnqual = pName1;
89332   }
89333   return iDb;
89334 }
89335 
89336 /*
89337 ** This routine is used to check if the UTF-8 string zName is a legal
89338 ** unqualified name for a new schema object (table, index, view or
89339 ** trigger). All names are legal except those that begin with the string
89340 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
89341 ** is reserved for internal use.
89342 */
89343 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
89344   if( !pParse->db->init.busy && pParse->nested==0
89345           && (pParse->db->flags & SQLITE_WriteSchema)==0
89346           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
89347     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
89348     return SQLITE_ERROR;
89349   }
89350   return SQLITE_OK;
89351 }
89352 
89353 /*
89354 ** Return the PRIMARY KEY index of a table
89355 */
89356 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
89357   Index *p;
89358   for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
89359   return p;
89360 }
89361 
89362 /*
89363 ** Return the column of index pIdx that corresponds to table
89364 ** column iCol.  Return -1 if not found.
89365 */
89366 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
89367   int i;
89368   for(i=0; i<pIdx->nColumn; i++){
89369     if( iCol==pIdx->aiColumn[i] ) return i;
89370   }
89371   return -1;
89372 }
89373 
89374 /*
89375 ** Begin constructing a new table representation in memory.  This is
89376 ** the first of several action routines that get called in response
89377 ** to a CREATE TABLE statement.  In particular, this routine is called
89378 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
89379 ** flag is true if the table should be stored in the auxiliary database
89380 ** file instead of in the main database file.  This is normally the case
89381 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
89382 ** CREATE and TABLE.
89383 **
89384 ** The new table record is initialized and put in pParse->pNewTable.
89385 ** As more of the CREATE TABLE statement is parsed, additional action
89386 ** routines will be called to add more information to this record.
89387 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
89388 ** is called to complete the construction of the new table record.
89389 */
89390 SQLITE_PRIVATE void sqlite3StartTable(
89391   Parse *pParse,   /* Parser context */
89392   Token *pName1,   /* First part of the name of the table or view */
89393   Token *pName2,   /* Second part of the name of the table or view */
89394   int isTemp,      /* True if this is a TEMP table */
89395   int isView,      /* True if this is a VIEW */
89396   int isVirtual,   /* True if this is a VIRTUAL table */
89397   int noErr        /* Do nothing if table already exists */
89398 ){
89399   Table *pTable;
89400   char *zName = 0; /* The name of the new table */
89401   sqlite3 *db = pParse->db;
89402   Vdbe *v;
89403   int iDb;         /* Database number to create the table in */
89404   Token *pName;    /* Unqualified name of the table to create */
89405 
89406   /* The table or view name to create is passed to this routine via tokens
89407   ** pName1 and pName2. If the table name was fully qualified, for example:
89408   **
89409   ** CREATE TABLE xxx.yyy (...);
89410   **
89411   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
89412   ** the table name is not fully qualified, i.e.:
89413   **
89414   ** CREATE TABLE yyy(...);
89415   **
89416   ** Then pName1 is set to "yyy" and pName2 is "".
89417   **
89418   ** The call below sets the pName pointer to point at the token (pName1 or
89419   ** pName2) that stores the unqualified table name. The variable iDb is
89420   ** set to the index of the database that the table or view is to be
89421   ** created in.
89422   */
89423   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
89424   if( iDb<0 ) return;
89425   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
89426     /* If creating a temp table, the name may not be qualified. Unless
89427     ** the database name is "temp" anyway.  */
89428     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
89429     return;
89430   }
89431   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
89432 
89433   pParse->sNameToken = *pName;
89434   zName = sqlite3NameFromToken(db, pName);
89435   if( zName==0 ) return;
89436   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
89437     goto begin_table_error;
89438   }
89439   if( db->init.iDb==1 ) isTemp = 1;
89440 #ifndef SQLITE_OMIT_AUTHORIZATION
89441   assert( (isTemp & 1)==isTemp );
89442   {
89443     int code;
89444     char *zDb = db->aDb[iDb].zName;
89445     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
89446       goto begin_table_error;
89447     }
89448     if( isView ){
89449       if( !OMIT_TEMPDB && isTemp ){
89450         code = SQLITE_CREATE_TEMP_VIEW;
89451       }else{
89452         code = SQLITE_CREATE_VIEW;
89453       }
89454     }else{
89455       if( !OMIT_TEMPDB && isTemp ){
89456         code = SQLITE_CREATE_TEMP_TABLE;
89457       }else{
89458         code = SQLITE_CREATE_TABLE;
89459       }
89460     }
89461     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
89462       goto begin_table_error;
89463     }
89464   }
89465 #endif
89466 
89467   /* Make sure the new table name does not collide with an existing
89468   ** index or table name in the same database.  Issue an error message if
89469   ** it does. The exception is if the statement being parsed was passed
89470   ** to an sqlite3_declare_vtab() call. In that case only the column names
89471   ** and types will be used, so there is no need to test for namespace
89472   ** collisions.
89473   */
89474   if( !IN_DECLARE_VTAB ){
89475     char *zDb = db->aDb[iDb].zName;
89476     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
89477       goto begin_table_error;
89478     }
89479     pTable = sqlite3FindTable(db, zName, zDb);
89480     if( pTable ){
89481       if( !noErr ){
89482         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
89483       }else{
89484         assert( !db->init.busy );
89485         sqlite3CodeVerifySchema(pParse, iDb);
89486       }
89487       goto begin_table_error;
89488     }
89489     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
89490       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
89491       goto begin_table_error;
89492     }
89493   }
89494 
89495   pTable = sqlite3DbMallocZero(db, sizeof(Table));
89496   if( pTable==0 ){
89497     db->mallocFailed = 1;
89498     pParse->rc = SQLITE_NOMEM;
89499     pParse->nErr++;
89500     goto begin_table_error;
89501   }
89502   pTable->zName = zName;
89503   pTable->iPKey = -1;
89504   pTable->pSchema = db->aDb[iDb].pSchema;
89505   pTable->nRef = 1;
89506   pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
89507   assert( pParse->pNewTable==0 );
89508   pParse->pNewTable = pTable;
89509 
89510   /* If this is the magic sqlite_sequence table used by autoincrement,
89511   ** then record a pointer to this table in the main database structure
89512   ** so that INSERT can find the table easily.
89513   */
89514 #ifndef SQLITE_OMIT_AUTOINCREMENT
89515   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
89516     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89517     pTable->pSchema->pSeqTab = pTable;
89518   }
89519 #endif
89520 
89521   /* Begin generating the code that will insert the table record into
89522   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
89523   ** and allocate the record number for the table entry now.  Before any
89524   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
89525   ** indices to be created and the table record must come before the
89526   ** indices.  Hence, the record number for the table must be allocated
89527   ** now.
89528   */
89529   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
89530     int j1;
89531     int fileFormat;
89532     int reg1, reg2, reg3;
89533     sqlite3BeginWriteOperation(pParse, 0, iDb);
89534 
89535 #ifndef SQLITE_OMIT_VIRTUALTABLE
89536     if( isVirtual ){
89537       sqlite3VdbeAddOp0(v, OP_VBegin);
89538     }
89539 #endif
89540 
89541     /* If the file format and encoding in the database have not been set,
89542     ** set them now.
89543     */
89544     reg1 = pParse->regRowid = ++pParse->nMem;
89545     reg2 = pParse->regRoot = ++pParse->nMem;
89546     reg3 = ++pParse->nMem;
89547     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
89548     sqlite3VdbeUsesBtree(v, iDb);
89549     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
89550     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
89551                   1 : SQLITE_MAX_FILE_FORMAT;
89552     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
89553     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
89554     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
89555     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
89556     sqlite3VdbeJumpHere(v, j1);
89557 
89558     /* This just creates a place-holder record in the sqlite_master table.
89559     ** The record created does not contain anything yet.  It will be replaced
89560     ** by the real entry in code generated at sqlite3EndTable().
89561     **
89562     ** The rowid for the new entry is left in register pParse->regRowid.
89563     ** The root page number of the new table is left in reg pParse->regRoot.
89564     ** The rowid and root page number values are needed by the code that
89565     ** sqlite3EndTable will generate.
89566     */
89567 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
89568     if( isView || isVirtual ){
89569       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
89570     }else
89571 #endif
89572     {
89573       pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
89574     }
89575     sqlite3OpenMasterTable(pParse, iDb);
89576     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
89577     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
89578     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
89579     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
89580     sqlite3VdbeAddOp0(v, OP_Close);
89581   }
89582 
89583   /* Normal (non-error) return. */
89584   return;
89585 
89586   /* If an error occurs, we jump here */
89587 begin_table_error:
89588   sqlite3DbFree(db, zName);
89589   return;
89590 }
89591 
89592 /*
89593 ** This macro is used to compare two strings in a case-insensitive manner.
89594 ** It is slightly faster than calling sqlite3StrICmp() directly, but
89595 ** produces larger code.
89596 **
89597 ** WARNING: This macro is not compatible with the strcmp() family. It
89598 ** returns true if the two strings are equal, otherwise false.
89599 */
89600 #define STRICMP(x, y) (\
89601 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
89602 sqlite3UpperToLower[*(unsigned char *)(y)]     \
89603 && sqlite3StrICmp((x)+1,(y)+1)==0 )
89604 
89605 /*
89606 ** Add a new column to the table currently being constructed.
89607 **
89608 ** The parser calls this routine once for each column declaration
89609 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
89610 ** first to get things going.  Then this routine is called for each
89611 ** column.
89612 */
89613 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
89614   Table *p;
89615   int i;
89616   char *z;
89617   Column *pCol;
89618   sqlite3 *db = pParse->db;
89619   if( (p = pParse->pNewTable)==0 ) return;
89620 #if SQLITE_MAX_COLUMN
89621   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
89622     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
89623     return;
89624   }
89625 #endif
89626   z = sqlite3NameFromToken(db, pName);
89627   if( z==0 ) return;
89628   for(i=0; i<p->nCol; i++){
89629     if( STRICMP(z, p->aCol[i].zName) ){
89630       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
89631       sqlite3DbFree(db, z);
89632       return;
89633     }
89634   }
89635   if( (p->nCol & 0x7)==0 ){
89636     Column *aNew;
89637     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
89638     if( aNew==0 ){
89639       sqlite3DbFree(db, z);
89640       return;
89641     }
89642     p->aCol = aNew;
89643   }
89644   pCol = &p->aCol[p->nCol];
89645   memset(pCol, 0, sizeof(p->aCol[0]));
89646   pCol->zName = z;
89647 
89648   /* If there is no type specified, columns have the default affinity
89649   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
89650   ** be called next to set pCol->affinity correctly.
89651   */
89652   pCol->affinity = SQLITE_AFF_NONE;
89653   pCol->szEst = 1;
89654   p->nCol++;
89655 }
89656 
89657 /*
89658 ** This routine is called by the parser while in the middle of
89659 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
89660 ** been seen on a column.  This routine sets the notNull flag on
89661 ** the column currently under construction.
89662 */
89663 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
89664   Table *p;
89665   p = pParse->pNewTable;
89666   if( p==0 || NEVER(p->nCol<1) ) return;
89667   p->aCol[p->nCol-1].notNull = (u8)onError;
89668 }
89669 
89670 /*
89671 ** Scan the column type name zType (length nType) and return the
89672 ** associated affinity type.
89673 **
89674 ** This routine does a case-independent search of zType for the
89675 ** substrings in the following table. If one of the substrings is
89676 ** found, the corresponding affinity is returned. If zType contains
89677 ** more than one of the substrings, entries toward the top of
89678 ** the table take priority. For example, if zType is 'BLOBINT',
89679 ** SQLITE_AFF_INTEGER is returned.
89680 **
89681 ** Substring     | Affinity
89682 ** --------------------------------
89683 ** 'INT'         | SQLITE_AFF_INTEGER
89684 ** 'CHAR'        | SQLITE_AFF_TEXT
89685 ** 'CLOB'        | SQLITE_AFF_TEXT
89686 ** 'TEXT'        | SQLITE_AFF_TEXT
89687 ** 'BLOB'        | SQLITE_AFF_NONE
89688 ** 'REAL'        | SQLITE_AFF_REAL
89689 ** 'FLOA'        | SQLITE_AFF_REAL
89690 ** 'DOUB'        | SQLITE_AFF_REAL
89691 **
89692 ** If none of the substrings in the above table are found,
89693 ** SQLITE_AFF_NUMERIC is returned.
89694 */
89695 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
89696   u32 h = 0;
89697   char aff = SQLITE_AFF_NUMERIC;
89698   const char *zChar = 0;
89699 
89700   if( zIn==0 ) return aff;
89701   while( zIn[0] ){
89702     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
89703     zIn++;
89704     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
89705       aff = SQLITE_AFF_TEXT;
89706       zChar = zIn;
89707     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
89708       aff = SQLITE_AFF_TEXT;
89709     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
89710       aff = SQLITE_AFF_TEXT;
89711     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
89712         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
89713       aff = SQLITE_AFF_NONE;
89714       if( zIn[0]=='(' ) zChar = zIn;
89715 #ifndef SQLITE_OMIT_FLOATING_POINT
89716     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
89717         && aff==SQLITE_AFF_NUMERIC ){
89718       aff = SQLITE_AFF_REAL;
89719     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
89720         && aff==SQLITE_AFF_NUMERIC ){
89721       aff = SQLITE_AFF_REAL;
89722     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
89723         && aff==SQLITE_AFF_NUMERIC ){
89724       aff = SQLITE_AFF_REAL;
89725 #endif
89726     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
89727       aff = SQLITE_AFF_INTEGER;
89728       break;
89729     }
89730   }
89731 
89732   /* If pszEst is not NULL, store an estimate of the field size.  The
89733   ** estimate is scaled so that the size of an integer is 1.  */
89734   if( pszEst ){
89735     *pszEst = 1;   /* default size is approx 4 bytes */
89736     if( aff<SQLITE_AFF_NUMERIC ){
89737       if( zChar ){
89738         while( zChar[0] ){
89739           if( sqlite3Isdigit(zChar[0]) ){
89740             int v = 0;
89741             sqlite3GetInt32(zChar, &v);
89742             v = v/4 + 1;
89743             if( v>255 ) v = 255;
89744             *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
89745             break;
89746           }
89747           zChar++;
89748         }
89749       }else{
89750         *pszEst = 5;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
89751       }
89752     }
89753   }
89754   return aff;
89755 }
89756 
89757 /*
89758 ** This routine is called by the parser while in the middle of
89759 ** parsing a CREATE TABLE statement.  The pFirst token is the first
89760 ** token in the sequence of tokens that describe the type of the
89761 ** column currently under construction.   pLast is the last token
89762 ** in the sequence.  Use this information to construct a string
89763 ** that contains the typename of the column and store that string
89764 ** in zType.
89765 */
89766 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
89767   Table *p;
89768   Column *pCol;
89769 
89770   p = pParse->pNewTable;
89771   if( p==0 || NEVER(p->nCol<1) ) return;
89772   pCol = &p->aCol[p->nCol-1];
89773   assert( pCol->zType==0 );
89774   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
89775   pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
89776 }
89777 
89778 /*
89779 ** The expression is the default value for the most recently added column
89780 ** of the table currently under construction.
89781 **
89782 ** Default value expressions must be constant.  Raise an exception if this
89783 ** is not the case.
89784 **
89785 ** This routine is called by the parser while in the middle of
89786 ** parsing a CREATE TABLE statement.
89787 */
89788 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
89789   Table *p;
89790   Column *pCol;
89791   sqlite3 *db = pParse->db;
89792   p = pParse->pNewTable;
89793   if( p!=0 ){
89794     pCol = &(p->aCol[p->nCol-1]);
89795     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
89796       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
89797           pCol->zName);
89798     }else{
89799       /* A copy of pExpr is used instead of the original, as pExpr contains
89800       ** tokens that point to volatile memory. The 'span' of the expression
89801       ** is required by pragma table_info.
89802       */
89803       sqlite3ExprDelete(db, pCol->pDflt);
89804       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
89805       sqlite3DbFree(db, pCol->zDflt);
89806       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
89807                                      (int)(pSpan->zEnd - pSpan->zStart));
89808     }
89809   }
89810   sqlite3ExprDelete(db, pSpan->pExpr);
89811 }
89812 
89813 /*
89814 ** Designate the PRIMARY KEY for the table.  pList is a list of names
89815 ** of columns that form the primary key.  If pList is NULL, then the
89816 ** most recently added column of the table is the primary key.
89817 **
89818 ** A table can have at most one primary key.  If the table already has
89819 ** a primary key (and this is the second primary key) then create an
89820 ** error.
89821 **
89822 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
89823 ** then we will try to use that column as the rowid.  Set the Table.iPKey
89824 ** field of the table under construction to be the index of the
89825 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
89826 ** no INTEGER PRIMARY KEY.
89827 **
89828 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
89829 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
89830 */
89831 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
89832   Parse *pParse,    /* Parsing context */
89833   ExprList *pList,  /* List of field names to be indexed */
89834   int onError,      /* What to do with a uniqueness conflict */
89835   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
89836   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
89837 ){
89838   Table *pTab = pParse->pNewTable;
89839   char *zType = 0;
89840   int iCol = -1, i;
89841   int nTerm;
89842   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
89843   if( pTab->tabFlags & TF_HasPrimaryKey ){
89844     sqlite3ErrorMsg(pParse,
89845       "table \"%s\" has more than one primary key", pTab->zName);
89846     goto primary_key_exit;
89847   }
89848   pTab->tabFlags |= TF_HasPrimaryKey;
89849   if( pList==0 ){
89850     iCol = pTab->nCol - 1;
89851     pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
89852     zType = pTab->aCol[iCol].zType;
89853     nTerm = 1;
89854   }else{
89855     nTerm = pList->nExpr;
89856     for(i=0; i<nTerm; i++){
89857       for(iCol=0; iCol<pTab->nCol; iCol++){
89858         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
89859           pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
89860           zType = pTab->aCol[iCol].zType;
89861           break;
89862         }
89863       }
89864     }
89865   }
89866   if( nTerm==1
89867    && zType && sqlite3StrICmp(zType, "INTEGER")==0
89868    && sortOrder==SQLITE_SO_ASC
89869   ){
89870     pTab->iPKey = iCol;
89871     pTab->keyConf = (u8)onError;
89872     assert( autoInc==0 || autoInc==1 );
89873     pTab->tabFlags |= autoInc*TF_Autoincrement;
89874     if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
89875   }else if( autoInc ){
89876 #ifndef SQLITE_OMIT_AUTOINCREMENT
89877     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
89878        "INTEGER PRIMARY KEY");
89879 #endif
89880   }else{
89881     Vdbe *v = pParse->pVdbe;
89882     Index *p;
89883     if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
89884     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
89885                            0, sortOrder, 0);
89886     if( p ){
89887       p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
89888       if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
89889     }
89890     pList = 0;
89891   }
89892 
89893 primary_key_exit:
89894   sqlite3ExprListDelete(pParse->db, pList);
89895   return;
89896 }
89897 
89898 /*
89899 ** Add a new CHECK constraint to the table currently under construction.
89900 */
89901 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
89902   Parse *pParse,    /* Parsing context */
89903   Expr *pCheckExpr  /* The check expression */
89904 ){
89905 #ifndef SQLITE_OMIT_CHECK
89906   Table *pTab = pParse->pNewTable;
89907   sqlite3 *db = pParse->db;
89908   if( pTab && !IN_DECLARE_VTAB
89909    && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
89910   ){
89911     pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
89912     if( pParse->constraintName.n ){
89913       sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
89914     }
89915   }else
89916 #endif
89917   {
89918     sqlite3ExprDelete(pParse->db, pCheckExpr);
89919   }
89920 }
89921 
89922 /*
89923 ** Set the collation function of the most recently parsed table column
89924 ** to the CollSeq given.
89925 */
89926 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
89927   Table *p;
89928   int i;
89929   char *zColl;              /* Dequoted name of collation sequence */
89930   sqlite3 *db;
89931 
89932   if( (p = pParse->pNewTable)==0 ) return;
89933   i = p->nCol-1;
89934   db = pParse->db;
89935   zColl = sqlite3NameFromToken(db, pToken);
89936   if( !zColl ) return;
89937 
89938   if( sqlite3LocateCollSeq(pParse, zColl) ){
89939     Index *pIdx;
89940     sqlite3DbFree(db, p->aCol[i].zColl);
89941     p->aCol[i].zColl = zColl;
89942 
89943     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
89944     ** then an index may have been created on this column before the
89945     ** collation type was added. Correct this if it is the case.
89946     */
89947     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
89948       assert( pIdx->nKeyCol==1 );
89949       if( pIdx->aiColumn[0]==i ){
89950         pIdx->azColl[0] = p->aCol[i].zColl;
89951       }
89952     }
89953   }else{
89954     sqlite3DbFree(db, zColl);
89955   }
89956 }
89957 
89958 /*
89959 ** This function returns the collation sequence for database native text
89960 ** encoding identified by the string zName, length nName.
89961 **
89962 ** If the requested collation sequence is not available, or not available
89963 ** in the database native encoding, the collation factory is invoked to
89964 ** request it. If the collation factory does not supply such a sequence,
89965 ** and the sequence is available in another text encoding, then that is
89966 ** returned instead.
89967 **
89968 ** If no versions of the requested collations sequence are available, or
89969 ** another error occurs, NULL is returned and an error message written into
89970 ** pParse.
89971 **
89972 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
89973 ** invokes the collation factory if the named collation cannot be found
89974 ** and generates an error message.
89975 **
89976 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
89977 */
89978 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
89979   sqlite3 *db = pParse->db;
89980   u8 enc = ENC(db);
89981   u8 initbusy = db->init.busy;
89982   CollSeq *pColl;
89983 
89984   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
89985   if( !initbusy && (!pColl || !pColl->xCmp) ){
89986     pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
89987   }
89988 
89989   return pColl;
89990 }
89991 
89992 
89993 /*
89994 ** Generate code that will increment the schema cookie.
89995 **
89996 ** The schema cookie is used to determine when the schema for the
89997 ** database changes.  After each schema change, the cookie value
89998 ** changes.  When a process first reads the schema it records the
89999 ** cookie.  Thereafter, whenever it goes to access the database,
90000 ** it checks the cookie to make sure the schema has not changed
90001 ** since it was last read.
90002 **
90003 ** This plan is not completely bullet-proof.  It is possible for
90004 ** the schema to change multiple times and for the cookie to be
90005 ** set back to prior value.  But schema changes are infrequent
90006 ** and the probability of hitting the same cookie value is only
90007 ** 1 chance in 2^32.  So we're safe enough.
90008 */
90009 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
90010   int r1 = sqlite3GetTempReg(pParse);
90011   sqlite3 *db = pParse->db;
90012   Vdbe *v = pParse->pVdbe;
90013   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
90014   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
90015   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
90016   sqlite3ReleaseTempReg(pParse, r1);
90017 }
90018 
90019 /*
90020 ** Measure the number of characters needed to output the given
90021 ** identifier.  The number returned includes any quotes used
90022 ** but does not include the null terminator.
90023 **
90024 ** The estimate is conservative.  It might be larger that what is
90025 ** really needed.
90026 */
90027 static int identLength(const char *z){
90028   int n;
90029   for(n=0; *z; n++, z++){
90030     if( *z=='"' ){ n++; }
90031   }
90032   return n + 2;
90033 }
90034 
90035 /*
90036 ** The first parameter is a pointer to an output buffer. The second
90037 ** parameter is a pointer to an integer that contains the offset at
90038 ** which to write into the output buffer. This function copies the
90039 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
90040 ** to the specified offset in the buffer and updates *pIdx to refer
90041 ** to the first byte after the last byte written before returning.
90042 **
90043 ** If the string zSignedIdent consists entirely of alpha-numeric
90044 ** characters, does not begin with a digit and is not an SQL keyword,
90045 ** then it is copied to the output buffer exactly as it is. Otherwise,
90046 ** it is quoted using double-quotes.
90047 */
90048 static void identPut(char *z, int *pIdx, char *zSignedIdent){
90049   unsigned char *zIdent = (unsigned char*)zSignedIdent;
90050   int i, j, needQuote;
90051   i = *pIdx;
90052 
90053   for(j=0; zIdent[j]; j++){
90054     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
90055   }
90056   needQuote = sqlite3Isdigit(zIdent[0])
90057             || sqlite3KeywordCode(zIdent, j)!=TK_ID
90058             || zIdent[j]!=0
90059             || j==0;
90060 
90061   if( needQuote ) z[i++] = '"';
90062   for(j=0; zIdent[j]; j++){
90063     z[i++] = zIdent[j];
90064     if( zIdent[j]=='"' ) z[i++] = '"';
90065   }
90066   if( needQuote ) z[i++] = '"';
90067   z[i] = 0;
90068   *pIdx = i;
90069 }
90070 
90071 /*
90072 ** Generate a CREATE TABLE statement appropriate for the given
90073 ** table.  Memory to hold the text of the statement is obtained
90074 ** from sqliteMalloc() and must be freed by the calling function.
90075 */
90076 static char *createTableStmt(sqlite3 *db, Table *p){
90077   int i, k, n;
90078   char *zStmt;
90079   char *zSep, *zSep2, *zEnd;
90080   Column *pCol;
90081   n = 0;
90082   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
90083     n += identLength(pCol->zName) + 5;
90084   }
90085   n += identLength(p->zName);
90086   if( n<50 ){
90087     zSep = "";
90088     zSep2 = ",";
90089     zEnd = ")";
90090   }else{
90091     zSep = "\n  ";
90092     zSep2 = ",\n  ";
90093     zEnd = "\n)";
90094   }
90095   n += 35 + 6*p->nCol;
90096   zStmt = sqlite3DbMallocRaw(0, n);
90097   if( zStmt==0 ){
90098     db->mallocFailed = 1;
90099     return 0;
90100   }
90101   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
90102   k = sqlite3Strlen30(zStmt);
90103   identPut(zStmt, &k, p->zName);
90104   zStmt[k++] = '(';
90105   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
90106     static const char * const azType[] = {
90107         /* SQLITE_AFF_NONE    */ "",
90108         /* SQLITE_AFF_TEXT    */ " TEXT",
90109         /* SQLITE_AFF_NUMERIC */ " NUM",
90110         /* SQLITE_AFF_INTEGER */ " INT",
90111         /* SQLITE_AFF_REAL    */ " REAL"
90112     };
90113     int len;
90114     const char *zType;
90115 
90116     sqlite3_snprintf(n-k, &zStmt[k], zSep);
90117     k += sqlite3Strlen30(&zStmt[k]);
90118     zSep = zSep2;
90119     identPut(zStmt, &k, pCol->zName);
90120     assert( pCol->affinity-SQLITE_AFF_NONE >= 0 );
90121     assert( pCol->affinity-SQLITE_AFF_NONE < ArraySize(azType) );
90122     testcase( pCol->affinity==SQLITE_AFF_NONE );
90123     testcase( pCol->affinity==SQLITE_AFF_TEXT );
90124     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
90125     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
90126     testcase( pCol->affinity==SQLITE_AFF_REAL );
90127 
90128     zType = azType[pCol->affinity - SQLITE_AFF_NONE];
90129     len = sqlite3Strlen30(zType);
90130     assert( pCol->affinity==SQLITE_AFF_NONE
90131             || pCol->affinity==sqlite3AffinityType(zType, 0) );
90132     memcpy(&zStmt[k], zType, len);
90133     k += len;
90134     assert( k<=n );
90135   }
90136   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
90137   return zStmt;
90138 }
90139 
90140 /*
90141 ** Resize an Index object to hold N columns total.  Return SQLITE_OK
90142 ** on success and SQLITE_NOMEM on an OOM error.
90143 */
90144 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
90145   char *zExtra;
90146   int nByte;
90147   if( pIdx->nColumn>=N ) return SQLITE_OK;
90148   assert( pIdx->isResized==0 );
90149   nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
90150   zExtra = sqlite3DbMallocZero(db, nByte);
90151   if( zExtra==0 ) return SQLITE_NOMEM;
90152   memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
90153   pIdx->azColl = (char**)zExtra;
90154   zExtra += sizeof(char*)*N;
90155   memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
90156   pIdx->aiColumn = (i16*)zExtra;
90157   zExtra += sizeof(i16)*N;
90158   memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
90159   pIdx->aSortOrder = (u8*)zExtra;
90160   pIdx->nColumn = N;
90161   pIdx->isResized = 1;
90162   return SQLITE_OK;
90163 }
90164 
90165 /*
90166 ** Estimate the total row width for a table.
90167 */
90168 static void estimateTableWidth(Table *pTab){
90169   unsigned wTable = 0;
90170   const Column *pTabCol;
90171   int i;
90172   for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
90173     wTable += pTabCol->szEst;
90174   }
90175   if( pTab->iPKey<0 ) wTable++;
90176   pTab->szTabRow = sqlite3LogEst(wTable*4);
90177 }
90178 
90179 /*
90180 ** Estimate the average size of a row for an index.
90181 */
90182 static void estimateIndexWidth(Index *pIdx){
90183   unsigned wIndex = 0;
90184   int i;
90185   const Column *aCol = pIdx->pTable->aCol;
90186   for(i=0; i<pIdx->nColumn; i++){
90187     i16 x = pIdx->aiColumn[i];
90188     assert( x<pIdx->pTable->nCol );
90189     wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
90190   }
90191   pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
90192 }
90193 
90194 /* Return true if value x is found any of the first nCol entries of aiCol[]
90195 */
90196 static int hasColumn(const i16 *aiCol, int nCol, int x){
90197   while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
90198   return 0;
90199 }
90200 
90201 /*
90202 ** This routine runs at the end of parsing a CREATE TABLE statement that
90203 ** has a WITHOUT ROWID clause.  The job of this routine is to convert both
90204 ** internal schema data structures and the generated VDBE code so that they
90205 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
90206 ** Changes include:
90207 **
90208 **     (1)  Convert the OP_CreateTable into an OP_CreateIndex.  There is
90209 **          no rowid btree for a WITHOUT ROWID.  Instead, the canonical
90210 **          data storage is a covering index btree.
90211 **     (2)  Bypass the creation of the sqlite_master table entry
90212 **          for the PRIMARY KEY as the primary key index is now
90213 **          identified by the sqlite_master table entry of the table itself.
90214 **     (3)  Set the Index.tnum of the PRIMARY KEY Index object in the
90215 **          schema to the rootpage from the main table.
90216 **     (4)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
90217 **     (5)  Add all table columns to the PRIMARY KEY Index object
90218 **          so that the PRIMARY KEY is a covering index.  The surplus
90219 **          columns are part of KeyInfo.nXField and are not used for
90220 **          sorting or lookup or uniqueness checks.
90221 **     (6)  Replace the rowid tail on all automatically generated UNIQUE
90222 **          indices with the PRIMARY KEY columns.
90223 */
90224 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
90225   Index *pIdx;
90226   Index *pPk;
90227   int nPk;
90228   int i, j;
90229   sqlite3 *db = pParse->db;
90230   Vdbe *v = pParse->pVdbe;
90231 
90232   /* Convert the OP_CreateTable opcode that would normally create the
90233   ** root-page for the table into an OP_CreateIndex opcode.  The index
90234   ** created will become the PRIMARY KEY index.
90235   */
90236   if( pParse->addrCrTab ){
90237     assert( v );
90238     sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
90239   }
90240 
90241   /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
90242   ** table entry.
90243   */
90244   if( pParse->addrSkipPK ){
90245     assert( v );
90246     sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
90247   }
90248 
90249   /* Locate the PRIMARY KEY index.  Or, if this table was originally
90250   ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
90251   */
90252   if( pTab->iPKey>=0 ){
90253     ExprList *pList;
90254     pList = sqlite3ExprListAppend(pParse, 0, 0);
90255     if( pList==0 ) return;
90256     pList->a[0].zName = sqlite3DbStrDup(pParse->db,
90257                                         pTab->aCol[pTab->iPKey].zName);
90258     pList->a[0].sortOrder = pParse->iPkSortOrder;
90259     assert( pParse->pNewTable==pTab );
90260     pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
90261     if( pPk==0 ) return;
90262     pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
90263     pTab->iPKey = -1;
90264   }else{
90265     pPk = sqlite3PrimaryKeyIndex(pTab);
90266   }
90267   pPk->isCovering = 1;
90268   assert( pPk!=0 );
90269   nPk = pPk->nKeyCol;
90270 
90271   /* Make sure every column of the PRIMARY KEY is NOT NULL */
90272   for(i=0; i<nPk; i++){
90273     pTab->aCol[pPk->aiColumn[i]].notNull = 1;
90274   }
90275   pPk->uniqNotNull = 1;
90276 
90277   /* The root page of the PRIMARY KEY is the table root page */
90278   pPk->tnum = pTab->tnum;
90279 
90280   /* Update the in-memory representation of all UNIQUE indices by converting
90281   ** the final rowid column into one or more columns of the PRIMARY KEY.
90282   */
90283   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
90284     int n;
90285     if( IsPrimaryKeyIndex(pIdx) ) continue;
90286     for(i=n=0; i<nPk; i++){
90287       if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
90288     }
90289     if( n==0 ){
90290       /* This index is a superset of the primary key */
90291       pIdx->nColumn = pIdx->nKeyCol;
90292       continue;
90293     }
90294     if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
90295     for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
90296       if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
90297         pIdx->aiColumn[j] = pPk->aiColumn[i];
90298         pIdx->azColl[j] = pPk->azColl[i];
90299         j++;
90300       }
90301     }
90302     assert( pIdx->nColumn>=pIdx->nKeyCol+n );
90303     assert( pIdx->nColumn>=j );
90304   }
90305 
90306   /* Add all table columns to the PRIMARY KEY index
90307   */
90308   if( nPk<pTab->nCol ){
90309     if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
90310     for(i=0, j=nPk; i<pTab->nCol; i++){
90311       if( !hasColumn(pPk->aiColumn, j, i) ){
90312         assert( j<pPk->nColumn );
90313         pPk->aiColumn[j] = i;
90314         pPk->azColl[j] = "BINARY";
90315         j++;
90316       }
90317     }
90318     assert( pPk->nColumn==j );
90319     assert( pTab->nCol==j );
90320   }else{
90321     pPk->nColumn = pTab->nCol;
90322   }
90323 }
90324 
90325 /*
90326 ** This routine is called to report the final ")" that terminates
90327 ** a CREATE TABLE statement.
90328 **
90329 ** The table structure that other action routines have been building
90330 ** is added to the internal hash tables, assuming no errors have
90331 ** occurred.
90332 **
90333 ** An entry for the table is made in the master table on disk, unless
90334 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
90335 ** it means we are reading the sqlite_master table because we just
90336 ** connected to the database or because the sqlite_master table has
90337 ** recently changed, so the entry for this table already exists in
90338 ** the sqlite_master table.  We do not want to create it again.
90339 **
90340 ** If the pSelect argument is not NULL, it means that this routine
90341 ** was called to create a table generated from a
90342 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
90343 ** the new table will match the result set of the SELECT.
90344 */
90345 SQLITE_PRIVATE void sqlite3EndTable(
90346   Parse *pParse,          /* Parse context */
90347   Token *pCons,           /* The ',' token after the last column defn. */
90348   Token *pEnd,            /* The ')' before options in the CREATE TABLE */
90349   u8 tabOpts,             /* Extra table options. Usually 0. */
90350   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
90351 ){
90352   Table *p;                 /* The new table */
90353   sqlite3 *db = pParse->db; /* The database connection */
90354   int iDb;                  /* Database in which the table lives */
90355   Index *pIdx;              /* An implied index of the table */
90356 
90357   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
90358     return;
90359   }
90360   p = pParse->pNewTable;
90361   if( p==0 ) return;
90362 
90363   assert( !db->init.busy || !pSelect );
90364 
90365   /* If the db->init.busy is 1 it means we are reading the SQL off the
90366   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
90367   ** So do not write to the disk again.  Extract the root page number
90368   ** for the table from the db->init.newTnum field.  (The page number
90369   ** should have been put there by the sqliteOpenCb routine.)
90370   */
90371   if( db->init.busy ){
90372     p->tnum = db->init.newTnum;
90373   }
90374 
90375   /* Special processing for WITHOUT ROWID Tables */
90376   if( tabOpts & TF_WithoutRowid ){
90377     if( (p->tabFlags & TF_Autoincrement) ){
90378       sqlite3ErrorMsg(pParse,
90379           "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
90380       return;
90381     }
90382     if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
90383       sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
90384     }else{
90385       p->tabFlags |= TF_WithoutRowid;
90386       convertToWithoutRowidTable(pParse, p);
90387     }
90388   }
90389 
90390   iDb = sqlite3SchemaToIndex(db, p->pSchema);
90391 
90392 #ifndef SQLITE_OMIT_CHECK
90393   /* Resolve names in all CHECK constraint expressions.
90394   */
90395   if( p->pCheck ){
90396     sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
90397   }
90398 #endif /* !defined(SQLITE_OMIT_CHECK) */
90399 
90400   /* Estimate the average row size for the table and for all implied indices */
90401   estimateTableWidth(p);
90402   for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
90403     estimateIndexWidth(pIdx);
90404   }
90405 
90406   /* If not initializing, then create a record for the new table
90407   ** in the SQLITE_MASTER table of the database.
90408   **
90409   ** If this is a TEMPORARY table, write the entry into the auxiliary
90410   ** file instead of into the main database file.
90411   */
90412   if( !db->init.busy ){
90413     int n;
90414     Vdbe *v;
90415     char *zType;    /* "view" or "table" */
90416     char *zType2;   /* "VIEW" or "TABLE" */
90417     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
90418 
90419     v = sqlite3GetVdbe(pParse);
90420     if( NEVER(v==0) ) return;
90421 
90422     sqlite3VdbeAddOp1(v, OP_Close, 0);
90423 
90424     /*
90425     ** Initialize zType for the new view or table.
90426     */
90427     if( p->pSelect==0 ){
90428       /* A regular table */
90429       zType = "table";
90430       zType2 = "TABLE";
90431 #ifndef SQLITE_OMIT_VIEW
90432     }else{
90433       /* A view */
90434       zType = "view";
90435       zType2 = "VIEW";
90436 #endif
90437     }
90438 
90439     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
90440     ** statement to populate the new table. The root-page number for the
90441     ** new table is in register pParse->regRoot.
90442     **
90443     ** Once the SELECT has been coded by sqlite3Select(), it is in a
90444     ** suitable state to query for the column names and types to be used
90445     ** by the new table.
90446     **
90447     ** A shared-cache write-lock is not required to write to the new table,
90448     ** as a schema-lock must have already been obtained to create it. Since
90449     ** a schema-lock excludes all other database users, the write-lock would
90450     ** be redundant.
90451     */
90452     if( pSelect ){
90453       SelectDest dest;
90454       Table *pSelTab;
90455 
90456       assert(pParse->nTab==1);
90457       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
90458       sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
90459       pParse->nTab = 2;
90460       sqlite3SelectDestInit(&dest, SRT_Table, 1);
90461       sqlite3Select(pParse, pSelect, &dest);
90462       sqlite3VdbeAddOp1(v, OP_Close, 1);
90463       if( pParse->nErr==0 ){
90464         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
90465         if( pSelTab==0 ) return;
90466         assert( p->aCol==0 );
90467         p->nCol = pSelTab->nCol;
90468         p->aCol = pSelTab->aCol;
90469         pSelTab->nCol = 0;
90470         pSelTab->aCol = 0;
90471         sqlite3DeleteTable(db, pSelTab);
90472       }
90473     }
90474 
90475     /* Compute the complete text of the CREATE statement */
90476     if( pSelect ){
90477       zStmt = createTableStmt(db, p);
90478     }else{
90479       Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
90480       n = (int)(pEnd2->z - pParse->sNameToken.z);
90481       if( pEnd2->z[0]!=';' ) n += pEnd2->n;
90482       zStmt = sqlite3MPrintf(db,
90483           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
90484       );
90485     }
90486 
90487     /* A slot for the record has already been allocated in the
90488     ** SQLITE_MASTER table.  We just need to update that slot with all
90489     ** the information we've collected.
90490     */
90491     sqlite3NestedParse(pParse,
90492       "UPDATE %Q.%s "
90493          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
90494        "WHERE rowid=#%d",
90495       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
90496       zType,
90497       p->zName,
90498       p->zName,
90499       pParse->regRoot,
90500       zStmt,
90501       pParse->regRowid
90502     );
90503     sqlite3DbFree(db, zStmt);
90504     sqlite3ChangeCookie(pParse, iDb);
90505 
90506 #ifndef SQLITE_OMIT_AUTOINCREMENT
90507     /* Check to see if we need to create an sqlite_sequence table for
90508     ** keeping track of autoincrement keys.
90509     */
90510     if( p->tabFlags & TF_Autoincrement ){
90511       Db *pDb = &db->aDb[iDb];
90512       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
90513       if( pDb->pSchema->pSeqTab==0 ){
90514         sqlite3NestedParse(pParse,
90515           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
90516           pDb->zName
90517         );
90518       }
90519     }
90520 #endif
90521 
90522     /* Reparse everything to update our internal data structures */
90523     sqlite3VdbeAddParseSchemaOp(v, iDb,
90524            sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
90525   }
90526 
90527 
90528   /* Add the table to the in-memory representation of the database.
90529   */
90530   if( db->init.busy ){
90531     Table *pOld;
90532     Schema *pSchema = p->pSchema;
90533     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
90534     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
90535     if( pOld ){
90536       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
90537       db->mallocFailed = 1;
90538       return;
90539     }
90540     pParse->pNewTable = 0;
90541     db->flags |= SQLITE_InternChanges;
90542 
90543 #ifndef SQLITE_OMIT_ALTERTABLE
90544     if( !p->pSelect ){
90545       const char *zName = (const char *)pParse->sNameToken.z;
90546       int nName;
90547       assert( !pSelect && pCons && pEnd );
90548       if( pCons->z==0 ){
90549         pCons = pEnd;
90550       }
90551       nName = (int)((const char *)pCons->z - zName);
90552       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
90553     }
90554 #endif
90555   }
90556 }
90557 
90558 #ifndef SQLITE_OMIT_VIEW
90559 /*
90560 ** The parser calls this routine in order to create a new VIEW
90561 */
90562 SQLITE_PRIVATE void sqlite3CreateView(
90563   Parse *pParse,     /* The parsing context */
90564   Token *pBegin,     /* The CREATE token that begins the statement */
90565   Token *pName1,     /* The token that holds the name of the view */
90566   Token *pName2,     /* The token that holds the name of the view */
90567   Select *pSelect,   /* A SELECT statement that will become the new view */
90568   int isTemp,        /* TRUE for a TEMPORARY view */
90569   int noErr          /* Suppress error messages if VIEW already exists */
90570 ){
90571   Table *p;
90572   int n;
90573   const char *z;
90574   Token sEnd;
90575   DbFixer sFix;
90576   Token *pName = 0;
90577   int iDb;
90578   sqlite3 *db = pParse->db;
90579 
90580   if( pParse->nVar>0 ){
90581     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
90582     sqlite3SelectDelete(db, pSelect);
90583     return;
90584   }
90585   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
90586   p = pParse->pNewTable;
90587   if( p==0 || pParse->nErr ){
90588     sqlite3SelectDelete(db, pSelect);
90589     return;
90590   }
90591   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
90592   iDb = sqlite3SchemaToIndex(db, p->pSchema);
90593   sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
90594   if( sqlite3FixSelect(&sFix, pSelect) ){
90595     sqlite3SelectDelete(db, pSelect);
90596     return;
90597   }
90598 
90599   /* Make a copy of the entire SELECT statement that defines the view.
90600   ** This will force all the Expr.token.z values to be dynamically
90601   ** allocated rather than point to the input string - which means that
90602   ** they will persist after the current sqlite3_exec() call returns.
90603   */
90604   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
90605   sqlite3SelectDelete(db, pSelect);
90606   if( db->mallocFailed ){
90607     return;
90608   }
90609   if( !db->init.busy ){
90610     sqlite3ViewGetColumnNames(pParse, p);
90611   }
90612 
90613   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
90614   ** the end.
90615   */
90616   sEnd = pParse->sLastToken;
90617   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
90618     sEnd.z += sEnd.n;
90619   }
90620   sEnd.n = 0;
90621   n = (int)(sEnd.z - pBegin->z);
90622   z = pBegin->z;
90623   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
90624   sEnd.z = &z[n-1];
90625   sEnd.n = 1;
90626 
90627   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
90628   sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
90629   return;
90630 }
90631 #endif /* SQLITE_OMIT_VIEW */
90632 
90633 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
90634 /*
90635 ** The Table structure pTable is really a VIEW.  Fill in the names of
90636 ** the columns of the view in the pTable structure.  Return the number
90637 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
90638 */
90639 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
90640   Table *pSelTab;   /* A fake table from which we get the result set */
90641   Select *pSel;     /* Copy of the SELECT that implements the view */
90642   int nErr = 0;     /* Number of errors encountered */
90643   int n;            /* Temporarily holds the number of cursors assigned */
90644   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
90645   sqlite3_xauth xAuth;       /* Saved xAuth pointer */
90646 
90647   assert( pTable );
90648 
90649 #ifndef SQLITE_OMIT_VIRTUALTABLE
90650   if( sqlite3VtabCallConnect(pParse, pTable) ){
90651     return SQLITE_ERROR;
90652   }
90653   if( IsVirtual(pTable) ) return 0;
90654 #endif
90655 
90656 #ifndef SQLITE_OMIT_VIEW
90657   /* A positive nCol means the columns names for this view are
90658   ** already known.
90659   */
90660   if( pTable->nCol>0 ) return 0;
90661 
90662   /* A negative nCol is a special marker meaning that we are currently
90663   ** trying to compute the column names.  If we enter this routine with
90664   ** a negative nCol, it means two or more views form a loop, like this:
90665   **
90666   **     CREATE VIEW one AS SELECT * FROM two;
90667   **     CREATE VIEW two AS SELECT * FROM one;
90668   **
90669   ** Actually, the error above is now caught prior to reaching this point.
90670   ** But the following test is still important as it does come up
90671   ** in the following:
90672   **
90673   **     CREATE TABLE main.ex1(a);
90674   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
90675   **     SELECT * FROM temp.ex1;
90676   */
90677   if( pTable->nCol<0 ){
90678     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
90679     return 1;
90680   }
90681   assert( pTable->nCol>=0 );
90682 
90683   /* If we get this far, it means we need to compute the table names.
90684   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
90685   ** "*" elements in the results set of the view and will assign cursors
90686   ** to the elements of the FROM clause.  But we do not want these changes
90687   ** to be permanent.  So the computation is done on a copy of the SELECT
90688   ** statement that defines the view.
90689   */
90690   assert( pTable->pSelect );
90691   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
90692   if( pSel ){
90693     u8 enableLookaside = db->lookaside.bEnabled;
90694     n = pParse->nTab;
90695     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
90696     pTable->nCol = -1;
90697     db->lookaside.bEnabled = 0;
90698 #ifndef SQLITE_OMIT_AUTHORIZATION
90699     xAuth = db->xAuth;
90700     db->xAuth = 0;
90701     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
90702     db->xAuth = xAuth;
90703 #else
90704     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
90705 #endif
90706     db->lookaside.bEnabled = enableLookaside;
90707     pParse->nTab = n;
90708     if( pSelTab ){
90709       assert( pTable->aCol==0 );
90710       pTable->nCol = pSelTab->nCol;
90711       pTable->aCol = pSelTab->aCol;
90712       pSelTab->nCol = 0;
90713       pSelTab->aCol = 0;
90714       sqlite3DeleteTable(db, pSelTab);
90715       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
90716       pTable->pSchema->schemaFlags |= DB_UnresetViews;
90717     }else{
90718       pTable->nCol = 0;
90719       nErr++;
90720     }
90721     sqlite3SelectDelete(db, pSel);
90722   } else {
90723     nErr++;
90724   }
90725 #endif /* SQLITE_OMIT_VIEW */
90726   return nErr;
90727 }
90728 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
90729 
90730 #ifndef SQLITE_OMIT_VIEW
90731 /*
90732 ** Clear the column names from every VIEW in database idx.
90733 */
90734 static void sqliteViewResetAll(sqlite3 *db, int idx){
90735   HashElem *i;
90736   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
90737   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
90738   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
90739     Table *pTab = sqliteHashData(i);
90740     if( pTab->pSelect ){
90741       sqliteDeleteColumnNames(db, pTab);
90742       pTab->aCol = 0;
90743       pTab->nCol = 0;
90744     }
90745   }
90746   DbClearProperty(db, idx, DB_UnresetViews);
90747 }
90748 #else
90749 # define sqliteViewResetAll(A,B)
90750 #endif /* SQLITE_OMIT_VIEW */
90751 
90752 /*
90753 ** This function is called by the VDBE to adjust the internal schema
90754 ** used by SQLite when the btree layer moves a table root page. The
90755 ** root-page of a table or index in database iDb has changed from iFrom
90756 ** to iTo.
90757 **
90758 ** Ticket #1728:  The symbol table might still contain information
90759 ** on tables and/or indices that are the process of being deleted.
90760 ** If you are unlucky, one of those deleted indices or tables might
90761 ** have the same rootpage number as the real table or index that is
90762 ** being moved.  So we cannot stop searching after the first match
90763 ** because the first match might be for one of the deleted indices
90764 ** or tables and not the table/index that is actually being moved.
90765 ** We must continue looping until all tables and indices with
90766 ** rootpage==iFrom have been converted to have a rootpage of iTo
90767 ** in order to be certain that we got the right one.
90768 */
90769 #ifndef SQLITE_OMIT_AUTOVACUUM
90770 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
90771   HashElem *pElem;
90772   Hash *pHash;
90773   Db *pDb;
90774 
90775   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
90776   pDb = &db->aDb[iDb];
90777   pHash = &pDb->pSchema->tblHash;
90778   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
90779     Table *pTab = sqliteHashData(pElem);
90780     if( pTab->tnum==iFrom ){
90781       pTab->tnum = iTo;
90782     }
90783   }
90784   pHash = &pDb->pSchema->idxHash;
90785   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
90786     Index *pIdx = sqliteHashData(pElem);
90787     if( pIdx->tnum==iFrom ){
90788       pIdx->tnum = iTo;
90789     }
90790   }
90791 }
90792 #endif
90793 
90794 /*
90795 ** Write code to erase the table with root-page iTable from database iDb.
90796 ** Also write code to modify the sqlite_master table and internal schema
90797 ** if a root-page of another table is moved by the btree-layer whilst
90798 ** erasing iTable (this can happen with an auto-vacuum database).
90799 */
90800 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
90801   Vdbe *v = sqlite3GetVdbe(pParse);
90802   int r1 = sqlite3GetTempReg(pParse);
90803   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
90804   sqlite3MayAbort(pParse);
90805 #ifndef SQLITE_OMIT_AUTOVACUUM
90806   /* OP_Destroy stores an in integer r1. If this integer
90807   ** is non-zero, then it is the root page number of a table moved to
90808   ** location iTable. The following code modifies the sqlite_master table to
90809   ** reflect this.
90810   **
90811   ** The "#NNN" in the SQL is a special constant that means whatever value
90812   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
90813   ** token for additional information.
90814   */
90815   sqlite3NestedParse(pParse,
90816      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
90817      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
90818 #endif
90819   sqlite3ReleaseTempReg(pParse, r1);
90820 }
90821 
90822 /*
90823 ** Write VDBE code to erase table pTab and all associated indices on disk.
90824 ** Code to update the sqlite_master tables and internal schema definitions
90825 ** in case a root-page belonging to another table is moved by the btree layer
90826 ** is also added (this can happen with an auto-vacuum database).
90827 */
90828 static void destroyTable(Parse *pParse, Table *pTab){
90829 #ifdef SQLITE_OMIT_AUTOVACUUM
90830   Index *pIdx;
90831   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
90832   destroyRootPage(pParse, pTab->tnum, iDb);
90833   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
90834     destroyRootPage(pParse, pIdx->tnum, iDb);
90835   }
90836 #else
90837   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
90838   ** is not defined), then it is important to call OP_Destroy on the
90839   ** table and index root-pages in order, starting with the numerically
90840   ** largest root-page number. This guarantees that none of the root-pages
90841   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
90842   ** following were coded:
90843   **
90844   ** OP_Destroy 4 0
90845   ** ...
90846   ** OP_Destroy 5 0
90847   **
90848   ** and root page 5 happened to be the largest root-page number in the
90849   ** database, then root page 5 would be moved to page 4 by the
90850   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
90851   ** a free-list page.
90852   */
90853   int iTab = pTab->tnum;
90854   int iDestroyed = 0;
90855 
90856   while( 1 ){
90857     Index *pIdx;
90858     int iLargest = 0;
90859 
90860     if( iDestroyed==0 || iTab<iDestroyed ){
90861       iLargest = iTab;
90862     }
90863     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
90864       int iIdx = pIdx->tnum;
90865       assert( pIdx->pSchema==pTab->pSchema );
90866       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
90867         iLargest = iIdx;
90868       }
90869     }
90870     if( iLargest==0 ){
90871       return;
90872     }else{
90873       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
90874       assert( iDb>=0 && iDb<pParse->db->nDb );
90875       destroyRootPage(pParse, iLargest, iDb);
90876       iDestroyed = iLargest;
90877     }
90878   }
90879 #endif
90880 }
90881 
90882 /*
90883 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
90884 ** after a DROP INDEX or DROP TABLE command.
90885 */
90886 static void sqlite3ClearStatTables(
90887   Parse *pParse,         /* The parsing context */
90888   int iDb,               /* The database number */
90889   const char *zType,     /* "idx" or "tbl" */
90890   const char *zName      /* Name of index or table */
90891 ){
90892   int i;
90893   const char *zDbName = pParse->db->aDb[iDb].zName;
90894   for(i=1; i<=4; i++){
90895     char zTab[24];
90896     sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
90897     if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
90898       sqlite3NestedParse(pParse,
90899         "DELETE FROM %Q.%s WHERE %s=%Q",
90900         zDbName, zTab, zType, zName
90901       );
90902     }
90903   }
90904 }
90905 
90906 /*
90907 ** Generate code to drop a table.
90908 */
90909 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
90910   Vdbe *v;
90911   sqlite3 *db = pParse->db;
90912   Trigger *pTrigger;
90913   Db *pDb = &db->aDb[iDb];
90914 
90915   v = sqlite3GetVdbe(pParse);
90916   assert( v!=0 );
90917   sqlite3BeginWriteOperation(pParse, 1, iDb);
90918 
90919 #ifndef SQLITE_OMIT_VIRTUALTABLE
90920   if( IsVirtual(pTab) ){
90921     sqlite3VdbeAddOp0(v, OP_VBegin);
90922   }
90923 #endif
90924 
90925   /* Drop all triggers associated with the table being dropped. Code
90926   ** is generated to remove entries from sqlite_master and/or
90927   ** sqlite_temp_master if required.
90928   */
90929   pTrigger = sqlite3TriggerList(pParse, pTab);
90930   while( pTrigger ){
90931     assert( pTrigger->pSchema==pTab->pSchema ||
90932         pTrigger->pSchema==db->aDb[1].pSchema );
90933     sqlite3DropTriggerPtr(pParse, pTrigger);
90934     pTrigger = pTrigger->pNext;
90935   }
90936 
90937 #ifndef SQLITE_OMIT_AUTOINCREMENT
90938   /* Remove any entries of the sqlite_sequence table associated with
90939   ** the table being dropped. This is done before the table is dropped
90940   ** at the btree level, in case the sqlite_sequence table needs to
90941   ** move as a result of the drop (can happen in auto-vacuum mode).
90942   */
90943   if( pTab->tabFlags & TF_Autoincrement ){
90944     sqlite3NestedParse(pParse,
90945       "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
90946       pDb->zName, pTab->zName
90947     );
90948   }
90949 #endif
90950 
90951   /* Drop all SQLITE_MASTER table and index entries that refer to the
90952   ** table. The program name loops through the master table and deletes
90953   ** every row that refers to a table of the same name as the one being
90954   ** dropped. Triggers are handled separately because a trigger can be
90955   ** created in the temp database that refers to a table in another
90956   ** database.
90957   */
90958   sqlite3NestedParse(pParse,
90959       "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
90960       pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
90961   if( !isView && !IsVirtual(pTab) ){
90962     destroyTable(pParse, pTab);
90963   }
90964 
90965   /* Remove the table entry from SQLite's internal schema and modify
90966   ** the schema cookie.
90967   */
90968   if( IsVirtual(pTab) ){
90969     sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
90970   }
90971   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
90972   sqlite3ChangeCookie(pParse, iDb);
90973   sqliteViewResetAll(db, iDb);
90974 }
90975 
90976 /*
90977 ** This routine is called to do the work of a DROP TABLE statement.
90978 ** pName is the name of the table to be dropped.
90979 */
90980 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
90981   Table *pTab;
90982   Vdbe *v;
90983   sqlite3 *db = pParse->db;
90984   int iDb;
90985 
90986   if( db->mallocFailed ){
90987     goto exit_drop_table;
90988   }
90989   assert( pParse->nErr==0 );
90990   assert( pName->nSrc==1 );
90991   if( noErr ) db->suppressErr++;
90992   pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
90993   if( noErr ) db->suppressErr--;
90994 
90995   if( pTab==0 ){
90996     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
90997     goto exit_drop_table;
90998   }
90999   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
91000   assert( iDb>=0 && iDb<db->nDb );
91001 
91002   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
91003   ** it is initialized.
91004   */
91005   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
91006     goto exit_drop_table;
91007   }
91008 #ifndef SQLITE_OMIT_AUTHORIZATION
91009   {
91010     int code;
91011     const char *zTab = SCHEMA_TABLE(iDb);
91012     const char *zDb = db->aDb[iDb].zName;
91013     const char *zArg2 = 0;
91014     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
91015       goto exit_drop_table;
91016     }
91017     if( isView ){
91018       if( !OMIT_TEMPDB && iDb==1 ){
91019         code = SQLITE_DROP_TEMP_VIEW;
91020       }else{
91021         code = SQLITE_DROP_VIEW;
91022       }
91023 #ifndef SQLITE_OMIT_VIRTUALTABLE
91024     }else if( IsVirtual(pTab) ){
91025       code = SQLITE_DROP_VTABLE;
91026       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
91027 #endif
91028     }else{
91029       if( !OMIT_TEMPDB && iDb==1 ){
91030         code = SQLITE_DROP_TEMP_TABLE;
91031       }else{
91032         code = SQLITE_DROP_TABLE;
91033       }
91034     }
91035     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
91036       goto exit_drop_table;
91037     }
91038     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
91039       goto exit_drop_table;
91040     }
91041   }
91042 #endif
91043   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
91044     && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
91045     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
91046     goto exit_drop_table;
91047   }
91048 
91049 #ifndef SQLITE_OMIT_VIEW
91050   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
91051   ** on a table.
91052   */
91053   if( isView && pTab->pSelect==0 ){
91054     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
91055     goto exit_drop_table;
91056   }
91057   if( !isView && pTab->pSelect ){
91058     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
91059     goto exit_drop_table;
91060   }
91061 #endif
91062 
91063   /* Generate code to remove the table from the master table
91064   ** on disk.
91065   */
91066   v = sqlite3GetVdbe(pParse);
91067   if( v ){
91068     sqlite3BeginWriteOperation(pParse, 1, iDb);
91069     sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
91070     sqlite3FkDropTable(pParse, pName, pTab);
91071     sqlite3CodeDropTable(pParse, pTab, iDb, isView);
91072   }
91073 
91074 exit_drop_table:
91075   sqlite3SrcListDelete(db, pName);
91076 }
91077 
91078 /*
91079 ** This routine is called to create a new foreign key on the table
91080 ** currently under construction.  pFromCol determines which columns
91081 ** in the current table point to the foreign key.  If pFromCol==0 then
91082 ** connect the key to the last column inserted.  pTo is the name of
91083 ** the table referred to (a.k.a the "parent" table).  pToCol is a list
91084 ** of tables in the parent pTo table.  flags contains all
91085 ** information about the conflict resolution algorithms specified
91086 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
91087 **
91088 ** An FKey structure is created and added to the table currently
91089 ** under construction in the pParse->pNewTable field.
91090 **
91091 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
91092 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
91093 */
91094 SQLITE_PRIVATE void sqlite3CreateForeignKey(
91095   Parse *pParse,       /* Parsing context */
91096   ExprList *pFromCol,  /* Columns in this table that point to other table */
91097   Token *pTo,          /* Name of the other table */
91098   ExprList *pToCol,    /* Columns in the other table */
91099   int flags            /* Conflict resolution algorithms. */
91100 ){
91101   sqlite3 *db = pParse->db;
91102 #ifndef SQLITE_OMIT_FOREIGN_KEY
91103   FKey *pFKey = 0;
91104   FKey *pNextTo;
91105   Table *p = pParse->pNewTable;
91106   int nByte;
91107   int i;
91108   int nCol;
91109   char *z;
91110 
91111   assert( pTo!=0 );
91112   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
91113   if( pFromCol==0 ){
91114     int iCol = p->nCol-1;
91115     if( NEVER(iCol<0) ) goto fk_end;
91116     if( pToCol && pToCol->nExpr!=1 ){
91117       sqlite3ErrorMsg(pParse, "foreign key on %s"
91118          " should reference only one column of table %T",
91119          p->aCol[iCol].zName, pTo);
91120       goto fk_end;
91121     }
91122     nCol = 1;
91123   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
91124     sqlite3ErrorMsg(pParse,
91125         "number of columns in foreign key does not match the number of "
91126         "columns in the referenced table");
91127     goto fk_end;
91128   }else{
91129     nCol = pFromCol->nExpr;
91130   }
91131   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
91132   if( pToCol ){
91133     for(i=0; i<pToCol->nExpr; i++){
91134       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
91135     }
91136   }
91137   pFKey = sqlite3DbMallocZero(db, nByte );
91138   if( pFKey==0 ){
91139     goto fk_end;
91140   }
91141   pFKey->pFrom = p;
91142   pFKey->pNextFrom = p->pFKey;
91143   z = (char*)&pFKey->aCol[nCol];
91144   pFKey->zTo = z;
91145   memcpy(z, pTo->z, pTo->n);
91146   z[pTo->n] = 0;
91147   sqlite3Dequote(z);
91148   z += pTo->n+1;
91149   pFKey->nCol = nCol;
91150   if( pFromCol==0 ){
91151     pFKey->aCol[0].iFrom = p->nCol-1;
91152   }else{
91153     for(i=0; i<nCol; i++){
91154       int j;
91155       for(j=0; j<p->nCol; j++){
91156         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
91157           pFKey->aCol[i].iFrom = j;
91158           break;
91159         }
91160       }
91161       if( j>=p->nCol ){
91162         sqlite3ErrorMsg(pParse,
91163           "unknown column \"%s\" in foreign key definition",
91164           pFromCol->a[i].zName);
91165         goto fk_end;
91166       }
91167     }
91168   }
91169   if( pToCol ){
91170     for(i=0; i<nCol; i++){
91171       int n = sqlite3Strlen30(pToCol->a[i].zName);
91172       pFKey->aCol[i].zCol = z;
91173       memcpy(z, pToCol->a[i].zName, n);
91174       z[n] = 0;
91175       z += n+1;
91176     }
91177   }
91178   pFKey->isDeferred = 0;
91179   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
91180   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
91181 
91182   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
91183   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
91184       pFKey->zTo, (void *)pFKey
91185   );
91186   if( pNextTo==pFKey ){
91187     db->mallocFailed = 1;
91188     goto fk_end;
91189   }
91190   if( pNextTo ){
91191     assert( pNextTo->pPrevTo==0 );
91192     pFKey->pNextTo = pNextTo;
91193     pNextTo->pPrevTo = pFKey;
91194   }
91195 
91196   /* Link the foreign key to the table as the last step.
91197   */
91198   p->pFKey = pFKey;
91199   pFKey = 0;
91200 
91201 fk_end:
91202   sqlite3DbFree(db, pFKey);
91203 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
91204   sqlite3ExprListDelete(db, pFromCol);
91205   sqlite3ExprListDelete(db, pToCol);
91206 }
91207 
91208 /*
91209 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
91210 ** clause is seen as part of a foreign key definition.  The isDeferred
91211 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
91212 ** The behavior of the most recently created foreign key is adjusted
91213 ** accordingly.
91214 */
91215 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
91216 #ifndef SQLITE_OMIT_FOREIGN_KEY
91217   Table *pTab;
91218   FKey *pFKey;
91219   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
91220   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
91221   pFKey->isDeferred = (u8)isDeferred;
91222 #endif
91223 }
91224 
91225 /*
91226 ** Generate code that will erase and refill index *pIdx.  This is
91227 ** used to initialize a newly created index or to recompute the
91228 ** content of an index in response to a REINDEX command.
91229 **
91230 ** if memRootPage is not negative, it means that the index is newly
91231 ** created.  The register specified by memRootPage contains the
91232 ** root page number of the index.  If memRootPage is negative, then
91233 ** the index already exists and must be cleared before being refilled and
91234 ** the root page number of the index is taken from pIndex->tnum.
91235 */
91236 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
91237   Table *pTab = pIndex->pTable;  /* The table that is indexed */
91238   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
91239   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
91240   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
91241   int addr1;                     /* Address of top of loop */
91242   int addr2;                     /* Address to jump to for next iteration */
91243   int tnum;                      /* Root page of index */
91244   int iPartIdxLabel;             /* Jump to this label to skip a row */
91245   Vdbe *v;                       /* Generate code into this virtual machine */
91246   KeyInfo *pKey;                 /* KeyInfo for index */
91247   int regRecord;                 /* Register holding assembled index record */
91248   sqlite3 *db = pParse->db;      /* The database connection */
91249   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
91250 
91251 #ifndef SQLITE_OMIT_AUTHORIZATION
91252   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
91253       db->aDb[iDb].zName ) ){
91254     return;
91255   }
91256 #endif
91257 
91258   /* Require a write-lock on the table to perform this operation */
91259   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
91260 
91261   v = sqlite3GetVdbe(pParse);
91262   if( v==0 ) return;
91263   if( memRootPage>=0 ){
91264     tnum = memRootPage;
91265   }else{
91266     tnum = pIndex->tnum;
91267   }
91268   pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
91269 
91270   /* Open the sorter cursor if we are to use one. */
91271   iSorter = pParse->nTab++;
91272   sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
91273                     sqlite3KeyInfoRef(pKey), P4_KEYINFO);
91274 
91275   /* Open the table. Loop through all rows of the table, inserting index
91276   ** records into the sorter. */
91277   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
91278   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
91279   regRecord = sqlite3GetTempReg(pParse);
91280 
91281   sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
91282   sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
91283   sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
91284   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
91285   sqlite3VdbeJumpHere(v, addr1);
91286   if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
91287   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
91288                     (char *)pKey, P4_KEYINFO);
91289   sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
91290 
91291   addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
91292   assert( pKey!=0 || db->mallocFailed || pParse->nErr );
91293   if( IsUniqueIndex(pIndex) && pKey!=0 ){
91294     int j2 = sqlite3VdbeCurrentAddr(v) + 3;
91295     sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
91296     addr2 = sqlite3VdbeCurrentAddr(v);
91297     sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
91298                          pIndex->nKeyCol); VdbeCoverage(v);
91299     sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
91300   }else{
91301     addr2 = sqlite3VdbeCurrentAddr(v);
91302   }
91303   sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
91304   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
91305   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
91306   sqlite3ReleaseTempReg(pParse, regRecord);
91307   sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
91308   sqlite3VdbeJumpHere(v, addr1);
91309 
91310   sqlite3VdbeAddOp1(v, OP_Close, iTab);
91311   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
91312   sqlite3VdbeAddOp1(v, OP_Close, iSorter);
91313 }
91314 
91315 /*
91316 ** Allocate heap space to hold an Index object with nCol columns.
91317 **
91318 ** Increase the allocation size to provide an extra nExtra bytes
91319 ** of 8-byte aligned space after the Index object and return a
91320 ** pointer to this extra space in *ppExtra.
91321 */
91322 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
91323   sqlite3 *db,         /* Database connection */
91324   i16 nCol,            /* Total number of columns in the index */
91325   int nExtra,          /* Number of bytes of extra space to alloc */
91326   char **ppExtra       /* Pointer to the "extra" space */
91327 ){
91328   Index *p;            /* Allocated index object */
91329   int nByte;           /* Bytes of space for Index object + arrays */
91330 
91331   nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
91332           ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
91333           ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
91334                  sizeof(i16)*nCol +            /* Index.aiColumn   */
91335                  sizeof(u8)*nCol);             /* Index.aSortOrder */
91336   p = sqlite3DbMallocZero(db, nByte + nExtra);
91337   if( p ){
91338     char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
91339     p->azColl = (char**)pExtra;       pExtra += ROUND8(sizeof(char*)*nCol);
91340     p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
91341     p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
91342     p->aSortOrder = (u8*)pExtra;
91343     p->nColumn = nCol;
91344     p->nKeyCol = nCol - 1;
91345     *ppExtra = ((char*)p) + nByte;
91346   }
91347   return p;
91348 }
91349 
91350 /*
91351 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index
91352 ** and pTblList is the name of the table that is to be indexed.  Both will
91353 ** be NULL for a primary key or an index that is created to satisfy a
91354 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
91355 ** as the table to be indexed.  pParse->pNewTable is a table that is
91356 ** currently being constructed by a CREATE TABLE statement.
91357 **
91358 ** pList is a list of columns to be indexed.  pList will be NULL if this
91359 ** is a primary key or unique-constraint on the most recent column added
91360 ** to the table currently under construction.
91361 **
91362 ** If the index is created successfully, return a pointer to the new Index
91363 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
91364 ** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
91365 */
91366 SQLITE_PRIVATE Index *sqlite3CreateIndex(
91367   Parse *pParse,     /* All information about this parse */
91368   Token *pName1,     /* First part of index name. May be NULL */
91369   Token *pName2,     /* Second part of index name. May be NULL */
91370   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
91371   ExprList *pList,   /* A list of columns to be indexed */
91372   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
91373   Token *pStart,     /* The CREATE token that begins this statement */
91374   Expr *pPIWhere,    /* WHERE clause for partial indices */
91375   int sortOrder,     /* Sort order of primary key when pList==NULL */
91376   int ifNotExist     /* Omit error if index already exists */
91377 ){
91378   Index *pRet = 0;     /* Pointer to return */
91379   Table *pTab = 0;     /* Table to be indexed */
91380   Index *pIndex = 0;   /* The index to be created */
91381   char *zName = 0;     /* Name of the index */
91382   int nName;           /* Number of characters in zName */
91383   int i, j;
91384   DbFixer sFix;        /* For assigning database names to pTable */
91385   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
91386   sqlite3 *db = pParse->db;
91387   Db *pDb;             /* The specific table containing the indexed database */
91388   int iDb;             /* Index of the database that is being written */
91389   Token *pName = 0;    /* Unqualified name of the index to create */
91390   struct ExprList_item *pListItem; /* For looping over pList */
91391   const Column *pTabCol;           /* A column in the table */
91392   int nExtra = 0;                  /* Space allocated for zExtra[] */
91393   int nExtraCol;                   /* Number of extra columns needed */
91394   char *zExtra = 0;                /* Extra space after the Index object */
91395   Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
91396 
91397   assert( pParse->nErr==0 );      /* Never called with prior errors */
91398   if( db->mallocFailed || IN_DECLARE_VTAB ){
91399     goto exit_create_index;
91400   }
91401   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
91402     goto exit_create_index;
91403   }
91404 
91405   /*
91406   ** Find the table that is to be indexed.  Return early if not found.
91407   */
91408   if( pTblName!=0 ){
91409 
91410     /* Use the two-part index name to determine the database
91411     ** to search for the table. 'Fix' the table name to this db
91412     ** before looking up the table.
91413     */
91414     assert( pName1 && pName2 );
91415     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
91416     if( iDb<0 ) goto exit_create_index;
91417     assert( pName && pName->z );
91418 
91419 #ifndef SQLITE_OMIT_TEMPDB
91420     /* If the index name was unqualified, check if the table
91421     ** is a temp table. If so, set the database to 1. Do not do this
91422     ** if initialising a database schema.
91423     */
91424     if( !db->init.busy ){
91425       pTab = sqlite3SrcListLookup(pParse, pTblName);
91426       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
91427         iDb = 1;
91428       }
91429     }
91430 #endif
91431 
91432     sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
91433     if( sqlite3FixSrcList(&sFix, pTblName) ){
91434       /* Because the parser constructs pTblName from a single identifier,
91435       ** sqlite3FixSrcList can never fail. */
91436       assert(0);
91437     }
91438     pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
91439     assert( db->mallocFailed==0 || pTab==0 );
91440     if( pTab==0 ) goto exit_create_index;
91441     if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
91442       sqlite3ErrorMsg(pParse,
91443            "cannot create a TEMP index on non-TEMP table \"%s\"",
91444            pTab->zName);
91445       goto exit_create_index;
91446     }
91447     if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
91448   }else{
91449     assert( pName==0 );
91450     assert( pStart==0 );
91451     pTab = pParse->pNewTable;
91452     if( !pTab ) goto exit_create_index;
91453     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
91454   }
91455   pDb = &db->aDb[iDb];
91456 
91457   assert( pTab!=0 );
91458   assert( pParse->nErr==0 );
91459   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
91460        && db->init.busy==0
91461 #if SQLITE_USER_AUTHENTICATION
91462        && sqlite3UserAuthTable(pTab->zName)==0
91463 #endif
91464        && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
91465     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
91466     goto exit_create_index;
91467   }
91468 #ifndef SQLITE_OMIT_VIEW
91469   if( pTab->pSelect ){
91470     sqlite3ErrorMsg(pParse, "views may not be indexed");
91471     goto exit_create_index;
91472   }
91473 #endif
91474 #ifndef SQLITE_OMIT_VIRTUALTABLE
91475   if( IsVirtual(pTab) ){
91476     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
91477     goto exit_create_index;
91478   }
91479 #endif
91480 
91481   /*
91482   ** Find the name of the index.  Make sure there is not already another
91483   ** index or table with the same name.
91484   **
91485   ** Exception:  If we are reading the names of permanent indices from the
91486   ** sqlite_master table (because some other process changed the schema) and
91487   ** one of the index names collides with the name of a temporary table or
91488   ** index, then we will continue to process this index.
91489   **
91490   ** If pName==0 it means that we are
91491   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
91492   ** own name.
91493   */
91494   if( pName ){
91495     zName = sqlite3NameFromToken(db, pName);
91496     if( zName==0 ) goto exit_create_index;
91497     assert( pName->z!=0 );
91498     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
91499       goto exit_create_index;
91500     }
91501     if( !db->init.busy ){
91502       if( sqlite3FindTable(db, zName, 0)!=0 ){
91503         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
91504         goto exit_create_index;
91505       }
91506     }
91507     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
91508       if( !ifNotExist ){
91509         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
91510       }else{
91511         assert( !db->init.busy );
91512         sqlite3CodeVerifySchema(pParse, iDb);
91513       }
91514       goto exit_create_index;
91515     }
91516   }else{
91517     int n;
91518     Index *pLoop;
91519     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
91520     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
91521     if( zName==0 ){
91522       goto exit_create_index;
91523     }
91524   }
91525 
91526   /* Check for authorization to create an index.
91527   */
91528 #ifndef SQLITE_OMIT_AUTHORIZATION
91529   {
91530     const char *zDb = pDb->zName;
91531     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
91532       goto exit_create_index;
91533     }
91534     i = SQLITE_CREATE_INDEX;
91535     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
91536     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
91537       goto exit_create_index;
91538     }
91539   }
91540 #endif
91541 
91542   /* If pList==0, it means this routine was called to make a primary
91543   ** key out of the last column added to the table under construction.
91544   ** So create a fake list to simulate this.
91545   */
91546   if( pList==0 ){
91547     pList = sqlite3ExprListAppend(pParse, 0, 0);
91548     if( pList==0 ) goto exit_create_index;
91549     pList->a[0].zName = sqlite3DbStrDup(pParse->db,
91550                                         pTab->aCol[pTab->nCol-1].zName);
91551     pList->a[0].sortOrder = (u8)sortOrder;
91552   }
91553 
91554   /* Figure out how many bytes of space are required to store explicitly
91555   ** specified collation sequence names.
91556   */
91557   for(i=0; i<pList->nExpr; i++){
91558     Expr *pExpr = pList->a[i].pExpr;
91559     if( pExpr ){
91560       assert( pExpr->op==TK_COLLATE );
91561       nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
91562     }
91563   }
91564 
91565   /*
91566   ** Allocate the index structure.
91567   */
91568   nName = sqlite3Strlen30(zName);
91569   nExtraCol = pPk ? pPk->nKeyCol : 1;
91570   pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
91571                                       nName + nExtra + 1, &zExtra);
91572   if( db->mallocFailed ){
91573     goto exit_create_index;
91574   }
91575   assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
91576   assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
91577   pIndex->zName = zExtra;
91578   zExtra += nName + 1;
91579   memcpy(pIndex->zName, zName, nName+1);
91580   pIndex->pTable = pTab;
91581   pIndex->onError = (u8)onError;
91582   pIndex->uniqNotNull = onError!=OE_None;
91583   pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
91584   pIndex->pSchema = db->aDb[iDb].pSchema;
91585   pIndex->nKeyCol = pList->nExpr;
91586   if( pPIWhere ){
91587     sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
91588     pIndex->pPartIdxWhere = pPIWhere;
91589     pPIWhere = 0;
91590   }
91591   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
91592 
91593   /* Check to see if we should honor DESC requests on index columns
91594   */
91595   if( pDb->pSchema->file_format>=4 ){
91596     sortOrderMask = -1;   /* Honor DESC */
91597   }else{
91598     sortOrderMask = 0;    /* Ignore DESC */
91599   }
91600 
91601   /* Scan the names of the columns of the table to be indexed and
91602   ** load the column indices into the Index structure.  Report an error
91603   ** if any column is not found.
91604   **
91605   ** TODO:  Add a test to make sure that the same column is not named
91606   ** more than once within the same index.  Only the first instance of
91607   ** the column will ever be used by the optimizer.  Note that using the
91608   ** same column more than once cannot be an error because that would
91609   ** break backwards compatibility - it needs to be a warning.
91610   */
91611   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
91612     const char *zColName = pListItem->zName;
91613     int requestedSortOrder;
91614     char *zColl;                   /* Collation sequence name */
91615 
91616     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
91617       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
91618     }
91619     if( j>=pTab->nCol ){
91620       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
91621         pTab->zName, zColName);
91622       pParse->checkSchema = 1;
91623       goto exit_create_index;
91624     }
91625     assert( j<=0x7fff );
91626     pIndex->aiColumn[i] = (i16)j;
91627     if( pListItem->pExpr ){
91628       int nColl;
91629       assert( pListItem->pExpr->op==TK_COLLATE );
91630       zColl = pListItem->pExpr->u.zToken;
91631       nColl = sqlite3Strlen30(zColl) + 1;
91632       assert( nExtra>=nColl );
91633       memcpy(zExtra, zColl, nColl);
91634       zColl = zExtra;
91635       zExtra += nColl;
91636       nExtra -= nColl;
91637     }else{
91638       zColl = pTab->aCol[j].zColl;
91639       if( !zColl ) zColl = "BINARY";
91640     }
91641     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
91642       goto exit_create_index;
91643     }
91644     pIndex->azColl[i] = zColl;
91645     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
91646     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
91647     if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
91648   }
91649   if( pPk ){
91650     for(j=0; j<pPk->nKeyCol; j++){
91651       int x = pPk->aiColumn[j];
91652       if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
91653         pIndex->nColumn--;
91654       }else{
91655         pIndex->aiColumn[i] = x;
91656         pIndex->azColl[i] = pPk->azColl[j];
91657         pIndex->aSortOrder[i] = pPk->aSortOrder[j];
91658         i++;
91659       }
91660     }
91661     assert( i==pIndex->nColumn );
91662   }else{
91663     pIndex->aiColumn[i] = -1;
91664     pIndex->azColl[i] = "BINARY";
91665   }
91666   sqlite3DefaultRowEst(pIndex);
91667   if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
91668 
91669   if( pTab==pParse->pNewTable ){
91670     /* This routine has been called to create an automatic index as a
91671     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
91672     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
91673     ** i.e. one of:
91674     **
91675     ** CREATE TABLE t(x PRIMARY KEY, y);
91676     ** CREATE TABLE t(x, y, UNIQUE(x, y));
91677     **
91678     ** Either way, check to see if the table already has such an index. If
91679     ** so, don't bother creating this one. This only applies to
91680     ** automatically created indices. Users can do as they wish with
91681     ** explicit indices.
91682     **
91683     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
91684     ** (and thus suppressing the second one) even if they have different
91685     ** sort orders.
91686     **
91687     ** If there are different collating sequences or if the columns of
91688     ** the constraint occur in different orders, then the constraints are
91689     ** considered distinct and both result in separate indices.
91690     */
91691     Index *pIdx;
91692     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
91693       int k;
91694       assert( IsUniqueIndex(pIdx) );
91695       assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
91696       assert( IsUniqueIndex(pIndex) );
91697 
91698       if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
91699       for(k=0; k<pIdx->nKeyCol; k++){
91700         const char *z1;
91701         const char *z2;
91702         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
91703         z1 = pIdx->azColl[k];
91704         z2 = pIndex->azColl[k];
91705         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
91706       }
91707       if( k==pIdx->nKeyCol ){
91708         if( pIdx->onError!=pIndex->onError ){
91709           /* This constraint creates the same index as a previous
91710           ** constraint specified somewhere in the CREATE TABLE statement.
91711           ** However the ON CONFLICT clauses are different. If both this
91712           ** constraint and the previous equivalent constraint have explicit
91713           ** ON CONFLICT clauses this is an error. Otherwise, use the
91714           ** explicitly specified behavior for the index.
91715           */
91716           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
91717             sqlite3ErrorMsg(pParse,
91718                 "conflicting ON CONFLICT clauses specified", 0);
91719           }
91720           if( pIdx->onError==OE_Default ){
91721             pIdx->onError = pIndex->onError;
91722           }
91723         }
91724         goto exit_create_index;
91725       }
91726     }
91727   }
91728 
91729   /* Link the new Index structure to its table and to the other
91730   ** in-memory database structures.
91731   */
91732   if( db->init.busy ){
91733     Index *p;
91734     assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
91735     p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
91736                           pIndex->zName, pIndex);
91737     if( p ){
91738       assert( p==pIndex );  /* Malloc must have failed */
91739       db->mallocFailed = 1;
91740       goto exit_create_index;
91741     }
91742     db->flags |= SQLITE_InternChanges;
91743     if( pTblName!=0 ){
91744       pIndex->tnum = db->init.newTnum;
91745     }
91746   }
91747 
91748   /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
91749   ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
91750   ** emit code to allocate the index rootpage on disk and make an entry for
91751   ** the index in the sqlite_master table and populate the index with
91752   ** content.  But, do not do this if we are simply reading the sqlite_master
91753   ** table to parse the schema, or if this index is the PRIMARY KEY index
91754   ** of a WITHOUT ROWID table.
91755   **
91756   ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
91757   ** or UNIQUE index in a CREATE TABLE statement.  Since the table
91758   ** has just been created, it contains no data and the index initialization
91759   ** step can be skipped.
91760   */
91761   else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
91762     Vdbe *v;
91763     char *zStmt;
91764     int iMem = ++pParse->nMem;
91765 
91766     v = sqlite3GetVdbe(pParse);
91767     if( v==0 ) goto exit_create_index;
91768 
91769 
91770     /* Create the rootpage for the index
91771     */
91772     sqlite3BeginWriteOperation(pParse, 1, iDb);
91773     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
91774 
91775     /* Gather the complete text of the CREATE INDEX statement into
91776     ** the zStmt variable
91777     */
91778     if( pStart ){
91779       int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
91780       if( pName->z[n-1]==';' ) n--;
91781       /* A named index with an explicit CREATE INDEX statement */
91782       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
91783         onError==OE_None ? "" : " UNIQUE", n, pName->z);
91784     }else{
91785       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
91786       /* zStmt = sqlite3MPrintf(""); */
91787       zStmt = 0;
91788     }
91789 
91790     /* Add an entry in sqlite_master for this index
91791     */
91792     sqlite3NestedParse(pParse,
91793         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
91794         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
91795         pIndex->zName,
91796         pTab->zName,
91797         iMem,
91798         zStmt
91799     );
91800     sqlite3DbFree(db, zStmt);
91801 
91802     /* Fill the index with data and reparse the schema. Code an OP_Expire
91803     ** to invalidate all pre-compiled statements.
91804     */
91805     if( pTblName ){
91806       sqlite3RefillIndex(pParse, pIndex, iMem);
91807       sqlite3ChangeCookie(pParse, iDb);
91808       sqlite3VdbeAddParseSchemaOp(v, iDb,
91809          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
91810       sqlite3VdbeAddOp1(v, OP_Expire, 0);
91811     }
91812   }
91813 
91814   /* When adding an index to the list of indices for a table, make
91815   ** sure all indices labeled OE_Replace come after all those labeled
91816   ** OE_Ignore.  This is necessary for the correct constraint check
91817   ** processing (in sqlite3GenerateConstraintChecks()) as part of
91818   ** UPDATE and INSERT statements.
91819   */
91820   if( db->init.busy || pTblName==0 ){
91821     if( onError!=OE_Replace || pTab->pIndex==0
91822          || pTab->pIndex->onError==OE_Replace){
91823       pIndex->pNext = pTab->pIndex;
91824       pTab->pIndex = pIndex;
91825     }else{
91826       Index *pOther = pTab->pIndex;
91827       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
91828         pOther = pOther->pNext;
91829       }
91830       pIndex->pNext = pOther->pNext;
91831       pOther->pNext = pIndex;
91832     }
91833     pRet = pIndex;
91834     pIndex = 0;
91835   }
91836 
91837   /* Clean up before exiting */
91838 exit_create_index:
91839   if( pIndex ) freeIndex(db, pIndex);
91840   sqlite3ExprDelete(db, pPIWhere);
91841   sqlite3ExprListDelete(db, pList);
91842   sqlite3SrcListDelete(db, pTblName);
91843   sqlite3DbFree(db, zName);
91844   return pRet;
91845 }
91846 
91847 /*
91848 ** Fill the Index.aiRowEst[] array with default information - information
91849 ** to be used when we have not run the ANALYZE command.
91850 **
91851 ** aiRowEst[0] is supposed to contain the number of elements in the index.
91852 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
91853 ** number of rows in the table that match any particular value of the
91854 ** first column of the index.  aiRowEst[2] is an estimate of the number
91855 ** of rows that match any particular combination of the first 2 columns
91856 ** of the index.  And so forth.  It must always be the case that
91857 *
91858 **           aiRowEst[N]<=aiRowEst[N-1]
91859 **           aiRowEst[N]>=1
91860 **
91861 ** Apart from that, we have little to go on besides intuition as to
91862 ** how aiRowEst[] should be initialized.  The numbers generated here
91863 ** are based on typical values found in actual indices.
91864 */
91865 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
91866   /*                10,  9,  8,  7,  6 */
91867   LogEst aVal[] = { 33, 32, 30, 28, 26 };
91868   LogEst *a = pIdx->aiRowLogEst;
91869   int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
91870   int i;
91871 
91872   /* Set the first entry (number of rows in the index) to the estimated
91873   ** number of rows in the table. Or 10, if the estimated number of rows
91874   ** in the table is less than that.  */
91875   a[0] = pIdx->pTable->nRowLogEst;
91876   if( a[0]<33 ) a[0] = 33;        assert( 33==sqlite3LogEst(10) );
91877 
91878   /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
91879   ** 6 and each subsequent value (if any) is 5.  */
91880   memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
91881   for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
91882     a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
91883   }
91884 
91885   assert( 0==sqlite3LogEst(1) );
91886   if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
91887 }
91888 
91889 /*
91890 ** This routine will drop an existing named index.  This routine
91891 ** implements the DROP INDEX statement.
91892 */
91893 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
91894   Index *pIndex;
91895   Vdbe *v;
91896   sqlite3 *db = pParse->db;
91897   int iDb;
91898 
91899   assert( pParse->nErr==0 );   /* Never called with prior errors */
91900   if( db->mallocFailed ){
91901     goto exit_drop_index;
91902   }
91903   assert( pName->nSrc==1 );
91904   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
91905     goto exit_drop_index;
91906   }
91907   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
91908   if( pIndex==0 ){
91909     if( !ifExists ){
91910       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
91911     }else{
91912       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
91913     }
91914     pParse->checkSchema = 1;
91915     goto exit_drop_index;
91916   }
91917   if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
91918     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
91919       "or PRIMARY KEY constraint cannot be dropped", 0);
91920     goto exit_drop_index;
91921   }
91922   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
91923 #ifndef SQLITE_OMIT_AUTHORIZATION
91924   {
91925     int code = SQLITE_DROP_INDEX;
91926     Table *pTab = pIndex->pTable;
91927     const char *zDb = db->aDb[iDb].zName;
91928     const char *zTab = SCHEMA_TABLE(iDb);
91929     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
91930       goto exit_drop_index;
91931     }
91932     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
91933     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
91934       goto exit_drop_index;
91935     }
91936   }
91937 #endif
91938 
91939   /* Generate code to remove the index and from the master table */
91940   v = sqlite3GetVdbe(pParse);
91941   if( v ){
91942     sqlite3BeginWriteOperation(pParse, 1, iDb);
91943     sqlite3NestedParse(pParse,
91944        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
91945        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
91946     );
91947     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
91948     sqlite3ChangeCookie(pParse, iDb);
91949     destroyRootPage(pParse, pIndex->tnum, iDb);
91950     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
91951   }
91952 
91953 exit_drop_index:
91954   sqlite3SrcListDelete(db, pName);
91955 }
91956 
91957 /*
91958 ** pArray is a pointer to an array of objects. Each object in the
91959 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
91960 ** to extend the array so that there is space for a new object at the end.
91961 **
91962 ** When this function is called, *pnEntry contains the current size of
91963 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
91964 ** in total).
91965 **
91966 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
91967 ** space allocated for the new object is zeroed, *pnEntry updated to
91968 ** reflect the new size of the array and a pointer to the new allocation
91969 ** returned. *pIdx is set to the index of the new array entry in this case.
91970 **
91971 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
91972 ** unchanged and a copy of pArray returned.
91973 */
91974 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
91975   sqlite3 *db,      /* Connection to notify of malloc failures */
91976   void *pArray,     /* Array of objects.  Might be reallocated */
91977   int szEntry,      /* Size of each object in the array */
91978   int *pnEntry,     /* Number of objects currently in use */
91979   int *pIdx         /* Write the index of a new slot here */
91980 ){
91981   char *z;
91982   int n = *pnEntry;
91983   if( (n & (n-1))==0 ){
91984     int sz = (n==0) ? 1 : 2*n;
91985     void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
91986     if( pNew==0 ){
91987       *pIdx = -1;
91988       return pArray;
91989     }
91990     pArray = pNew;
91991   }
91992   z = (char*)pArray;
91993   memset(&z[n * szEntry], 0, szEntry);
91994   *pIdx = n;
91995   ++*pnEntry;
91996   return pArray;
91997 }
91998 
91999 /*
92000 ** Append a new element to the given IdList.  Create a new IdList if
92001 ** need be.
92002 **
92003 ** A new IdList is returned, or NULL if malloc() fails.
92004 */
92005 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
92006   int i;
92007   if( pList==0 ){
92008     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
92009     if( pList==0 ) return 0;
92010   }
92011   pList->a = sqlite3ArrayAllocate(
92012       db,
92013       pList->a,
92014       sizeof(pList->a[0]),
92015       &pList->nId,
92016       &i
92017   );
92018   if( i<0 ){
92019     sqlite3IdListDelete(db, pList);
92020     return 0;
92021   }
92022   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
92023   return pList;
92024 }
92025 
92026 /*
92027 ** Delete an IdList.
92028 */
92029 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
92030   int i;
92031   if( pList==0 ) return;
92032   for(i=0; i<pList->nId; i++){
92033     sqlite3DbFree(db, pList->a[i].zName);
92034   }
92035   sqlite3DbFree(db, pList->a);
92036   sqlite3DbFree(db, pList);
92037 }
92038 
92039 /*
92040 ** Return the index in pList of the identifier named zId.  Return -1
92041 ** if not found.
92042 */
92043 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
92044   int i;
92045   if( pList==0 ) return -1;
92046   for(i=0; i<pList->nId; i++){
92047     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
92048   }
92049   return -1;
92050 }
92051 
92052 /*
92053 ** Expand the space allocated for the given SrcList object by
92054 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
92055 ** New slots are zeroed.
92056 **
92057 ** For example, suppose a SrcList initially contains two entries: A,B.
92058 ** To append 3 new entries onto the end, do this:
92059 **
92060 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
92061 **
92062 ** After the call above it would contain:  A, B, nil, nil, nil.
92063 ** If the iStart argument had been 1 instead of 2, then the result
92064 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
92065 ** the iStart value would be 0.  The result then would
92066 ** be: nil, nil, nil, A, B.
92067 **
92068 ** If a memory allocation fails the SrcList is unchanged.  The
92069 ** db->mallocFailed flag will be set to true.
92070 */
92071 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
92072   sqlite3 *db,       /* Database connection to notify of OOM errors */
92073   SrcList *pSrc,     /* The SrcList to be enlarged */
92074   int nExtra,        /* Number of new slots to add to pSrc->a[] */
92075   int iStart         /* Index in pSrc->a[] of first new slot */
92076 ){
92077   int i;
92078 
92079   /* Sanity checking on calling parameters */
92080   assert( iStart>=0 );
92081   assert( nExtra>=1 );
92082   assert( pSrc!=0 );
92083   assert( iStart<=pSrc->nSrc );
92084 
92085   /* Allocate additional space if needed */
92086   if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
92087     SrcList *pNew;
92088     int nAlloc = pSrc->nSrc+nExtra;
92089     int nGot;
92090     pNew = sqlite3DbRealloc(db, pSrc,
92091                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
92092     if( pNew==0 ){
92093       assert( db->mallocFailed );
92094       return pSrc;
92095     }
92096     pSrc = pNew;
92097     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
92098     pSrc->nAlloc = nGot;
92099   }
92100 
92101   /* Move existing slots that come after the newly inserted slots
92102   ** out of the way */
92103   for(i=pSrc->nSrc-1; i>=iStart; i--){
92104     pSrc->a[i+nExtra] = pSrc->a[i];
92105   }
92106   pSrc->nSrc += nExtra;
92107 
92108   /* Zero the newly allocated slots */
92109   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
92110   for(i=iStart; i<iStart+nExtra; i++){
92111     pSrc->a[i].iCursor = -1;
92112   }
92113 
92114   /* Return a pointer to the enlarged SrcList */
92115   return pSrc;
92116 }
92117 
92118 
92119 /*
92120 ** Append a new table name to the given SrcList.  Create a new SrcList if
92121 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
92122 **
92123 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
92124 ** SrcList might be the same as the SrcList that was input or it might be
92125 ** a new one.  If an OOM error does occurs, then the prior value of pList
92126 ** that is input to this routine is automatically freed.
92127 **
92128 ** If pDatabase is not null, it means that the table has an optional
92129 ** database name prefix.  Like this:  "database.table".  The pDatabase
92130 ** points to the table name and the pTable points to the database name.
92131 ** The SrcList.a[].zName field is filled with the table name which might
92132 ** come from pTable (if pDatabase is NULL) or from pDatabase.
92133 ** SrcList.a[].zDatabase is filled with the database name from pTable,
92134 ** or with NULL if no database is specified.
92135 **
92136 ** In other words, if call like this:
92137 **
92138 **         sqlite3SrcListAppend(D,A,B,0);
92139 **
92140 ** Then B is a table name and the database name is unspecified.  If called
92141 ** like this:
92142 **
92143 **         sqlite3SrcListAppend(D,A,B,C);
92144 **
92145 ** Then C is the table name and B is the database name.  If C is defined
92146 ** then so is B.  In other words, we never have a case where:
92147 **
92148 **         sqlite3SrcListAppend(D,A,0,C);
92149 **
92150 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
92151 ** before being added to the SrcList.
92152 */
92153 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
92154   sqlite3 *db,        /* Connection to notify of malloc failures */
92155   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
92156   Token *pTable,      /* Table to append */
92157   Token *pDatabase    /* Database of the table */
92158 ){
92159   struct SrcList_item *pItem;
92160   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
92161   if( pList==0 ){
92162     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
92163     if( pList==0 ) return 0;
92164     pList->nAlloc = 1;
92165   }
92166   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
92167   if( db->mallocFailed ){
92168     sqlite3SrcListDelete(db, pList);
92169     return 0;
92170   }
92171   pItem = &pList->a[pList->nSrc-1];
92172   if( pDatabase && pDatabase->z==0 ){
92173     pDatabase = 0;
92174   }
92175   if( pDatabase ){
92176     Token *pTemp = pDatabase;
92177     pDatabase = pTable;
92178     pTable = pTemp;
92179   }
92180   pItem->zName = sqlite3NameFromToken(db, pTable);
92181   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
92182   return pList;
92183 }
92184 
92185 /*
92186 ** Assign VdbeCursor index numbers to all tables in a SrcList
92187 */
92188 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
92189   int i;
92190   struct SrcList_item *pItem;
92191   assert(pList || pParse->db->mallocFailed );
92192   if( pList ){
92193     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
92194       if( pItem->iCursor>=0 ) break;
92195       pItem->iCursor = pParse->nTab++;
92196       if( pItem->pSelect ){
92197         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
92198       }
92199     }
92200   }
92201 }
92202 
92203 /*
92204 ** Delete an entire SrcList including all its substructure.
92205 */
92206 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
92207   int i;
92208   struct SrcList_item *pItem;
92209   if( pList==0 ) return;
92210   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
92211     sqlite3DbFree(db, pItem->zDatabase);
92212     sqlite3DbFree(db, pItem->zName);
92213     sqlite3DbFree(db, pItem->zAlias);
92214     sqlite3DbFree(db, pItem->zIndex);
92215     sqlite3DeleteTable(db, pItem->pTab);
92216     sqlite3SelectDelete(db, pItem->pSelect);
92217     sqlite3ExprDelete(db, pItem->pOn);
92218     sqlite3IdListDelete(db, pItem->pUsing);
92219   }
92220   sqlite3DbFree(db, pList);
92221 }
92222 
92223 /*
92224 ** This routine is called by the parser to add a new term to the
92225 ** end of a growing FROM clause.  The "p" parameter is the part of
92226 ** the FROM clause that has already been constructed.  "p" is NULL
92227 ** if this is the first term of the FROM clause.  pTable and pDatabase
92228 ** are the name of the table and database named in the FROM clause term.
92229 ** pDatabase is NULL if the database name qualifier is missing - the
92230 ** usual case.  If the term has an alias, then pAlias points to the
92231 ** alias token.  If the term is a subquery, then pSubquery is the
92232 ** SELECT statement that the subquery encodes.  The pTable and
92233 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
92234 ** parameters are the content of the ON and USING clauses.
92235 **
92236 ** Return a new SrcList which encodes is the FROM with the new
92237 ** term added.
92238 */
92239 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
92240   Parse *pParse,          /* Parsing context */
92241   SrcList *p,             /* The left part of the FROM clause already seen */
92242   Token *pTable,          /* Name of the table to add to the FROM clause */
92243   Token *pDatabase,       /* Name of the database containing pTable */
92244   Token *pAlias,          /* The right-hand side of the AS subexpression */
92245   Select *pSubquery,      /* A subquery used in place of a table name */
92246   Expr *pOn,              /* The ON clause of a join */
92247   IdList *pUsing          /* The USING clause of a join */
92248 ){
92249   struct SrcList_item *pItem;
92250   sqlite3 *db = pParse->db;
92251   if( !p && (pOn || pUsing) ){
92252     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
92253       (pOn ? "ON" : "USING")
92254     );
92255     goto append_from_error;
92256   }
92257   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
92258   if( p==0 || NEVER(p->nSrc==0) ){
92259     goto append_from_error;
92260   }
92261   pItem = &p->a[p->nSrc-1];
92262   assert( pAlias!=0 );
92263   if( pAlias->n ){
92264     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
92265   }
92266   pItem->pSelect = pSubquery;
92267   pItem->pOn = pOn;
92268   pItem->pUsing = pUsing;
92269   return p;
92270 
92271  append_from_error:
92272   assert( p==0 );
92273   sqlite3ExprDelete(db, pOn);
92274   sqlite3IdListDelete(db, pUsing);
92275   sqlite3SelectDelete(db, pSubquery);
92276   return 0;
92277 }
92278 
92279 /*
92280 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
92281 ** element of the source-list passed as the second argument.
92282 */
92283 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
92284   assert( pIndexedBy!=0 );
92285   if( p && ALWAYS(p->nSrc>0) ){
92286     struct SrcList_item *pItem = &p->a[p->nSrc-1];
92287     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
92288     if( pIndexedBy->n==1 && !pIndexedBy->z ){
92289       /* A "NOT INDEXED" clause was supplied. See parse.y
92290       ** construct "indexed_opt" for details. */
92291       pItem->notIndexed = 1;
92292     }else{
92293       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
92294     }
92295   }
92296 }
92297 
92298 /*
92299 ** When building up a FROM clause in the parser, the join operator
92300 ** is initially attached to the left operand.  But the code generator
92301 ** expects the join operator to be on the right operand.  This routine
92302 ** Shifts all join operators from left to right for an entire FROM
92303 ** clause.
92304 **
92305 ** Example: Suppose the join is like this:
92306 **
92307 **           A natural cross join B
92308 **
92309 ** The operator is "natural cross join".  The A and B operands are stored
92310 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
92311 ** operator with A.  This routine shifts that operator over to B.
92312 */
92313 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
92314   if( p ){
92315     int i;
92316     assert( p->a || p->nSrc==0 );
92317     for(i=p->nSrc-1; i>0; i--){
92318       p->a[i].jointype = p->a[i-1].jointype;
92319     }
92320     p->a[0].jointype = 0;
92321   }
92322 }
92323 
92324 /*
92325 ** Begin a transaction
92326 */
92327 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
92328   sqlite3 *db;
92329   Vdbe *v;
92330   int i;
92331 
92332   assert( pParse!=0 );
92333   db = pParse->db;
92334   assert( db!=0 );
92335 /*  if( db->aDb[0].pBt==0 ) return; */
92336   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
92337     return;
92338   }
92339   v = sqlite3GetVdbe(pParse);
92340   if( !v ) return;
92341   if( type!=TK_DEFERRED ){
92342     for(i=0; i<db->nDb; i++){
92343       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
92344       sqlite3VdbeUsesBtree(v, i);
92345     }
92346   }
92347   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
92348 }
92349 
92350 /*
92351 ** Commit a transaction
92352 */
92353 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
92354   Vdbe *v;
92355 
92356   assert( pParse!=0 );
92357   assert( pParse->db!=0 );
92358   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
92359     return;
92360   }
92361   v = sqlite3GetVdbe(pParse);
92362   if( v ){
92363     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
92364   }
92365 }
92366 
92367 /*
92368 ** Rollback a transaction
92369 */
92370 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
92371   Vdbe *v;
92372 
92373   assert( pParse!=0 );
92374   assert( pParse->db!=0 );
92375   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
92376     return;
92377   }
92378   v = sqlite3GetVdbe(pParse);
92379   if( v ){
92380     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
92381   }
92382 }
92383 
92384 /*
92385 ** This function is called by the parser when it parses a command to create,
92386 ** release or rollback an SQL savepoint.
92387 */
92388 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
92389   char *zName = sqlite3NameFromToken(pParse->db, pName);
92390   if( zName ){
92391     Vdbe *v = sqlite3GetVdbe(pParse);
92392 #ifndef SQLITE_OMIT_AUTHORIZATION
92393     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
92394     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
92395 #endif
92396     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
92397       sqlite3DbFree(pParse->db, zName);
92398       return;
92399     }
92400     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
92401   }
92402 }
92403 
92404 /*
92405 ** Make sure the TEMP database is open and available for use.  Return
92406 ** the number of errors.  Leave any error messages in the pParse structure.
92407 */
92408 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
92409   sqlite3 *db = pParse->db;
92410   if( db->aDb[1].pBt==0 && !pParse->explain ){
92411     int rc;
92412     Btree *pBt;
92413     static const int flags =
92414           SQLITE_OPEN_READWRITE |
92415           SQLITE_OPEN_CREATE |
92416           SQLITE_OPEN_EXCLUSIVE |
92417           SQLITE_OPEN_DELETEONCLOSE |
92418           SQLITE_OPEN_TEMP_DB;
92419 
92420     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
92421     if( rc!=SQLITE_OK ){
92422       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
92423         "file for storing temporary tables");
92424       pParse->rc = rc;
92425       return 1;
92426     }
92427     db->aDb[1].pBt = pBt;
92428     assert( db->aDb[1].pSchema );
92429     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
92430       db->mallocFailed = 1;
92431       return 1;
92432     }
92433   }
92434   return 0;
92435 }
92436 
92437 /*
92438 ** Record the fact that the schema cookie will need to be verified
92439 ** for database iDb.  The code to actually verify the schema cookie
92440 ** will occur at the end of the top-level VDBE and will be generated
92441 ** later, by sqlite3FinishCoding().
92442 */
92443 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
92444   Parse *pToplevel = sqlite3ParseToplevel(pParse);
92445   sqlite3 *db = pToplevel->db;
92446 
92447   assert( iDb>=0 && iDb<db->nDb );
92448   assert( db->aDb[iDb].pBt!=0 || iDb==1 );
92449   assert( iDb<SQLITE_MAX_ATTACHED+2 );
92450   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
92451   if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
92452     DbMaskSet(pToplevel->cookieMask, iDb);
92453     pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
92454     if( !OMIT_TEMPDB && iDb==1 ){
92455       sqlite3OpenTempDatabase(pToplevel);
92456     }
92457   }
92458 }
92459 
92460 /*
92461 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
92462 ** attached database. Otherwise, invoke it for the database named zDb only.
92463 */
92464 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
92465   sqlite3 *db = pParse->db;
92466   int i;
92467   for(i=0; i<db->nDb; i++){
92468     Db *pDb = &db->aDb[i];
92469     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
92470       sqlite3CodeVerifySchema(pParse, i);
92471     }
92472   }
92473 }
92474 
92475 /*
92476 ** Generate VDBE code that prepares for doing an operation that
92477 ** might change the database.
92478 **
92479 ** This routine starts a new transaction if we are not already within
92480 ** a transaction.  If we are already within a transaction, then a checkpoint
92481 ** is set if the setStatement parameter is true.  A checkpoint should
92482 ** be set for operations that might fail (due to a constraint) part of
92483 ** the way through and which will need to undo some writes without having to
92484 ** rollback the whole transaction.  For operations where all constraints
92485 ** can be checked before any changes are made to the database, it is never
92486 ** necessary to undo a write and the checkpoint should not be set.
92487 */
92488 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
92489   Parse *pToplevel = sqlite3ParseToplevel(pParse);
92490   sqlite3CodeVerifySchema(pParse, iDb);
92491   DbMaskSet(pToplevel->writeMask, iDb);
92492   pToplevel->isMultiWrite |= setStatement;
92493 }
92494 
92495 /*
92496 ** Indicate that the statement currently under construction might write
92497 ** more than one entry (example: deleting one row then inserting another,
92498 ** inserting multiple rows in a table, or inserting a row and index entries.)
92499 ** If an abort occurs after some of these writes have completed, then it will
92500 ** be necessary to undo the completed writes.
92501 */
92502 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
92503   Parse *pToplevel = sqlite3ParseToplevel(pParse);
92504   pToplevel->isMultiWrite = 1;
92505 }
92506 
92507 /*
92508 ** The code generator calls this routine if is discovers that it is
92509 ** possible to abort a statement prior to completion.  In order to
92510 ** perform this abort without corrupting the database, we need to make
92511 ** sure that the statement is protected by a statement transaction.
92512 **
92513 ** Technically, we only need to set the mayAbort flag if the
92514 ** isMultiWrite flag was previously set.  There is a time dependency
92515 ** such that the abort must occur after the multiwrite.  This makes
92516 ** some statements involving the REPLACE conflict resolution algorithm
92517 ** go a little faster.  But taking advantage of this time dependency
92518 ** makes it more difficult to prove that the code is correct (in
92519 ** particular, it prevents us from writing an effective
92520 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
92521 ** to take the safe route and skip the optimization.
92522 */
92523 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
92524   Parse *pToplevel = sqlite3ParseToplevel(pParse);
92525   pToplevel->mayAbort = 1;
92526 }
92527 
92528 /*
92529 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
92530 ** error. The onError parameter determines which (if any) of the statement
92531 ** and/or current transaction is rolled back.
92532 */
92533 SQLITE_PRIVATE void sqlite3HaltConstraint(
92534   Parse *pParse,    /* Parsing context */
92535   int errCode,      /* extended error code */
92536   int onError,      /* Constraint type */
92537   char *p4,         /* Error message */
92538   i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
92539   u8 p5Errmsg       /* P5_ErrMsg type */
92540 ){
92541   Vdbe *v = sqlite3GetVdbe(pParse);
92542   assert( (errCode&0xff)==SQLITE_CONSTRAINT );
92543   if( onError==OE_Abort ){
92544     sqlite3MayAbort(pParse);
92545   }
92546   sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
92547   if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
92548 }
92549 
92550 /*
92551 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
92552 */
92553 SQLITE_PRIVATE void sqlite3UniqueConstraint(
92554   Parse *pParse,    /* Parsing context */
92555   int onError,      /* Constraint type */
92556   Index *pIdx       /* The index that triggers the constraint */
92557 ){
92558   char *zErr;
92559   int j;
92560   StrAccum errMsg;
92561   Table *pTab = pIdx->pTable;
92562 
92563   sqlite3StrAccumInit(&errMsg, 0, 0, 200);
92564   errMsg.db = pParse->db;
92565   for(j=0; j<pIdx->nKeyCol; j++){
92566     char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
92567     if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
92568     sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
92569     sqlite3StrAccumAppend(&errMsg, ".", 1);
92570     sqlite3StrAccumAppendAll(&errMsg, zCol);
92571   }
92572   zErr = sqlite3StrAccumFinish(&errMsg);
92573   sqlite3HaltConstraint(pParse,
92574     IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
92575                             : SQLITE_CONSTRAINT_UNIQUE,
92576     onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
92577 }
92578 
92579 
92580 /*
92581 ** Code an OP_Halt due to non-unique rowid.
92582 */
92583 SQLITE_PRIVATE void sqlite3RowidConstraint(
92584   Parse *pParse,    /* Parsing context */
92585   int onError,      /* Conflict resolution algorithm */
92586   Table *pTab       /* The table with the non-unique rowid */
92587 ){
92588   char *zMsg;
92589   int rc;
92590   if( pTab->iPKey>=0 ){
92591     zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
92592                           pTab->aCol[pTab->iPKey].zName);
92593     rc = SQLITE_CONSTRAINT_PRIMARYKEY;
92594   }else{
92595     zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
92596     rc = SQLITE_CONSTRAINT_ROWID;
92597   }
92598   sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
92599                         P5_ConstraintUnique);
92600 }
92601 
92602 /*
92603 ** Check to see if pIndex uses the collating sequence pColl.  Return
92604 ** true if it does and false if it does not.
92605 */
92606 #ifndef SQLITE_OMIT_REINDEX
92607 static int collationMatch(const char *zColl, Index *pIndex){
92608   int i;
92609   assert( zColl!=0 );
92610   for(i=0; i<pIndex->nColumn; i++){
92611     const char *z = pIndex->azColl[i];
92612     assert( z!=0 || pIndex->aiColumn[i]<0 );
92613     if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
92614       return 1;
92615     }
92616   }
92617   return 0;
92618 }
92619 #endif
92620 
92621 /*
92622 ** Recompute all indices of pTab that use the collating sequence pColl.
92623 ** If pColl==0 then recompute all indices of pTab.
92624 */
92625 #ifndef SQLITE_OMIT_REINDEX
92626 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
92627   Index *pIndex;              /* An index associated with pTab */
92628 
92629   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
92630     if( zColl==0 || collationMatch(zColl, pIndex) ){
92631       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
92632       sqlite3BeginWriteOperation(pParse, 0, iDb);
92633       sqlite3RefillIndex(pParse, pIndex, -1);
92634     }
92635   }
92636 }
92637 #endif
92638 
92639 /*
92640 ** Recompute all indices of all tables in all databases where the
92641 ** indices use the collating sequence pColl.  If pColl==0 then recompute
92642 ** all indices everywhere.
92643 */
92644 #ifndef SQLITE_OMIT_REINDEX
92645 static void reindexDatabases(Parse *pParse, char const *zColl){
92646   Db *pDb;                    /* A single database */
92647   int iDb;                    /* The database index number */
92648   sqlite3 *db = pParse->db;   /* The database connection */
92649   HashElem *k;                /* For looping over tables in pDb */
92650   Table *pTab;                /* A table in the database */
92651 
92652   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
92653   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
92654     assert( pDb!=0 );
92655     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
92656       pTab = (Table*)sqliteHashData(k);
92657       reindexTable(pParse, pTab, zColl);
92658     }
92659   }
92660 }
92661 #endif
92662 
92663 /*
92664 ** Generate code for the REINDEX command.
92665 **
92666 **        REINDEX                            -- 1
92667 **        REINDEX  <collation>               -- 2
92668 **        REINDEX  ?<database>.?<tablename>  -- 3
92669 **        REINDEX  ?<database>.?<indexname>  -- 4
92670 **
92671 ** Form 1 causes all indices in all attached databases to be rebuilt.
92672 ** Form 2 rebuilds all indices in all databases that use the named
92673 ** collating function.  Forms 3 and 4 rebuild the named index or all
92674 ** indices associated with the named table.
92675 */
92676 #ifndef SQLITE_OMIT_REINDEX
92677 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
92678   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
92679   char *z;                    /* Name of a table or index */
92680   const char *zDb;            /* Name of the database */
92681   Table *pTab;                /* A table in the database */
92682   Index *pIndex;              /* An index associated with pTab */
92683   int iDb;                    /* The database index number */
92684   sqlite3 *db = pParse->db;   /* The database connection */
92685   Token *pObjName;            /* Name of the table or index to be reindexed */
92686 
92687   /* Read the database schema. If an error occurs, leave an error message
92688   ** and code in pParse and return NULL. */
92689   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
92690     return;
92691   }
92692 
92693   if( pName1==0 ){
92694     reindexDatabases(pParse, 0);
92695     return;
92696   }else if( NEVER(pName2==0) || pName2->z==0 ){
92697     char *zColl;
92698     assert( pName1->z );
92699     zColl = sqlite3NameFromToken(pParse->db, pName1);
92700     if( !zColl ) return;
92701     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
92702     if( pColl ){
92703       reindexDatabases(pParse, zColl);
92704       sqlite3DbFree(db, zColl);
92705       return;
92706     }
92707     sqlite3DbFree(db, zColl);
92708   }
92709   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
92710   if( iDb<0 ) return;
92711   z = sqlite3NameFromToken(db, pObjName);
92712   if( z==0 ) return;
92713   zDb = db->aDb[iDb].zName;
92714   pTab = sqlite3FindTable(db, z, zDb);
92715   if( pTab ){
92716     reindexTable(pParse, pTab, 0);
92717     sqlite3DbFree(db, z);
92718     return;
92719   }
92720   pIndex = sqlite3FindIndex(db, z, zDb);
92721   sqlite3DbFree(db, z);
92722   if( pIndex ){
92723     sqlite3BeginWriteOperation(pParse, 0, iDb);
92724     sqlite3RefillIndex(pParse, pIndex, -1);
92725     return;
92726   }
92727   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
92728 }
92729 #endif
92730 
92731 /*
92732 ** Return a KeyInfo structure that is appropriate for the given Index.
92733 **
92734 ** The KeyInfo structure for an index is cached in the Index object.
92735 ** So there might be multiple references to the returned pointer.  The
92736 ** caller should not try to modify the KeyInfo object.
92737 **
92738 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
92739 ** when it has finished using it.
92740 */
92741 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
92742   if( pParse->nErr ) return 0;
92743 #ifndef SQLITE_OMIT_SHARED_CACHE
92744   if( pIdx->pKeyInfo && pIdx->pKeyInfo->db!=pParse->db ){
92745     sqlite3KeyInfoUnref(pIdx->pKeyInfo);
92746     pIdx->pKeyInfo = 0;
92747   }
92748 #endif
92749   if( pIdx->pKeyInfo==0 ){
92750     int i;
92751     int nCol = pIdx->nColumn;
92752     int nKey = pIdx->nKeyCol;
92753     KeyInfo *pKey;
92754     if( pIdx->uniqNotNull ){
92755       pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
92756     }else{
92757       pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
92758     }
92759     if( pKey ){
92760       assert( sqlite3KeyInfoIsWriteable(pKey) );
92761       for(i=0; i<nCol; i++){
92762         char *zColl = pIdx->azColl[i];
92763         assert( zColl!=0 );
92764         pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
92765                           sqlite3LocateCollSeq(pParse, zColl);
92766         pKey->aSortOrder[i] = pIdx->aSortOrder[i];
92767       }
92768       if( pParse->nErr ){
92769         sqlite3KeyInfoUnref(pKey);
92770       }else{
92771         pIdx->pKeyInfo = pKey;
92772       }
92773     }
92774   }
92775   return sqlite3KeyInfoRef(pIdx->pKeyInfo);
92776 }
92777 
92778 #ifndef SQLITE_OMIT_CTE
92779 /*
92780 ** This routine is invoked once per CTE by the parser while parsing a
92781 ** WITH clause.
92782 */
92783 SQLITE_PRIVATE With *sqlite3WithAdd(
92784   Parse *pParse,          /* Parsing context */
92785   With *pWith,            /* Existing WITH clause, or NULL */
92786   Token *pName,           /* Name of the common-table */
92787   ExprList *pArglist,     /* Optional column name list for the table */
92788   Select *pQuery          /* Query used to initialize the table */
92789 ){
92790   sqlite3 *db = pParse->db;
92791   With *pNew;
92792   char *zName;
92793 
92794   /* Check that the CTE name is unique within this WITH clause. If
92795   ** not, store an error in the Parse structure. */
92796   zName = sqlite3NameFromToken(pParse->db, pName);
92797   if( zName && pWith ){
92798     int i;
92799     for(i=0; i<pWith->nCte; i++){
92800       if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
92801         sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
92802       }
92803     }
92804   }
92805 
92806   if( pWith ){
92807     int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
92808     pNew = sqlite3DbRealloc(db, pWith, nByte);
92809   }else{
92810     pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
92811   }
92812   assert( zName!=0 || pNew==0 );
92813   assert( db->mallocFailed==0 || pNew==0 );
92814 
92815   if( pNew==0 ){
92816     sqlite3ExprListDelete(db, pArglist);
92817     sqlite3SelectDelete(db, pQuery);
92818     sqlite3DbFree(db, zName);
92819     pNew = pWith;
92820   }else{
92821     pNew->a[pNew->nCte].pSelect = pQuery;
92822     pNew->a[pNew->nCte].pCols = pArglist;
92823     pNew->a[pNew->nCte].zName = zName;
92824     pNew->a[pNew->nCte].zErr = 0;
92825     pNew->nCte++;
92826   }
92827 
92828   return pNew;
92829 }
92830 
92831 /*
92832 ** Free the contents of the With object passed as the second argument.
92833 */
92834 SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
92835   if( pWith ){
92836     int i;
92837     for(i=0; i<pWith->nCte; i++){
92838       struct Cte *pCte = &pWith->a[i];
92839       sqlite3ExprListDelete(db, pCte->pCols);
92840       sqlite3SelectDelete(db, pCte->pSelect);
92841       sqlite3DbFree(db, pCte->zName);
92842     }
92843     sqlite3DbFree(db, pWith);
92844   }
92845 }
92846 #endif /* !defined(SQLITE_OMIT_CTE) */
92847 
92848 /************** End of build.c ***********************************************/
92849 /************** Begin file callback.c ****************************************/
92850 /*
92851 ** 2005 May 23
92852 **
92853 ** The author disclaims copyright to this source code.  In place of
92854 ** a legal notice, here is a blessing:
92855 **
92856 **    May you do good and not evil.
92857 **    May you find forgiveness for yourself and forgive others.
92858 **    May you share freely, never taking more than you give.
92859 **
92860 *************************************************************************
92861 **
92862 ** This file contains functions used to access the internal hash tables
92863 ** of user defined functions and collation sequences.
92864 */
92865 
92866 
92867 /*
92868 ** Invoke the 'collation needed' callback to request a collation sequence
92869 ** in the encoding enc of name zName, length nName.
92870 */
92871 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
92872   assert( !db->xCollNeeded || !db->xCollNeeded16 );
92873   if( db->xCollNeeded ){
92874     char *zExternal = sqlite3DbStrDup(db, zName);
92875     if( !zExternal ) return;
92876     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
92877     sqlite3DbFree(db, zExternal);
92878   }
92879 #ifndef SQLITE_OMIT_UTF16
92880   if( db->xCollNeeded16 ){
92881     char const *zExternal;
92882     sqlite3_value *pTmp = sqlite3ValueNew(db);
92883     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
92884     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
92885     if( zExternal ){
92886       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
92887     }
92888     sqlite3ValueFree(pTmp);
92889   }
92890 #endif
92891 }
92892 
92893 /*
92894 ** This routine is called if the collation factory fails to deliver a
92895 ** collation function in the best encoding but there may be other versions
92896 ** of this collation function (for other text encodings) available. Use one
92897 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
92898 ** possible.
92899 */
92900 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
92901   CollSeq *pColl2;
92902   char *z = pColl->zName;
92903   int i;
92904   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
92905   for(i=0; i<3; i++){
92906     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
92907     if( pColl2->xCmp!=0 ){
92908       memcpy(pColl, pColl2, sizeof(CollSeq));
92909       pColl->xDel = 0;         /* Do not copy the destructor */
92910       return SQLITE_OK;
92911     }
92912   }
92913   return SQLITE_ERROR;
92914 }
92915 
92916 /*
92917 ** This function is responsible for invoking the collation factory callback
92918 ** or substituting a collation sequence of a different encoding when the
92919 ** requested collation sequence is not available in the desired encoding.
92920 **
92921 ** If it is not NULL, then pColl must point to the database native encoding
92922 ** collation sequence with name zName, length nName.
92923 **
92924 ** The return value is either the collation sequence to be used in database
92925 ** db for collation type name zName, length nName, or NULL, if no collation
92926 ** sequence can be found.  If no collation is found, leave an error message.
92927 **
92928 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
92929 */
92930 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
92931   Parse *pParse,        /* Parsing context */
92932   u8 enc,               /* The desired encoding for the collating sequence */
92933   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
92934   const char *zName     /* Collating sequence name */
92935 ){
92936   CollSeq *p;
92937   sqlite3 *db = pParse->db;
92938 
92939   p = pColl;
92940   if( !p ){
92941     p = sqlite3FindCollSeq(db, enc, zName, 0);
92942   }
92943   if( !p || !p->xCmp ){
92944     /* No collation sequence of this type for this encoding is registered.
92945     ** Call the collation factory to see if it can supply us with one.
92946     */
92947     callCollNeeded(db, enc, zName);
92948     p = sqlite3FindCollSeq(db, enc, zName, 0);
92949   }
92950   if( p && !p->xCmp && synthCollSeq(db, p) ){
92951     p = 0;
92952   }
92953   assert( !p || p->xCmp );
92954   if( p==0 ){
92955     sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
92956   }
92957   return p;
92958 }
92959 
92960 /*
92961 ** This routine is called on a collation sequence before it is used to
92962 ** check that it is defined. An undefined collation sequence exists when
92963 ** a database is loaded that contains references to collation sequences
92964 ** that have not been defined by sqlite3_create_collation() etc.
92965 **
92966 ** If required, this routine calls the 'collation needed' callback to
92967 ** request a definition of the collating sequence. If this doesn't work,
92968 ** an equivalent collating sequence that uses a text encoding different
92969 ** from the main database is substituted, if one is available.
92970 */
92971 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
92972   if( pColl ){
92973     const char *zName = pColl->zName;
92974     sqlite3 *db = pParse->db;
92975     CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
92976     if( !p ){
92977       return SQLITE_ERROR;
92978     }
92979     assert( p==pColl );
92980   }
92981   return SQLITE_OK;
92982 }
92983 
92984 
92985 
92986 /*
92987 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
92988 ** specified by zName and nName is not found and parameter 'create' is
92989 ** true, then create a new entry. Otherwise return NULL.
92990 **
92991 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
92992 ** array of three CollSeq structures. The first is the collation sequence
92993 ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
92994 **
92995 ** Stored immediately after the three collation sequences is a copy of
92996 ** the collation sequence name. A pointer to this string is stored in
92997 ** each collation sequence structure.
92998 */
92999 static CollSeq *findCollSeqEntry(
93000   sqlite3 *db,          /* Database connection */
93001   const char *zName,    /* Name of the collating sequence */
93002   int create            /* Create a new entry if true */
93003 ){
93004   CollSeq *pColl;
93005   pColl = sqlite3HashFind(&db->aCollSeq, zName);
93006 
93007   if( 0==pColl && create ){
93008     int nName = sqlite3Strlen30(zName);
93009     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1);
93010     if( pColl ){
93011       CollSeq *pDel = 0;
93012       pColl[0].zName = (char*)&pColl[3];
93013       pColl[0].enc = SQLITE_UTF8;
93014       pColl[1].zName = (char*)&pColl[3];
93015       pColl[1].enc = SQLITE_UTF16LE;
93016       pColl[2].zName = (char*)&pColl[3];
93017       pColl[2].enc = SQLITE_UTF16BE;
93018       memcpy(pColl[0].zName, zName, nName);
93019       pColl[0].zName[nName] = 0;
93020       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
93021 
93022       /* If a malloc() failure occurred in sqlite3HashInsert(), it will
93023       ** return the pColl pointer to be deleted (because it wasn't added
93024       ** to the hash table).
93025       */
93026       assert( pDel==0 || pDel==pColl );
93027       if( pDel!=0 ){
93028         db->mallocFailed = 1;
93029         sqlite3DbFree(db, pDel);
93030         pColl = 0;
93031       }
93032     }
93033   }
93034   return pColl;
93035 }
93036 
93037 /*
93038 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
93039 ** Return the CollSeq* pointer for the collation sequence named zName
93040 ** for the encoding 'enc' from the database 'db'.
93041 **
93042 ** If the entry specified is not found and 'create' is true, then create a
93043 ** new entry.  Otherwise return NULL.
93044 **
93045 ** A separate function sqlite3LocateCollSeq() is a wrapper around
93046 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
93047 ** if necessary and generates an error message if the collating sequence
93048 ** cannot be found.
93049 **
93050 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
93051 */
93052 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
93053   sqlite3 *db,
93054   u8 enc,
93055   const char *zName,
93056   int create
93057 ){
93058   CollSeq *pColl;
93059   if( zName ){
93060     pColl = findCollSeqEntry(db, zName, create);
93061   }else{
93062     pColl = db->pDfltColl;
93063   }
93064   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
93065   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
93066   if( pColl ) pColl += enc-1;
93067   return pColl;
93068 }
93069 
93070 /* During the search for the best function definition, this procedure
93071 ** is called to test how well the function passed as the first argument
93072 ** matches the request for a function with nArg arguments in a system
93073 ** that uses encoding enc. The value returned indicates how well the
93074 ** request is matched. A higher value indicates a better match.
93075 **
93076 ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
93077 ** is also -1.  In other words, we are searching for a function that
93078 ** takes a variable number of arguments.
93079 **
93080 ** If nArg is -2 that means that we are searching for any function
93081 ** regardless of the number of arguments it uses, so return a positive
93082 ** match score for any
93083 **
93084 ** The returned value is always between 0 and 6, as follows:
93085 **
93086 ** 0: Not a match.
93087 ** 1: UTF8/16 conversion required and function takes any number of arguments.
93088 ** 2: UTF16 byte order change required and function takes any number of args.
93089 ** 3: encoding matches and function takes any number of arguments
93090 ** 4: UTF8/16 conversion required - argument count matches exactly
93091 ** 5: UTF16 byte order conversion required - argument count matches exactly
93092 ** 6: Perfect match:  encoding and argument count match exactly.
93093 **
93094 ** If nArg==(-2) then any function with a non-null xStep or xFunc is
93095 ** a perfect match and any function with both xStep and xFunc NULL is
93096 ** a non-match.
93097 */
93098 #define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
93099 static int matchQuality(
93100   FuncDef *p,     /* The function we are evaluating for match quality */
93101   int nArg,       /* Desired number of arguments.  (-1)==any */
93102   u8 enc          /* Desired text encoding */
93103 ){
93104   int match;
93105 
93106   /* nArg of -2 is a special case */
93107   if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
93108 
93109   /* Wrong number of arguments means "no match" */
93110   if( p->nArg!=nArg && p->nArg>=0 ) return 0;
93111 
93112   /* Give a better score to a function with a specific number of arguments
93113   ** than to function that accepts any number of arguments. */
93114   if( p->nArg==nArg ){
93115     match = 4;
93116   }else{
93117     match = 1;
93118   }
93119 
93120   /* Bonus points if the text encoding matches */
93121   if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
93122     match += 2;  /* Exact encoding match */
93123   }else if( (enc & p->funcFlags & 2)!=0 ){
93124     match += 1;  /* Both are UTF16, but with different byte orders */
93125   }
93126 
93127   return match;
93128 }
93129 
93130 /*
93131 ** Search a FuncDefHash for a function with the given name.  Return
93132 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
93133 */
93134 static FuncDef *functionSearch(
93135   FuncDefHash *pHash,  /* Hash table to search */
93136   int h,               /* Hash of the name */
93137   const char *zFunc,   /* Name of function */
93138   int nFunc            /* Number of bytes in zFunc */
93139 ){
93140   FuncDef *p;
93141   for(p=pHash->a[h]; p; p=p->pHash){
93142     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
93143       return p;
93144     }
93145   }
93146   return 0;
93147 }
93148 
93149 /*
93150 ** Insert a new FuncDef into a FuncDefHash hash table.
93151 */
93152 SQLITE_PRIVATE void sqlite3FuncDefInsert(
93153   FuncDefHash *pHash,  /* The hash table into which to insert */
93154   FuncDef *pDef        /* The function definition to insert */
93155 ){
93156   FuncDef *pOther;
93157   int nName = sqlite3Strlen30(pDef->zName);
93158   u8 c1 = (u8)pDef->zName[0];
93159   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
93160   pOther = functionSearch(pHash, h, pDef->zName, nName);
93161   if( pOther ){
93162     assert( pOther!=pDef && pOther->pNext!=pDef );
93163     pDef->pNext = pOther->pNext;
93164     pOther->pNext = pDef;
93165   }else{
93166     pDef->pNext = 0;
93167     pDef->pHash = pHash->a[h];
93168     pHash->a[h] = pDef;
93169   }
93170 }
93171 
93172 
93173 
93174 /*
93175 ** Locate a user function given a name, a number of arguments and a flag
93176 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
93177 ** pointer to the FuncDef structure that defines that function, or return
93178 ** NULL if the function does not exist.
93179 **
93180 ** If the createFlag argument is true, then a new (blank) FuncDef
93181 ** structure is created and liked into the "db" structure if a
93182 ** no matching function previously existed.
93183 **
93184 ** If nArg is -2, then the first valid function found is returned.  A
93185 ** function is valid if either xFunc or xStep is non-zero.  The nArg==(-2)
93186 ** case is used to see if zName is a valid function name for some number
93187 ** of arguments.  If nArg is -2, then createFlag must be 0.
93188 **
93189 ** If createFlag is false, then a function with the required name and
93190 ** number of arguments may be returned even if the eTextRep flag does not
93191 ** match that requested.
93192 */
93193 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
93194   sqlite3 *db,       /* An open database */
93195   const char *zName, /* Name of the function.  Not null-terminated */
93196   int nName,         /* Number of characters in the name */
93197   int nArg,          /* Number of arguments.  -1 means any number */
93198   u8 enc,            /* Preferred text encoding */
93199   u8 createFlag      /* Create new entry if true and does not otherwise exist */
93200 ){
93201   FuncDef *p;         /* Iterator variable */
93202   FuncDef *pBest = 0; /* Best match found so far */
93203   int bestScore = 0;  /* Score of best match */
93204   int h;              /* Hash value */
93205 
93206   assert( nArg>=(-2) );
93207   assert( nArg>=(-1) || createFlag==0 );
93208   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
93209 
93210   /* First search for a match amongst the application-defined functions.
93211   */
93212   p = functionSearch(&db->aFunc, h, zName, nName);
93213   while( p ){
93214     int score = matchQuality(p, nArg, enc);
93215     if( score>bestScore ){
93216       pBest = p;
93217       bestScore = score;
93218     }
93219     p = p->pNext;
93220   }
93221 
93222   /* If no match is found, search the built-in functions.
93223   **
93224   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
93225   ** functions even if a prior app-defined function was found.  And give
93226   ** priority to built-in functions.
93227   **
93228   ** Except, if createFlag is true, that means that we are trying to
93229   ** install a new function.  Whatever FuncDef structure is returned it will
93230   ** have fields overwritten with new information appropriate for the
93231   ** new function.  But the FuncDefs for built-in functions are read-only.
93232   ** So we must not search for built-ins when creating a new function.
93233   */
93234   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
93235     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
93236     bestScore = 0;
93237     p = functionSearch(pHash, h, zName, nName);
93238     while( p ){
93239       int score = matchQuality(p, nArg, enc);
93240       if( score>bestScore ){
93241         pBest = p;
93242         bestScore = score;
93243       }
93244       p = p->pNext;
93245     }
93246   }
93247 
93248   /* If the createFlag parameter is true and the search did not reveal an
93249   ** exact match for the name, number of arguments and encoding, then add a
93250   ** new entry to the hash table and return it.
93251   */
93252   if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
93253       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
93254     pBest->zName = (char *)&pBest[1];
93255     pBest->nArg = (u16)nArg;
93256     pBest->funcFlags = enc;
93257     memcpy(pBest->zName, zName, nName);
93258     pBest->zName[nName] = 0;
93259     sqlite3FuncDefInsert(&db->aFunc, pBest);
93260   }
93261 
93262   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
93263     return pBest;
93264   }
93265   return 0;
93266 }
93267 
93268 /*
93269 ** Free all resources held by the schema structure. The void* argument points
93270 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
93271 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
93272 ** of the schema hash tables).
93273 **
93274 ** The Schema.cache_size variable is not cleared.
93275 */
93276 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
93277   Hash temp1;
93278   Hash temp2;
93279   HashElem *pElem;
93280   Schema *pSchema = (Schema *)p;
93281 
93282   temp1 = pSchema->tblHash;
93283   temp2 = pSchema->trigHash;
93284   sqlite3HashInit(&pSchema->trigHash);
93285   sqlite3HashClear(&pSchema->idxHash);
93286   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
93287     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
93288   }
93289   sqlite3HashClear(&temp2);
93290   sqlite3HashInit(&pSchema->tblHash);
93291   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
93292     Table *pTab = sqliteHashData(pElem);
93293     sqlite3DeleteTable(0, pTab);
93294   }
93295   sqlite3HashClear(&temp1);
93296   sqlite3HashClear(&pSchema->fkeyHash);
93297   pSchema->pSeqTab = 0;
93298   if( pSchema->schemaFlags & DB_SchemaLoaded ){
93299     pSchema->iGeneration++;
93300     pSchema->schemaFlags &= ~DB_SchemaLoaded;
93301   }
93302 }
93303 
93304 /*
93305 ** Find and return the schema associated with a BTree.  Create
93306 ** a new one if necessary.
93307 */
93308 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
93309   Schema * p;
93310   if( pBt ){
93311     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
93312   }else{
93313     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
93314   }
93315   if( !p ){
93316     db->mallocFailed = 1;
93317   }else if ( 0==p->file_format ){
93318     sqlite3HashInit(&p->tblHash);
93319     sqlite3HashInit(&p->idxHash);
93320     sqlite3HashInit(&p->trigHash);
93321     sqlite3HashInit(&p->fkeyHash);
93322     p->enc = SQLITE_UTF8;
93323   }
93324   return p;
93325 }
93326 
93327 /************** End of callback.c ********************************************/
93328 /************** Begin file delete.c ******************************************/
93329 /*
93330 ** 2001 September 15
93331 **
93332 ** The author disclaims copyright to this source code.  In place of
93333 ** a legal notice, here is a blessing:
93334 **
93335 **    May you do good and not evil.
93336 **    May you find forgiveness for yourself and forgive others.
93337 **    May you share freely, never taking more than you give.
93338 **
93339 *************************************************************************
93340 ** This file contains C code routines that are called by the parser
93341 ** in order to generate code for DELETE FROM statements.
93342 */
93343 
93344 /*
93345 ** While a SrcList can in general represent multiple tables and subqueries
93346 ** (as in the FROM clause of a SELECT statement) in this case it contains
93347 ** the name of a single table, as one might find in an INSERT, DELETE,
93348 ** or UPDATE statement.  Look up that table in the symbol table and
93349 ** return a pointer.  Set an error message and return NULL if the table
93350 ** name is not found or if any other error occurs.
93351 **
93352 ** The following fields are initialized appropriate in pSrc:
93353 **
93354 **    pSrc->a[0].pTab       Pointer to the Table object
93355 **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
93356 **
93357 */
93358 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
93359   struct SrcList_item *pItem = pSrc->a;
93360   Table *pTab;
93361   assert( pItem && pSrc->nSrc==1 );
93362   pTab = sqlite3LocateTableItem(pParse, 0, pItem);
93363   sqlite3DeleteTable(pParse->db, pItem->pTab);
93364   pItem->pTab = pTab;
93365   if( pTab ){
93366     pTab->nRef++;
93367   }
93368   if( sqlite3IndexedByLookup(pParse, pItem) ){
93369     pTab = 0;
93370   }
93371   return pTab;
93372 }
93373 
93374 /*
93375 ** Check to make sure the given table is writable.  If it is not
93376 ** writable, generate an error message and return 1.  If it is
93377 ** writable return 0;
93378 */
93379 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
93380   /* A table is not writable under the following circumstances:
93381   **
93382   **   1) It is a virtual table and no implementation of the xUpdate method
93383   **      has been provided, or
93384   **   2) It is a system table (i.e. sqlite_master), this call is not
93385   **      part of a nested parse and writable_schema pragma has not
93386   **      been specified.
93387   **
93388   ** In either case leave an error message in pParse and return non-zero.
93389   */
93390   if( ( IsVirtual(pTab)
93391      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
93392    || ( (pTab->tabFlags & TF_Readonly)!=0
93393      && (pParse->db->flags & SQLITE_WriteSchema)==0
93394      && pParse->nested==0 )
93395   ){
93396     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
93397     return 1;
93398   }
93399 
93400 #ifndef SQLITE_OMIT_VIEW
93401   if( !viewOk && pTab->pSelect ){
93402     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
93403     return 1;
93404   }
93405 #endif
93406   return 0;
93407 }
93408 
93409 
93410 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
93411 /*
93412 ** Evaluate a view and store its result in an ephemeral table.  The
93413 ** pWhere argument is an optional WHERE clause that restricts the
93414 ** set of rows in the view that are to be added to the ephemeral table.
93415 */
93416 SQLITE_PRIVATE void sqlite3MaterializeView(
93417   Parse *pParse,       /* Parsing context */
93418   Table *pView,        /* View definition */
93419   Expr *pWhere,        /* Optional WHERE clause to be added */
93420   int iCur             /* Cursor number for ephemeral table */
93421 ){
93422   SelectDest dest;
93423   Select *pSel;
93424   SrcList *pFrom;
93425   sqlite3 *db = pParse->db;
93426   int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
93427   pWhere = sqlite3ExprDup(db, pWhere, 0);
93428   pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
93429   if( pFrom ){
93430     assert( pFrom->nSrc==1 );
93431     pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
93432     pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
93433     assert( pFrom->a[0].pOn==0 );
93434     assert( pFrom->a[0].pUsing==0 );
93435   }
93436   pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
93437   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
93438   sqlite3Select(pParse, pSel, &dest);
93439   sqlite3SelectDelete(db, pSel);
93440 }
93441 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
93442 
93443 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
93444 /*
93445 ** Generate an expression tree to implement the WHERE, ORDER BY,
93446 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
93447 **
93448 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
93449 **                            \__________________________/
93450 **                               pLimitWhere (pInClause)
93451 */
93452 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
93453   Parse *pParse,               /* The parser context */
93454   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
93455   Expr *pWhere,                /* The WHERE clause.  May be null */
93456   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
93457   Expr *pLimit,                /* The LIMIT clause.  May be null */
93458   Expr *pOffset,               /* The OFFSET clause.  May be null */
93459   char *zStmtType              /* Either DELETE or UPDATE.  For err msgs. */
93460 ){
93461   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
93462   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
93463   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
93464   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
93465   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
93466   Select *pSelect = NULL;      /* Complete SELECT tree */
93467 
93468   /* Check that there isn't an ORDER BY without a LIMIT clause.
93469   */
93470   if( pOrderBy && (pLimit == 0) ) {
93471     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
93472     goto limit_where_cleanup_2;
93473   }
93474 
93475   /* We only need to generate a select expression if there
93476   ** is a limit/offset term to enforce.
93477   */
93478   if( pLimit == 0 ) {
93479     /* if pLimit is null, pOffset will always be null as well. */
93480     assert( pOffset == 0 );
93481     return pWhere;
93482   }
93483 
93484   /* Generate a select expression tree to enforce the limit/offset
93485   ** term for the DELETE or UPDATE statement.  For example:
93486   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
93487   ** becomes:
93488   **   DELETE FROM table_a WHERE rowid IN (
93489   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
93490   **   );
93491   */
93492 
93493   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
93494   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
93495   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
93496   if( pEList == 0 ) goto limit_where_cleanup_2;
93497 
93498   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
93499   ** and the SELECT subtree. */
93500   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
93501   if( pSelectSrc == 0 ) {
93502     sqlite3ExprListDelete(pParse->db, pEList);
93503     goto limit_where_cleanup_2;
93504   }
93505 
93506   /* generate the SELECT expression tree. */
93507   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
93508                              pOrderBy,0,pLimit,pOffset);
93509   if( pSelect == 0 ) return 0;
93510 
93511   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
93512   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
93513   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
93514   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
93515   if( pInClause == 0 ) goto limit_where_cleanup_1;
93516 
93517   pInClause->x.pSelect = pSelect;
93518   pInClause->flags |= EP_xIsSelect;
93519   sqlite3ExprSetHeight(pParse, pInClause);
93520   return pInClause;
93521 
93522   /* something went wrong. clean up anything allocated. */
93523 limit_where_cleanup_1:
93524   sqlite3SelectDelete(pParse->db, pSelect);
93525   return 0;
93526 
93527 limit_where_cleanup_2:
93528   sqlite3ExprDelete(pParse->db, pWhere);
93529   sqlite3ExprListDelete(pParse->db, pOrderBy);
93530   sqlite3ExprDelete(pParse->db, pLimit);
93531   sqlite3ExprDelete(pParse->db, pOffset);
93532   return 0;
93533 }
93534 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
93535        /*      && !defined(SQLITE_OMIT_SUBQUERY) */
93536 
93537 /*
93538 ** Generate code for a DELETE FROM statement.
93539 **
93540 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
93541 **                 \________/       \________________/
93542 **                  pTabList              pWhere
93543 */
93544 SQLITE_PRIVATE void sqlite3DeleteFrom(
93545   Parse *pParse,         /* The parser context */
93546   SrcList *pTabList,     /* The table from which we should delete things */
93547   Expr *pWhere           /* The WHERE clause.  May be null */
93548 ){
93549   Vdbe *v;               /* The virtual database engine */
93550   Table *pTab;           /* The table from which records will be deleted */
93551   const char *zDb;       /* Name of database holding pTab */
93552   int i;                 /* Loop counter */
93553   WhereInfo *pWInfo;     /* Information about the WHERE clause */
93554   Index *pIdx;           /* For looping over indices of the table */
93555   int iTabCur;           /* Cursor number for the table */
93556   int iDataCur;          /* VDBE cursor for the canonical data source */
93557   int iIdxCur;           /* Cursor number of the first index */
93558   int nIdx;              /* Number of indices */
93559   sqlite3 *db;           /* Main database structure */
93560   AuthContext sContext;  /* Authorization context */
93561   NameContext sNC;       /* Name context to resolve expressions in */
93562   int iDb;               /* Database number */
93563   int memCnt = -1;       /* Memory cell used for change counting */
93564   int rcauth;            /* Value returned by authorization callback */
93565   int okOnePass;         /* True for one-pass algorithm without the FIFO */
93566   int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
93567   u8 *aToOpen = 0;       /* Open cursor iTabCur+j if aToOpen[j] is true */
93568   Index *pPk;            /* The PRIMARY KEY index on the table */
93569   int iPk = 0;           /* First of nPk registers holding PRIMARY KEY value */
93570   i16 nPk = 1;           /* Number of columns in the PRIMARY KEY */
93571   int iKey;              /* Memory cell holding key of row to be deleted */
93572   i16 nKey;              /* Number of memory cells in the row key */
93573   int iEphCur = 0;       /* Ephemeral table holding all primary key values */
93574   int iRowSet = 0;       /* Register for rowset of rows to delete */
93575   int addrBypass = 0;    /* Address of jump over the delete logic */
93576   int addrLoop = 0;      /* Top of the delete loop */
93577   int addrDelete = 0;    /* Jump directly to the delete logic */
93578   int addrEphOpen = 0;   /* Instruction to open the Ephemeral table */
93579 
93580 #ifndef SQLITE_OMIT_TRIGGER
93581   int isView;                  /* True if attempting to delete from a view */
93582   Trigger *pTrigger;           /* List of table triggers, if required */
93583 #endif
93584 
93585   memset(&sContext, 0, sizeof(sContext));
93586   db = pParse->db;
93587   if( pParse->nErr || db->mallocFailed ){
93588     goto delete_from_cleanup;
93589   }
93590   assert( pTabList->nSrc==1 );
93591 
93592   /* Locate the table which we want to delete.  This table has to be
93593   ** put in an SrcList structure because some of the subroutines we
93594   ** will be calling are designed to work with multiple tables and expect
93595   ** an SrcList* parameter instead of just a Table* parameter.
93596   */
93597   pTab = sqlite3SrcListLookup(pParse, pTabList);
93598   if( pTab==0 )  goto delete_from_cleanup;
93599 
93600   /* Figure out if we have any triggers and if the table being
93601   ** deleted from is a view
93602   */
93603 #ifndef SQLITE_OMIT_TRIGGER
93604   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
93605   isView = pTab->pSelect!=0;
93606 #else
93607 # define pTrigger 0
93608 # define isView 0
93609 #endif
93610 #ifdef SQLITE_OMIT_VIEW
93611 # undef isView
93612 # define isView 0
93613 #endif
93614 
93615   /* If pTab is really a view, make sure it has been initialized.
93616   */
93617   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
93618     goto delete_from_cleanup;
93619   }
93620 
93621   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
93622     goto delete_from_cleanup;
93623   }
93624   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
93625   assert( iDb<db->nDb );
93626   zDb = db->aDb[iDb].zName;
93627   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
93628   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
93629   if( rcauth==SQLITE_DENY ){
93630     goto delete_from_cleanup;
93631   }
93632   assert(!isView || pTrigger);
93633 
93634   /* Assign cursor numbers to the table and all its indices.
93635   */
93636   assert( pTabList->nSrc==1 );
93637   iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
93638   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
93639     pParse->nTab++;
93640   }
93641 
93642   /* Start the view context
93643   */
93644   if( isView ){
93645     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
93646   }
93647 
93648   /* Begin generating code.
93649   */
93650   v = sqlite3GetVdbe(pParse);
93651   if( v==0 ){
93652     goto delete_from_cleanup;
93653   }
93654   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
93655   sqlite3BeginWriteOperation(pParse, 1, iDb);
93656 
93657   /* If we are trying to delete from a view, realize that view into
93658   ** an ephemeral table.
93659   */
93660 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
93661   if( isView ){
93662     sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
93663     iDataCur = iIdxCur = iTabCur;
93664   }
93665 #endif
93666 
93667   /* Resolve the column names in the WHERE clause.
93668   */
93669   memset(&sNC, 0, sizeof(sNC));
93670   sNC.pParse = pParse;
93671   sNC.pSrcList = pTabList;
93672   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
93673     goto delete_from_cleanup;
93674   }
93675 
93676   /* Initialize the counter of the number of rows deleted, if
93677   ** we are counting rows.
93678   */
93679   if( db->flags & SQLITE_CountRows ){
93680     memCnt = ++pParse->nMem;
93681     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
93682   }
93683 
93684 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
93685   /* Special case: A DELETE without a WHERE clause deletes everything.
93686   ** It is easier just to erase the whole table. Prior to version 3.6.5,
93687   ** this optimization caused the row change count (the value returned by
93688   ** API function sqlite3_count_changes) to be set incorrectly.  */
93689   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
93690    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
93691   ){
93692     assert( !isView );
93693     sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
93694     if( HasRowid(pTab) ){
93695       sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
93696                         pTab->zName, P4_STATIC);
93697     }
93698     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
93699       assert( pIdx->pSchema==pTab->pSchema );
93700       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
93701     }
93702   }else
93703 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
93704   {
93705     if( HasRowid(pTab) ){
93706       /* For a rowid table, initialize the RowSet to an empty set */
93707       pPk = 0;
93708       nPk = 1;
93709       iRowSet = ++pParse->nMem;
93710       sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
93711     }else{
93712       /* For a WITHOUT ROWID table, create an ephemeral table used to
93713       ** hold all primary keys for rows to be deleted. */
93714       pPk = sqlite3PrimaryKeyIndex(pTab);
93715       assert( pPk!=0 );
93716       nPk = pPk->nKeyCol;
93717       iPk = pParse->nMem+1;
93718       pParse->nMem += nPk;
93719       iEphCur = pParse->nTab++;
93720       addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
93721       sqlite3VdbeSetP4KeyInfo(pParse, pPk);
93722     }
93723 
93724     /* Construct a query to find the rowid or primary key for every row
93725     ** to be deleted, based on the WHERE clause.
93726     */
93727     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
93728                                WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK,
93729                                iTabCur+1);
93730     if( pWInfo==0 ) goto delete_from_cleanup;
93731     okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
93732 
93733     /* Keep track of the number of rows to be deleted */
93734     if( db->flags & SQLITE_CountRows ){
93735       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
93736     }
93737 
93738     /* Extract the rowid or primary key for the current row */
93739     if( pPk ){
93740       for(i=0; i<nPk; i++){
93741         sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
93742                                         pPk->aiColumn[i], iPk+i);
93743       }
93744       iKey = iPk;
93745     }else{
93746       iKey = pParse->nMem + 1;
93747       iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
93748       if( iKey>pParse->nMem ) pParse->nMem = iKey;
93749     }
93750 
93751     if( okOnePass ){
93752       /* For ONEPASS, no need to store the rowid/primary-key.  There is only
93753       ** one, so just keep it in its register(s) and fall through to the
93754       ** delete code.
93755       */
93756       nKey = nPk; /* OP_Found will use an unpacked key */
93757       aToOpen = sqlite3DbMallocRaw(db, nIdx+2);
93758       if( aToOpen==0 ){
93759         sqlite3WhereEnd(pWInfo);
93760         goto delete_from_cleanup;
93761       }
93762       memset(aToOpen, 1, nIdx+1);
93763       aToOpen[nIdx+1] = 0;
93764       if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
93765       if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
93766       if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
93767       addrDelete = sqlite3VdbeAddOp0(v, OP_Goto); /* Jump to DELETE logic */
93768     }else if( pPk ){
93769       /* Construct a composite key for the row to be deleted and remember it */
93770       iKey = ++pParse->nMem;
93771       nKey = 0;   /* Zero tells OP_Found to use a composite key */
93772       sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
93773                         sqlite3IndexAffinityStr(v, pPk), nPk);
93774       sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
93775     }else{
93776       /* Get the rowid of the row to be deleted and remember it in the RowSet */
93777       nKey = 1;  /* OP_Seek always uses a single rowid */
93778       sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
93779     }
93780 
93781     /* End of the WHERE loop */
93782     sqlite3WhereEnd(pWInfo);
93783     if( okOnePass ){
93784       /* Bypass the delete logic below if the WHERE loop found zero rows */
93785       addrBypass = sqlite3VdbeMakeLabel(v);
93786       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBypass);
93787       sqlite3VdbeJumpHere(v, addrDelete);
93788     }
93789 
93790     /* Unless this is a view, open cursors for the table we are
93791     ** deleting from and all its indices. If this is a view, then the
93792     ** only effect this statement has is to fire the INSTEAD OF
93793     ** triggers.
93794     */
93795     if( !isView ){
93796       testcase( IsVirtual(pTab) );
93797       sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iTabCur, aToOpen,
93798                                  &iDataCur, &iIdxCur);
93799       assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
93800       assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
93801     }
93802 
93803     /* Set up a loop over the rowids/primary-keys that were found in the
93804     ** where-clause loop above.
93805     */
93806     if( okOnePass ){
93807       /* Just one row.  Hence the top-of-loop is a no-op */
93808       assert( nKey==nPk );  /* OP_Found will use an unpacked key */
93809       assert( !IsVirtual(pTab) );
93810       if( aToOpen[iDataCur-iTabCur] ){
93811         assert( pPk!=0 || pTab->pSelect!=0 );
93812         sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
93813         VdbeCoverage(v);
93814       }
93815     }else if( pPk ){
93816       addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
93817       sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
93818       assert( nKey==0 );  /* OP_Found will use a composite key */
93819     }else{
93820       addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
93821       VdbeCoverage(v);
93822       assert( nKey==1 );
93823     }
93824 
93825     /* Delete the row */
93826 #ifndef SQLITE_OMIT_VIRTUALTABLE
93827     if( IsVirtual(pTab) ){
93828       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
93829       sqlite3VtabMakeWritable(pParse, pTab);
93830       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
93831       sqlite3VdbeChangeP5(v, OE_Abort);
93832       sqlite3MayAbort(pParse);
93833     }else
93834 #endif
93835     {
93836       int count = (pParse->nested==0);    /* True to count changes */
93837       sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
93838                                iKey, nKey, count, OE_Default, okOnePass);
93839     }
93840 
93841     /* End of the loop over all rowids/primary-keys. */
93842     if( okOnePass ){
93843       sqlite3VdbeResolveLabel(v, addrBypass);
93844     }else if( pPk ){
93845       sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
93846       sqlite3VdbeJumpHere(v, addrLoop);
93847     }else{
93848       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrLoop);
93849       sqlite3VdbeJumpHere(v, addrLoop);
93850     }
93851 
93852     /* Close the cursors open on the table and its indexes. */
93853     if( !isView && !IsVirtual(pTab) ){
93854       if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
93855       for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
93856         sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
93857       }
93858     }
93859   } /* End non-truncate path */
93860 
93861   /* Update the sqlite_sequence table by storing the content of the
93862   ** maximum rowid counter values recorded while inserting into
93863   ** autoincrement tables.
93864   */
93865   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
93866     sqlite3AutoincrementEnd(pParse);
93867   }
93868 
93869   /* Return the number of rows that were deleted. If this routine is
93870   ** generating code because of a call to sqlite3NestedParse(), do not
93871   ** invoke the callback function.
93872   */
93873   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
93874     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
93875     sqlite3VdbeSetNumCols(v, 1);
93876     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
93877   }
93878 
93879 delete_from_cleanup:
93880   sqlite3AuthContextPop(&sContext);
93881   sqlite3SrcListDelete(db, pTabList);
93882   sqlite3ExprDelete(db, pWhere);
93883   sqlite3DbFree(db, aToOpen);
93884   return;
93885 }
93886 /* Make sure "isView" and other macros defined above are undefined. Otherwise
93887 ** they may interfere with compilation of other functions in this file
93888 ** (or in another file, if this file becomes part of the amalgamation).  */
93889 #ifdef isView
93890  #undef isView
93891 #endif
93892 #ifdef pTrigger
93893  #undef pTrigger
93894 #endif
93895 
93896 /*
93897 ** This routine generates VDBE code that causes a single row of a
93898 ** single table to be deleted.  Both the original table entry and
93899 ** all indices are removed.
93900 **
93901 ** Preconditions:
93902 **
93903 **   1.  iDataCur is an open cursor on the btree that is the canonical data
93904 **       store for the table.  (This will be either the table itself,
93905 **       in the case of a rowid table, or the PRIMARY KEY index in the case
93906 **       of a WITHOUT ROWID table.)
93907 **
93908 **   2.  Read/write cursors for all indices of pTab must be open as
93909 **       cursor number iIdxCur+i for the i-th index.
93910 **
93911 **   3.  The primary key for the row to be deleted must be stored in a
93912 **       sequence of nPk memory cells starting at iPk.  If nPk==0 that means
93913 **       that a search record formed from OP_MakeRecord is contained in the
93914 **       single memory location iPk.
93915 */
93916 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
93917   Parse *pParse,     /* Parsing context */
93918   Table *pTab,       /* Table containing the row to be deleted */
93919   Trigger *pTrigger, /* List of triggers to (potentially) fire */
93920   int iDataCur,      /* Cursor from which column data is extracted */
93921   int iIdxCur,       /* First index cursor */
93922   int iPk,           /* First memory cell containing the PRIMARY KEY */
93923   i16 nPk,           /* Number of PRIMARY KEY memory cells */
93924   u8 count,          /* If non-zero, increment the row change counter */
93925   u8 onconf,         /* Default ON CONFLICT policy for triggers */
93926   u8 bNoSeek         /* iDataCur is already pointing to the row to delete */
93927 ){
93928   Vdbe *v = pParse->pVdbe;        /* Vdbe */
93929   int iOld = 0;                   /* First register in OLD.* array */
93930   int iLabel;                     /* Label resolved to end of generated code */
93931   u8 opSeek;                      /* Seek opcode */
93932 
93933   /* Vdbe is guaranteed to have been allocated by this stage. */
93934   assert( v );
93935   VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
93936                          iDataCur, iIdxCur, iPk, (int)nPk));
93937 
93938   /* Seek cursor iCur to the row to delete. If this row no longer exists
93939   ** (this can happen if a trigger program has already deleted it), do
93940   ** not attempt to delete it or fire any DELETE triggers.  */
93941   iLabel = sqlite3VdbeMakeLabel(v);
93942   opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
93943   if( !bNoSeek ){
93944     sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
93945     VdbeCoverageIf(v, opSeek==OP_NotExists);
93946     VdbeCoverageIf(v, opSeek==OP_NotFound);
93947   }
93948 
93949   /* If there are any triggers to fire, allocate a range of registers to
93950   ** use for the old.* references in the triggers.  */
93951   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
93952     u32 mask;                     /* Mask of OLD.* columns in use */
93953     int iCol;                     /* Iterator used while populating OLD.* */
93954     int addrStart;                /* Start of BEFORE trigger programs */
93955 
93956     /* TODO: Could use temporary registers here. Also could attempt to
93957     ** avoid copying the contents of the rowid register.  */
93958     mask = sqlite3TriggerColmask(
93959         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
93960     );
93961     mask |= sqlite3FkOldmask(pParse, pTab);
93962     iOld = pParse->nMem+1;
93963     pParse->nMem += (1 + pTab->nCol);
93964 
93965     /* Populate the OLD.* pseudo-table register array. These values will be
93966     ** used by any BEFORE and AFTER triggers that exist.  */
93967     sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
93968     for(iCol=0; iCol<pTab->nCol; iCol++){
93969       testcase( mask!=0xffffffff && iCol==31 );
93970       testcase( mask!=0xffffffff && iCol==32 );
93971       if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
93972         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
93973       }
93974     }
93975 
93976     /* Invoke BEFORE DELETE trigger programs. */
93977     addrStart = sqlite3VdbeCurrentAddr(v);
93978     sqlite3CodeRowTrigger(pParse, pTrigger,
93979         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
93980     );
93981 
93982     /* If any BEFORE triggers were coded, then seek the cursor to the
93983     ** row to be deleted again. It may be that the BEFORE triggers moved
93984     ** the cursor or of already deleted the row that the cursor was
93985     ** pointing to.
93986     */
93987     if( addrStart<sqlite3VdbeCurrentAddr(v) ){
93988       sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
93989       VdbeCoverageIf(v, opSeek==OP_NotExists);
93990       VdbeCoverageIf(v, opSeek==OP_NotFound);
93991     }
93992 
93993     /* Do FK processing. This call checks that any FK constraints that
93994     ** refer to this table (i.e. constraints attached to other tables)
93995     ** are not violated by deleting this row.  */
93996     sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
93997   }
93998 
93999   /* Delete the index and table entries. Skip this step if pTab is really
94000   ** a view (in which case the only effect of the DELETE statement is to
94001   ** fire the INSTEAD OF triggers).  */
94002   if( pTab->pSelect==0 ){
94003     sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
94004     sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
94005     if( count ){
94006       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
94007     }
94008   }
94009 
94010   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
94011   ** handle rows (possibly in other tables) that refer via a foreign key
94012   ** to the row just deleted. */
94013   sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
94014 
94015   /* Invoke AFTER DELETE trigger programs. */
94016   sqlite3CodeRowTrigger(pParse, pTrigger,
94017       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
94018   );
94019 
94020   /* Jump here if the row had already been deleted before any BEFORE
94021   ** trigger programs were invoked. Or if a trigger program throws a
94022   ** RAISE(IGNORE) exception.  */
94023   sqlite3VdbeResolveLabel(v, iLabel);
94024   VdbeModuleComment((v, "END: GenRowDel()"));
94025 }
94026 
94027 /*
94028 ** This routine generates VDBE code that causes the deletion of all
94029 ** index entries associated with a single row of a single table, pTab
94030 **
94031 ** Preconditions:
94032 **
94033 **   1.  A read/write cursor "iDataCur" must be open on the canonical storage
94034 **       btree for the table pTab.  (This will be either the table itself
94035 **       for rowid tables or to the primary key index for WITHOUT ROWID
94036 **       tables.)
94037 **
94038 **   2.  Read/write cursors for all indices of pTab must be open as
94039 **       cursor number iIdxCur+i for the i-th index.  (The pTab->pIndex
94040 **       index is the 0-th index.)
94041 **
94042 **   3.  The "iDataCur" cursor must be already be positioned on the row
94043 **       that is to be deleted.
94044 */
94045 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
94046   Parse *pParse,     /* Parsing and code generating context */
94047   Table *pTab,       /* Table containing the row to be deleted */
94048   int iDataCur,      /* Cursor of table holding data. */
94049   int iIdxCur,       /* First index cursor */
94050   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
94051 ){
94052   int i;             /* Index loop counter */
94053   int r1 = -1;       /* Register holding an index key */
94054   int iPartIdxLabel; /* Jump destination for skipping partial index entries */
94055   Index *pIdx;       /* Current index */
94056   Index *pPrior = 0; /* Prior index */
94057   Vdbe *v;           /* The prepared statement under construction */
94058   Index *pPk;        /* PRIMARY KEY index, or NULL for rowid tables */
94059 
94060   v = pParse->pVdbe;
94061   pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
94062   for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
94063     assert( iIdxCur+i!=iDataCur || pPk==pIdx );
94064     if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
94065     if( pIdx==pPk ) continue;
94066     VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
94067     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
94068                                  &iPartIdxLabel, pPrior, r1);
94069     sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
94070                       pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
94071     sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
94072     pPrior = pIdx;
94073   }
94074 }
94075 
94076 /*
94077 ** Generate code that will assemble an index key and stores it in register
94078 ** regOut.  The key with be for index pIdx which is an index on pTab.
94079 ** iCur is the index of a cursor open on the pTab table and pointing to
94080 ** the entry that needs indexing.  If pTab is a WITHOUT ROWID table, then
94081 ** iCur must be the cursor of the PRIMARY KEY index.
94082 **
94083 ** Return a register number which is the first in a block of
94084 ** registers that holds the elements of the index key.  The
94085 ** block of registers has already been deallocated by the time
94086 ** this routine returns.
94087 **
94088 ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
94089 ** to that label if pIdx is a partial index that should be skipped.
94090 ** The label should be resolved using sqlite3ResolvePartIdxLabel().
94091 ** A partial index should be skipped if its WHERE clause evaluates
94092 ** to false or null.  If pIdx is not a partial index, *piPartIdxLabel
94093 ** will be set to zero which is an empty label that is ignored by
94094 ** sqlite3ResolvePartIdxLabel().
94095 **
94096 ** The pPrior and regPrior parameters are used to implement a cache to
94097 ** avoid unnecessary register loads.  If pPrior is not NULL, then it is
94098 ** a pointer to a different index for which an index key has just been
94099 ** computed into register regPrior.  If the current pIdx index is generating
94100 ** its key into the same sequence of registers and if pPrior and pIdx share
94101 ** a column in common, then the register corresponding to that column already
94102 ** holds the correct value and the loading of that register is skipped.
94103 ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
94104 ** on a table with multiple indices, and especially with the ROWID or
94105 ** PRIMARY KEY columns of the index.
94106 */
94107 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
94108   Parse *pParse,       /* Parsing context */
94109   Index *pIdx,         /* The index for which to generate a key */
94110   int iDataCur,        /* Cursor number from which to take column data */
94111   int regOut,          /* Put the new key into this register if not 0 */
94112   int prefixOnly,      /* Compute only a unique prefix of the key */
94113   int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
94114   Index *pPrior,       /* Previously generated index key */
94115   int regPrior         /* Register holding previous generated key */
94116 ){
94117   Vdbe *v = pParse->pVdbe;
94118   int j;
94119   Table *pTab = pIdx->pTable;
94120   int regBase;
94121   int nCol;
94122 
94123   if( piPartIdxLabel ){
94124     if( pIdx->pPartIdxWhere ){
94125       *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
94126       pParse->iPartIdxTab = iDataCur;
94127       sqlite3ExprCachePush(pParse);
94128       sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
94129                          SQLITE_JUMPIFNULL);
94130     }else{
94131       *piPartIdxLabel = 0;
94132     }
94133   }
94134   nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
94135   regBase = sqlite3GetTempRange(pParse, nCol);
94136   if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
94137   for(j=0; j<nCol; j++){
94138     if( pPrior && pPrior->aiColumn[j]==pIdx->aiColumn[j] ) continue;
94139     sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pIdx->aiColumn[j],
94140                                     regBase+j);
94141     /* If the column affinity is REAL but the number is an integer, then it
94142     ** might be stored in the table as an integer (using a compact
94143     ** representation) then converted to REAL by an OP_RealAffinity opcode.
94144     ** But we are getting ready to store this value back into an index, where
94145     ** it should be converted by to INTEGER again.  So omit the OP_RealAffinity
94146     ** opcode if it is present */
94147     sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
94148   }
94149   if( regOut ){
94150     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
94151   }
94152   sqlite3ReleaseTempRange(pParse, regBase, nCol);
94153   return regBase;
94154 }
94155 
94156 /*
94157 ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
94158 ** because it was a partial index, then this routine should be called to
94159 ** resolve that label.
94160 */
94161 SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
94162   if( iLabel ){
94163     sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
94164     sqlite3ExprCachePop(pParse);
94165   }
94166 }
94167 
94168 /************** End of delete.c **********************************************/
94169 /************** Begin file func.c ********************************************/
94170 /*
94171 ** 2002 February 23
94172 **
94173 ** The author disclaims copyright to this source code.  In place of
94174 ** a legal notice, here is a blessing:
94175 **
94176 **    May you do good and not evil.
94177 **    May you find forgiveness for yourself and forgive others.
94178 **    May you share freely, never taking more than you give.
94179 **
94180 *************************************************************************
94181 ** This file contains the C-language implementations for many of the SQL
94182 ** functions of SQLite.  (Some function, and in particular the date and
94183 ** time functions, are implemented separately.)
94184 */
94185 /* #include <stdlib.h> */
94186 /* #include <assert.h> */
94187 
94188 /*
94189 ** Return the collating function associated with a function.
94190 */
94191 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
94192   VdbeOp *pOp = &context->pVdbe->aOp[context->iOp-1];
94193   assert( pOp->opcode==OP_CollSeq );
94194   assert( pOp->p4type==P4_COLLSEQ );
94195   return pOp->p4.pColl;
94196 }
94197 
94198 /*
94199 ** Indicate that the accumulator load should be skipped on this
94200 ** iteration of the aggregate loop.
94201 */
94202 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
94203   context->skipFlag = 1;
94204 }
94205 
94206 /*
94207 ** Implementation of the non-aggregate min() and max() functions
94208 */
94209 static void minmaxFunc(
94210   sqlite3_context *context,
94211   int argc,
94212   sqlite3_value **argv
94213 ){
94214   int i;
94215   int mask;    /* 0 for min() or 0xffffffff for max() */
94216   int iBest;
94217   CollSeq *pColl;
94218 
94219   assert( argc>1 );
94220   mask = sqlite3_user_data(context)==0 ? 0 : -1;
94221   pColl = sqlite3GetFuncCollSeq(context);
94222   assert( pColl );
94223   assert( mask==-1 || mask==0 );
94224   iBest = 0;
94225   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
94226   for(i=1; i<argc; i++){
94227     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
94228     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
94229       testcase( mask==0 );
94230       iBest = i;
94231     }
94232   }
94233   sqlite3_result_value(context, argv[iBest]);
94234 }
94235 
94236 /*
94237 ** Return the type of the argument.
94238 */
94239 static void typeofFunc(
94240   sqlite3_context *context,
94241   int NotUsed,
94242   sqlite3_value **argv
94243 ){
94244   const char *z = 0;
94245   UNUSED_PARAMETER(NotUsed);
94246   switch( sqlite3_value_type(argv[0]) ){
94247     case SQLITE_INTEGER: z = "integer"; break;
94248     case SQLITE_TEXT:    z = "text";    break;
94249     case SQLITE_FLOAT:   z = "real";    break;
94250     case SQLITE_BLOB:    z = "blob";    break;
94251     default:             z = "null";    break;
94252   }
94253   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
94254 }
94255 
94256 
94257 /*
94258 ** Implementation of the length() function
94259 */
94260 static void lengthFunc(
94261   sqlite3_context *context,
94262   int argc,
94263   sqlite3_value **argv
94264 ){
94265   int len;
94266 
94267   assert( argc==1 );
94268   UNUSED_PARAMETER(argc);
94269   switch( sqlite3_value_type(argv[0]) ){
94270     case SQLITE_BLOB:
94271     case SQLITE_INTEGER:
94272     case SQLITE_FLOAT: {
94273       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
94274       break;
94275     }
94276     case SQLITE_TEXT: {
94277       const unsigned char *z = sqlite3_value_text(argv[0]);
94278       if( z==0 ) return;
94279       len = 0;
94280       while( *z ){
94281         len++;
94282         SQLITE_SKIP_UTF8(z);
94283       }
94284       sqlite3_result_int(context, len);
94285       break;
94286     }
94287     default: {
94288       sqlite3_result_null(context);
94289       break;
94290     }
94291   }
94292 }
94293 
94294 /*
94295 ** Implementation of the abs() function.
94296 **
94297 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
94298 ** the numeric argument X.
94299 */
94300 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
94301   assert( argc==1 );
94302   UNUSED_PARAMETER(argc);
94303   switch( sqlite3_value_type(argv[0]) ){
94304     case SQLITE_INTEGER: {
94305       i64 iVal = sqlite3_value_int64(argv[0]);
94306       if( iVal<0 ){
94307         if( iVal==SMALLEST_INT64 ){
94308           /* IMP: R-31676-45509 If X is the integer -9223372036854775808
94309           ** then abs(X) throws an integer overflow error since there is no
94310           ** equivalent positive 64-bit two complement value. */
94311           sqlite3_result_error(context, "integer overflow", -1);
94312           return;
94313         }
94314         iVal = -iVal;
94315       }
94316       sqlite3_result_int64(context, iVal);
94317       break;
94318     }
94319     case SQLITE_NULL: {
94320       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
94321       sqlite3_result_null(context);
94322       break;
94323     }
94324     default: {
94325       /* Because sqlite3_value_double() returns 0.0 if the argument is not
94326       ** something that can be converted into a number, we have:
94327       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
94328       ** cannot be converted to a numeric value.
94329       */
94330       double rVal = sqlite3_value_double(argv[0]);
94331       if( rVal<0 ) rVal = -rVal;
94332       sqlite3_result_double(context, rVal);
94333       break;
94334     }
94335   }
94336 }
94337 
94338 /*
94339 ** Implementation of the instr() function.
94340 **
94341 ** instr(haystack,needle) finds the first occurrence of needle
94342 ** in haystack and returns the number of previous characters plus 1,
94343 ** or 0 if needle does not occur within haystack.
94344 **
94345 ** If both haystack and needle are BLOBs, then the result is one more than
94346 ** the number of bytes in haystack prior to the first occurrence of needle,
94347 ** or 0 if needle never occurs in haystack.
94348 */
94349 static void instrFunc(
94350   sqlite3_context *context,
94351   int argc,
94352   sqlite3_value **argv
94353 ){
94354   const unsigned char *zHaystack;
94355   const unsigned char *zNeedle;
94356   int nHaystack;
94357   int nNeedle;
94358   int typeHaystack, typeNeedle;
94359   int N = 1;
94360   int isText;
94361 
94362   UNUSED_PARAMETER(argc);
94363   typeHaystack = sqlite3_value_type(argv[0]);
94364   typeNeedle = sqlite3_value_type(argv[1]);
94365   if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
94366   nHaystack = sqlite3_value_bytes(argv[0]);
94367   nNeedle = sqlite3_value_bytes(argv[1]);
94368   if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
94369     zHaystack = sqlite3_value_blob(argv[0]);
94370     zNeedle = sqlite3_value_blob(argv[1]);
94371     isText = 0;
94372   }else{
94373     zHaystack = sqlite3_value_text(argv[0]);
94374     zNeedle = sqlite3_value_text(argv[1]);
94375     isText = 1;
94376   }
94377   while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
94378     N++;
94379     do{
94380       nHaystack--;
94381       zHaystack++;
94382     }while( isText && (zHaystack[0]&0xc0)==0x80 );
94383   }
94384   if( nNeedle>nHaystack ) N = 0;
94385   sqlite3_result_int(context, N);
94386 }
94387 
94388 /*
94389 ** Implementation of the printf() function.
94390 */
94391 static void printfFunc(
94392   sqlite3_context *context,
94393   int argc,
94394   sqlite3_value **argv
94395 ){
94396   PrintfArguments x;
94397   StrAccum str;
94398   const char *zFormat;
94399   int n;
94400 
94401   if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
94402     x.nArg = argc-1;
94403     x.nUsed = 0;
94404     x.apArg = argv+1;
94405     sqlite3StrAccumInit(&str, 0, 0, SQLITE_MAX_LENGTH);
94406     str.db = sqlite3_context_db_handle(context);
94407     sqlite3XPrintf(&str, SQLITE_PRINTF_SQLFUNC, zFormat, &x);
94408     n = str.nChar;
94409     sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
94410                         SQLITE_DYNAMIC);
94411   }
94412 }
94413 
94414 /*
94415 ** Implementation of the substr() function.
94416 **
94417 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
94418 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
94419 ** of x.  If x is text, then we actually count UTF-8 characters.
94420 ** If x is a blob, then we count bytes.
94421 **
94422 ** If p1 is negative, then we begin abs(p1) from the end of x[].
94423 **
94424 ** If p2 is negative, return the p2 characters preceding p1.
94425 */
94426 static void substrFunc(
94427   sqlite3_context *context,
94428   int argc,
94429   sqlite3_value **argv
94430 ){
94431   const unsigned char *z;
94432   const unsigned char *z2;
94433   int len;
94434   int p0type;
94435   i64 p1, p2;
94436   int negP2 = 0;
94437 
94438   assert( argc==3 || argc==2 );
94439   if( sqlite3_value_type(argv[1])==SQLITE_NULL
94440    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
94441   ){
94442     return;
94443   }
94444   p0type = sqlite3_value_type(argv[0]);
94445   p1 = sqlite3_value_int(argv[1]);
94446   if( p0type==SQLITE_BLOB ){
94447     len = sqlite3_value_bytes(argv[0]);
94448     z = sqlite3_value_blob(argv[0]);
94449     if( z==0 ) return;
94450     assert( len==sqlite3_value_bytes(argv[0]) );
94451   }else{
94452     z = sqlite3_value_text(argv[0]);
94453     if( z==0 ) return;
94454     len = 0;
94455     if( p1<0 ){
94456       for(z2=z; *z2; len++){
94457         SQLITE_SKIP_UTF8(z2);
94458       }
94459     }
94460   }
94461   if( argc==3 ){
94462     p2 = sqlite3_value_int(argv[2]);
94463     if( p2<0 ){
94464       p2 = -p2;
94465       negP2 = 1;
94466     }
94467   }else{
94468     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
94469   }
94470   if( p1<0 ){
94471     p1 += len;
94472     if( p1<0 ){
94473       p2 += p1;
94474       if( p2<0 ) p2 = 0;
94475       p1 = 0;
94476     }
94477   }else if( p1>0 ){
94478     p1--;
94479   }else if( p2>0 ){
94480     p2--;
94481   }
94482   if( negP2 ){
94483     p1 -= p2;
94484     if( p1<0 ){
94485       p2 += p1;
94486       p1 = 0;
94487     }
94488   }
94489   assert( p1>=0 && p2>=0 );
94490   if( p0type!=SQLITE_BLOB ){
94491     while( *z && p1 ){
94492       SQLITE_SKIP_UTF8(z);
94493       p1--;
94494     }
94495     for(z2=z; *z2 && p2; p2--){
94496       SQLITE_SKIP_UTF8(z2);
94497     }
94498     sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
94499                           SQLITE_UTF8);
94500   }else{
94501     if( p1+p2>len ){
94502       p2 = len-p1;
94503       if( p2<0 ) p2 = 0;
94504     }
94505     sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
94506   }
94507 }
94508 
94509 /*
94510 ** Implementation of the round() function
94511 */
94512 #ifndef SQLITE_OMIT_FLOATING_POINT
94513 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
94514   int n = 0;
94515   double r;
94516   char *zBuf;
94517   assert( argc==1 || argc==2 );
94518   if( argc==2 ){
94519     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
94520     n = sqlite3_value_int(argv[1]);
94521     if( n>30 ) n = 30;
94522     if( n<0 ) n = 0;
94523   }
94524   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
94525   r = sqlite3_value_double(argv[0]);
94526   /* If Y==0 and X will fit in a 64-bit int,
94527   ** handle the rounding directly,
94528   ** otherwise use printf.
94529   */
94530   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
94531     r = (double)((sqlite_int64)(r+0.5));
94532   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
94533     r = -(double)((sqlite_int64)((-r)+0.5));
94534   }else{
94535     zBuf = sqlite3_mprintf("%.*f",n,r);
94536     if( zBuf==0 ){
94537       sqlite3_result_error_nomem(context);
94538       return;
94539     }
94540     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
94541     sqlite3_free(zBuf);
94542   }
94543   sqlite3_result_double(context, r);
94544 }
94545 #endif
94546 
94547 /*
94548 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
94549 ** allocation fails, call sqlite3_result_error_nomem() to notify
94550 ** the database handle that malloc() has failed and return NULL.
94551 ** If nByte is larger than the maximum string or blob length, then
94552 ** raise an SQLITE_TOOBIG exception and return NULL.
94553 */
94554 static void *contextMalloc(sqlite3_context *context, i64 nByte){
94555   char *z;
94556   sqlite3 *db = sqlite3_context_db_handle(context);
94557   assert( nByte>0 );
94558   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
94559   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
94560   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
94561     sqlite3_result_error_toobig(context);
94562     z = 0;
94563   }else{
94564     z = sqlite3Malloc(nByte);
94565     if( !z ){
94566       sqlite3_result_error_nomem(context);
94567     }
94568   }
94569   return z;
94570 }
94571 
94572 /*
94573 ** Implementation of the upper() and lower() SQL functions.
94574 */
94575 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
94576   char *z1;
94577   const char *z2;
94578   int i, n;
94579   UNUSED_PARAMETER(argc);
94580   z2 = (char*)sqlite3_value_text(argv[0]);
94581   n = sqlite3_value_bytes(argv[0]);
94582   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
94583   assert( z2==(char*)sqlite3_value_text(argv[0]) );
94584   if( z2 ){
94585     z1 = contextMalloc(context, ((i64)n)+1);
94586     if( z1 ){
94587       for(i=0; i<n; i++){
94588         z1[i] = (char)sqlite3Toupper(z2[i]);
94589       }
94590       sqlite3_result_text(context, z1, n, sqlite3_free);
94591     }
94592   }
94593 }
94594 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
94595   char *z1;
94596   const char *z2;
94597   int i, n;
94598   UNUSED_PARAMETER(argc);
94599   z2 = (char*)sqlite3_value_text(argv[0]);
94600   n = sqlite3_value_bytes(argv[0]);
94601   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
94602   assert( z2==(char*)sqlite3_value_text(argv[0]) );
94603   if( z2 ){
94604     z1 = contextMalloc(context, ((i64)n)+1);
94605     if( z1 ){
94606       for(i=0; i<n; i++){
94607         z1[i] = sqlite3Tolower(z2[i]);
94608       }
94609       sqlite3_result_text(context, z1, n, sqlite3_free);
94610     }
94611   }
94612 }
94613 
94614 /*
94615 ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
94616 ** as VDBE code so that unused argument values do not have to be computed.
94617 ** However, we still need some kind of function implementation for this
94618 ** routines in the function table.  The noopFunc macro provides this.
94619 ** noopFunc will never be called so it doesn't matter what the implementation
94620 ** is.  We might as well use the "version()" function as a substitute.
94621 */
94622 #define noopFunc versionFunc   /* Substitute function - never called */
94623 
94624 /*
94625 ** Implementation of random().  Return a random integer.
94626 */
94627 static void randomFunc(
94628   sqlite3_context *context,
94629   int NotUsed,
94630   sqlite3_value **NotUsed2
94631 ){
94632   sqlite_int64 r;
94633   UNUSED_PARAMETER2(NotUsed, NotUsed2);
94634   sqlite3_randomness(sizeof(r), &r);
94635   if( r<0 ){
94636     /* We need to prevent a random number of 0x8000000000000000
94637     ** (or -9223372036854775808) since when you do abs() of that
94638     ** number of you get the same value back again.  To do this
94639     ** in a way that is testable, mask the sign bit off of negative
94640     ** values, resulting in a positive value.  Then take the
94641     ** 2s complement of that positive value.  The end result can
94642     ** therefore be no less than -9223372036854775807.
94643     */
94644     r = -(r & LARGEST_INT64);
94645   }
94646   sqlite3_result_int64(context, r);
94647 }
94648 
94649 /*
94650 ** Implementation of randomblob(N).  Return a random blob
94651 ** that is N bytes long.
94652 */
94653 static void randomBlob(
94654   sqlite3_context *context,
94655   int argc,
94656   sqlite3_value **argv
94657 ){
94658   int n;
94659   unsigned char *p;
94660   assert( argc==1 );
94661   UNUSED_PARAMETER(argc);
94662   n = sqlite3_value_int(argv[0]);
94663   if( n<1 ){
94664     n = 1;
94665   }
94666   p = contextMalloc(context, n);
94667   if( p ){
94668     sqlite3_randomness(n, p);
94669     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
94670   }
94671 }
94672 
94673 /*
94674 ** Implementation of the last_insert_rowid() SQL function.  The return
94675 ** value is the same as the sqlite3_last_insert_rowid() API function.
94676 */
94677 static void last_insert_rowid(
94678   sqlite3_context *context,
94679   int NotUsed,
94680   sqlite3_value **NotUsed2
94681 ){
94682   sqlite3 *db = sqlite3_context_db_handle(context);
94683   UNUSED_PARAMETER2(NotUsed, NotUsed2);
94684   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
94685   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
94686   ** function. */
94687   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
94688 }
94689 
94690 /*
94691 ** Implementation of the changes() SQL function.
94692 **
94693 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
94694 ** around the sqlite3_changes() C/C++ function and hence follows the same
94695 ** rules for counting changes.
94696 */
94697 static void changes(
94698   sqlite3_context *context,
94699   int NotUsed,
94700   sqlite3_value **NotUsed2
94701 ){
94702   sqlite3 *db = sqlite3_context_db_handle(context);
94703   UNUSED_PARAMETER2(NotUsed, NotUsed2);
94704   sqlite3_result_int(context, sqlite3_changes(db));
94705 }
94706 
94707 /*
94708 ** Implementation of the total_changes() SQL function.  The return value is
94709 ** the same as the sqlite3_total_changes() API function.
94710 */
94711 static void total_changes(
94712   sqlite3_context *context,
94713   int NotUsed,
94714   sqlite3_value **NotUsed2
94715 ){
94716   sqlite3 *db = sqlite3_context_db_handle(context);
94717   UNUSED_PARAMETER2(NotUsed, NotUsed2);
94718   /* IMP: R-52756-41993 This function is a wrapper around the
94719   ** sqlite3_total_changes() C/C++ interface. */
94720   sqlite3_result_int(context, sqlite3_total_changes(db));
94721 }
94722 
94723 /*
94724 ** A structure defining how to do GLOB-style comparisons.
94725 */
94726 struct compareInfo {
94727   u8 matchAll;
94728   u8 matchOne;
94729   u8 matchSet;
94730   u8 noCase;
94731 };
94732 
94733 /*
94734 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
94735 ** character is exactly one byte in size.  Also, all characters are
94736 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
94737 ** whereas only characters less than 0x80 do in ASCII.
94738 */
94739 #if defined(SQLITE_EBCDIC)
94740 # define sqlite3Utf8Read(A)        (*((*A)++))
94741 # define GlobUpperToLower(A)       A = sqlite3UpperToLower[A]
94742 # define GlobUpperToLowerAscii(A)  A = sqlite3UpperToLower[A]
94743 #else
94744 # define GlobUpperToLower(A)       if( A<=0x7f ){ A = sqlite3UpperToLower[A]; }
94745 # define GlobUpperToLowerAscii(A)  A = sqlite3UpperToLower[A]
94746 #endif
94747 
94748 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
94749 /* The correct SQL-92 behavior is for the LIKE operator to ignore
94750 ** case.  Thus  'a' LIKE 'A' would be true. */
94751 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
94752 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
94753 ** is case sensitive causing 'a' LIKE 'A' to be false */
94754 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
94755 
94756 /*
94757 ** Compare two UTF-8 strings for equality where the first string can
94758 ** potentially be a "glob" or "like" expression.  Return true (1) if they
94759 ** are the same and false (0) if they are different.
94760 **
94761 ** Globbing rules:
94762 **
94763 **      '*'       Matches any sequence of zero or more characters.
94764 **
94765 **      '?'       Matches exactly one character.
94766 **
94767 **     [...]      Matches one character from the enclosed list of
94768 **                characters.
94769 **
94770 **     [^...]     Matches one character not in the enclosed list.
94771 **
94772 ** With the [...] and [^...] matching, a ']' character can be included
94773 ** in the list by making it the first character after '[' or '^'.  A
94774 ** range of characters can be specified using '-'.  Example:
94775 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
94776 ** it the last character in the list.
94777 **
94778 ** Like matching rules:
94779 **
94780 **      '%'       Matches any sequence of zero or more characters
94781 **
94782 ***     '_'       Matches any one character
94783 **
94784 **      Ec        Where E is the "esc" character and c is any other
94785 **                character, including '%', '_', and esc, match exactly c.
94786 **
94787 ** The comments through this routine usually assume glob matching.
94788 **
94789 ** This routine is usually quick, but can be N**2 in the worst case.
94790 */
94791 static int patternCompare(
94792   const u8 *zPattern,              /* The glob pattern */
94793   const u8 *zString,               /* The string to compare against the glob */
94794   const struct compareInfo *pInfo, /* Information about how to do the compare */
94795   u32 esc                          /* The escape character */
94796 ){
94797   u32 c, c2;                       /* Next pattern and input string chars */
94798   u32 matchOne = pInfo->matchOne;  /* "?" or "_" */
94799   u32 matchAll = pInfo->matchAll;  /* "*" or "%" */
94800   u32 matchOther;                  /* "[" or the escape character */
94801   u8 noCase = pInfo->noCase;       /* True if uppercase==lowercase */
94802   const u8 *zEscaped = 0;          /* One past the last escaped input char */
94803 
94804   /* The GLOB operator does not have an ESCAPE clause.  And LIKE does not
94805   ** have the matchSet operator.  So we either have to look for one or
94806   ** the other, never both.  Hence the single variable matchOther is used
94807   ** to store the one we have to look for.
94808   */
94809   matchOther = esc ? esc : pInfo->matchSet;
94810 
94811   while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
94812     if( c==matchAll ){  /* Match "*" */
94813       /* Skip over multiple "*" characters in the pattern.  If there
94814       ** are also "?" characters, skip those as well, but consume a
94815       ** single character of the input string for each "?" skipped */
94816       while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
94817                || c == matchOne ){
94818         if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
94819           return 0;
94820         }
94821       }
94822       if( c==0 ){
94823         return 1;   /* "*" at the end of the pattern matches */
94824       }else if( c==matchOther ){
94825         if( esc ){
94826           c = sqlite3Utf8Read(&zPattern);
94827           if( c==0 ) return 0;
94828         }else{
94829           /* "[...]" immediately follows the "*".  We have to do a slow
94830           ** recursive search in this case, but it is an unusual case. */
94831           assert( matchOther<0x80 );  /* '[' is a single-byte character */
94832           while( *zString
94833                  && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
94834             SQLITE_SKIP_UTF8(zString);
94835           }
94836           return *zString!=0;
94837         }
94838       }
94839 
94840       /* At this point variable c contains the first character of the
94841       ** pattern string past the "*".  Search in the input string for the
94842       ** first matching character and recursively contine the match from
94843       ** that point.
94844       **
94845       ** For a case-insensitive search, set variable cx to be the same as
94846       ** c but in the other case and search the input string for either
94847       ** c or cx.
94848       */
94849       if( c<=0x80 ){
94850         u32 cx;
94851         if( noCase ){
94852           cx = sqlite3Toupper(c);
94853           c = sqlite3Tolower(c);
94854         }else{
94855           cx = c;
94856         }
94857         while( (c2 = *(zString++))!=0 ){
94858           if( c2!=c && c2!=cx ) continue;
94859           if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
94860         }
94861       }else{
94862         while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
94863           if( c2!=c ) continue;
94864           if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
94865         }
94866       }
94867       return 0;
94868     }
94869     if( c==matchOther ){
94870       if( esc ){
94871         c = sqlite3Utf8Read(&zPattern);
94872         if( c==0 ) return 0;
94873         zEscaped = zPattern;
94874       }else{
94875         u32 prior_c = 0;
94876         int seen = 0;
94877         int invert = 0;
94878         c = sqlite3Utf8Read(&zString);
94879         if( c==0 ) return 0;
94880         c2 = sqlite3Utf8Read(&zPattern);
94881         if( c2=='^' ){
94882           invert = 1;
94883           c2 = sqlite3Utf8Read(&zPattern);
94884         }
94885         if( c2==']' ){
94886           if( c==']' ) seen = 1;
94887           c2 = sqlite3Utf8Read(&zPattern);
94888         }
94889         while( c2 && c2!=']' ){
94890           if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
94891             c2 = sqlite3Utf8Read(&zPattern);
94892             if( c>=prior_c && c<=c2 ) seen = 1;
94893             prior_c = 0;
94894           }else{
94895             if( c==c2 ){
94896               seen = 1;
94897             }
94898             prior_c = c2;
94899           }
94900           c2 = sqlite3Utf8Read(&zPattern);
94901         }
94902         if( c2==0 || (seen ^ invert)==0 ){
94903           return 0;
94904         }
94905         continue;
94906       }
94907     }
94908     c2 = sqlite3Utf8Read(&zString);
94909     if( c==c2 ) continue;
94910     if( noCase && c<0x80 && c2<0x80 && sqlite3Tolower(c)==sqlite3Tolower(c2) ){
94911       continue;
94912     }
94913     if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
94914     return 0;
94915   }
94916   return *zString==0;
94917 }
94918 
94919 /*
94920 ** The sqlite3_strglob() interface.
94921 */
94922 SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
94923   return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
94924 }
94925 
94926 /*
94927 ** Count the number of times that the LIKE operator (or GLOB which is
94928 ** just a variation of LIKE) gets called.  This is used for testing
94929 ** only.
94930 */
94931 #ifdef SQLITE_TEST
94932 SQLITE_API int sqlite3_like_count = 0;
94933 #endif
94934 
94935 
94936 /*
94937 ** Implementation of the like() SQL function.  This function implements
94938 ** the build-in LIKE operator.  The first argument to the function is the
94939 ** pattern and the second argument is the string.  So, the SQL statements:
94940 **
94941 **       A LIKE B
94942 **
94943 ** is implemented as like(B,A).
94944 **
94945 ** This same function (with a different compareInfo structure) computes
94946 ** the GLOB operator.
94947 */
94948 static void likeFunc(
94949   sqlite3_context *context,
94950   int argc,
94951   sqlite3_value **argv
94952 ){
94953   const unsigned char *zA, *zB;
94954   u32 escape = 0;
94955   int nPat;
94956   sqlite3 *db = sqlite3_context_db_handle(context);
94957 
94958   zB = sqlite3_value_text(argv[0]);
94959   zA = sqlite3_value_text(argv[1]);
94960 
94961   /* Limit the length of the LIKE or GLOB pattern to avoid problems
94962   ** of deep recursion and N*N behavior in patternCompare().
94963   */
94964   nPat = sqlite3_value_bytes(argv[0]);
94965   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
94966   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
94967   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
94968     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
94969     return;
94970   }
94971   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
94972 
94973   if( argc==3 ){
94974     /* The escape character string must consist of a single UTF-8 character.
94975     ** Otherwise, return an error.
94976     */
94977     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
94978     if( zEsc==0 ) return;
94979     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
94980       sqlite3_result_error(context,
94981           "ESCAPE expression must be a single character", -1);
94982       return;
94983     }
94984     escape = sqlite3Utf8Read(&zEsc);
94985   }
94986   if( zA && zB ){
94987     struct compareInfo *pInfo = sqlite3_user_data(context);
94988 #ifdef SQLITE_TEST
94989     sqlite3_like_count++;
94990 #endif
94991 
94992     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
94993   }
94994 }
94995 
94996 /*
94997 ** Implementation of the NULLIF(x,y) function.  The result is the first
94998 ** argument if the arguments are different.  The result is NULL if the
94999 ** arguments are equal to each other.
95000 */
95001 static void nullifFunc(
95002   sqlite3_context *context,
95003   int NotUsed,
95004   sqlite3_value **argv
95005 ){
95006   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
95007   UNUSED_PARAMETER(NotUsed);
95008   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
95009     sqlite3_result_value(context, argv[0]);
95010   }
95011 }
95012 
95013 /*
95014 ** Implementation of the sqlite_version() function.  The result is the version
95015 ** of the SQLite library that is running.
95016 */
95017 static void versionFunc(
95018   sqlite3_context *context,
95019   int NotUsed,
95020   sqlite3_value **NotUsed2
95021 ){
95022   UNUSED_PARAMETER2(NotUsed, NotUsed2);
95023   /* IMP: R-48699-48617 This function is an SQL wrapper around the
95024   ** sqlite3_libversion() C-interface. */
95025   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
95026 }
95027 
95028 /*
95029 ** Implementation of the sqlite_source_id() function. The result is a string
95030 ** that identifies the particular version of the source code used to build
95031 ** SQLite.
95032 */
95033 static void sourceidFunc(
95034   sqlite3_context *context,
95035   int NotUsed,
95036   sqlite3_value **NotUsed2
95037 ){
95038   UNUSED_PARAMETER2(NotUsed, NotUsed2);
95039   /* IMP: R-24470-31136 This function is an SQL wrapper around the
95040   ** sqlite3_sourceid() C interface. */
95041   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
95042 }
95043 
95044 /*
95045 ** Implementation of the sqlite_log() function.  This is a wrapper around
95046 ** sqlite3_log().  The return value is NULL.  The function exists purely for
95047 ** its side-effects.
95048 */
95049 static void errlogFunc(
95050   sqlite3_context *context,
95051   int argc,
95052   sqlite3_value **argv
95053 ){
95054   UNUSED_PARAMETER(argc);
95055   UNUSED_PARAMETER(context);
95056   sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
95057 }
95058 
95059 /*
95060 ** Implementation of the sqlite_compileoption_used() function.
95061 ** The result is an integer that identifies if the compiler option
95062 ** was used to build SQLite.
95063 */
95064 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
95065 static void compileoptionusedFunc(
95066   sqlite3_context *context,
95067   int argc,
95068   sqlite3_value **argv
95069 ){
95070   const char *zOptName;
95071   assert( argc==1 );
95072   UNUSED_PARAMETER(argc);
95073   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
95074   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
95075   ** function.
95076   */
95077   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
95078     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
95079   }
95080 }
95081 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
95082 
95083 /*
95084 ** Implementation of the sqlite_compileoption_get() function.
95085 ** The result is a string that identifies the compiler options
95086 ** used to build SQLite.
95087 */
95088 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
95089 static void compileoptiongetFunc(
95090   sqlite3_context *context,
95091   int argc,
95092   sqlite3_value **argv
95093 ){
95094   int n;
95095   assert( argc==1 );
95096   UNUSED_PARAMETER(argc);
95097   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
95098   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
95099   */
95100   n = sqlite3_value_int(argv[0]);
95101   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
95102 }
95103 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
95104 
95105 /* Array for converting from half-bytes (nybbles) into ASCII hex
95106 ** digits. */
95107 static const char hexdigits[] = {
95108   '0', '1', '2', '3', '4', '5', '6', '7',
95109   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
95110 };
95111 
95112 /*
95113 ** Implementation of the QUOTE() function.  This function takes a single
95114 ** argument.  If the argument is numeric, the return value is the same as
95115 ** the argument.  If the argument is NULL, the return value is the string
95116 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
95117 ** single-quote escapes.
95118 */
95119 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
95120   assert( argc==1 );
95121   UNUSED_PARAMETER(argc);
95122   switch( sqlite3_value_type(argv[0]) ){
95123     case SQLITE_FLOAT: {
95124       double r1, r2;
95125       char zBuf[50];
95126       r1 = sqlite3_value_double(argv[0]);
95127       sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
95128       sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
95129       if( r1!=r2 ){
95130         sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
95131       }
95132       sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
95133       break;
95134     }
95135     case SQLITE_INTEGER: {
95136       sqlite3_result_value(context, argv[0]);
95137       break;
95138     }
95139     case SQLITE_BLOB: {
95140       char *zText = 0;
95141       char const *zBlob = sqlite3_value_blob(argv[0]);
95142       int nBlob = sqlite3_value_bytes(argv[0]);
95143       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
95144       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
95145       if( zText ){
95146         int i;
95147         for(i=0; i<nBlob; i++){
95148           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
95149           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
95150         }
95151         zText[(nBlob*2)+2] = '\'';
95152         zText[(nBlob*2)+3] = '\0';
95153         zText[0] = 'X';
95154         zText[1] = '\'';
95155         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
95156         sqlite3_free(zText);
95157       }
95158       break;
95159     }
95160     case SQLITE_TEXT: {
95161       int i,j;
95162       u64 n;
95163       const unsigned char *zArg = sqlite3_value_text(argv[0]);
95164       char *z;
95165 
95166       if( zArg==0 ) return;
95167       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
95168       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
95169       if( z ){
95170         z[0] = '\'';
95171         for(i=0, j=1; zArg[i]; i++){
95172           z[j++] = zArg[i];
95173           if( zArg[i]=='\'' ){
95174             z[j++] = '\'';
95175           }
95176         }
95177         z[j++] = '\'';
95178         z[j] = 0;
95179         sqlite3_result_text(context, z, j, sqlite3_free);
95180       }
95181       break;
95182     }
95183     default: {
95184       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
95185       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
95186       break;
95187     }
95188   }
95189 }
95190 
95191 /*
95192 ** The unicode() function.  Return the integer unicode code-point value
95193 ** for the first character of the input string.
95194 */
95195 static void unicodeFunc(
95196   sqlite3_context *context,
95197   int argc,
95198   sqlite3_value **argv
95199 ){
95200   const unsigned char *z = sqlite3_value_text(argv[0]);
95201   (void)argc;
95202   if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
95203 }
95204 
95205 /*
95206 ** The char() function takes zero or more arguments, each of which is
95207 ** an integer.  It constructs a string where each character of the string
95208 ** is the unicode character for the corresponding integer argument.
95209 */
95210 static void charFunc(
95211   sqlite3_context *context,
95212   int argc,
95213   sqlite3_value **argv
95214 ){
95215   unsigned char *z, *zOut;
95216   int i;
95217   zOut = z = sqlite3_malloc( argc*4+1 );
95218   if( z==0 ){
95219     sqlite3_result_error_nomem(context);
95220     return;
95221   }
95222   for(i=0; i<argc; i++){
95223     sqlite3_int64 x;
95224     unsigned c;
95225     x = sqlite3_value_int64(argv[i]);
95226     if( x<0 || x>0x10ffff ) x = 0xfffd;
95227     c = (unsigned)(x & 0x1fffff);
95228     if( c<0x00080 ){
95229       *zOut++ = (u8)(c&0xFF);
95230     }else if( c<0x00800 ){
95231       *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
95232       *zOut++ = 0x80 + (u8)(c & 0x3F);
95233     }else if( c<0x10000 ){
95234       *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
95235       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
95236       *zOut++ = 0x80 + (u8)(c & 0x3F);
95237     }else{
95238       *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
95239       *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
95240       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
95241       *zOut++ = 0x80 + (u8)(c & 0x3F);
95242     }                                                    \
95243   }
95244   sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
95245 }
95246 
95247 /*
95248 ** The hex() function.  Interpret the argument as a blob.  Return
95249 ** a hexadecimal rendering as text.
95250 */
95251 static void hexFunc(
95252   sqlite3_context *context,
95253   int argc,
95254   sqlite3_value **argv
95255 ){
95256   int i, n;
95257   const unsigned char *pBlob;
95258   char *zHex, *z;
95259   assert( argc==1 );
95260   UNUSED_PARAMETER(argc);
95261   pBlob = sqlite3_value_blob(argv[0]);
95262   n = sqlite3_value_bytes(argv[0]);
95263   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
95264   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
95265   if( zHex ){
95266     for(i=0; i<n; i++, pBlob++){
95267       unsigned char c = *pBlob;
95268       *(z++) = hexdigits[(c>>4)&0xf];
95269       *(z++) = hexdigits[c&0xf];
95270     }
95271     *z = 0;
95272     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
95273   }
95274 }
95275 
95276 /*
95277 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
95278 */
95279 static void zeroblobFunc(
95280   sqlite3_context *context,
95281   int argc,
95282   sqlite3_value **argv
95283 ){
95284   i64 n;
95285   sqlite3 *db = sqlite3_context_db_handle(context);
95286   assert( argc==1 );
95287   UNUSED_PARAMETER(argc);
95288   n = sqlite3_value_int64(argv[0]);
95289   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
95290   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
95291   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
95292     sqlite3_result_error_toobig(context);
95293   }else{
95294     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
95295   }
95296 }
95297 
95298 /*
95299 ** The replace() function.  Three arguments are all strings: call
95300 ** them A, B, and C. The result is also a string which is derived
95301 ** from A by replacing every occurrence of B with C.  The match
95302 ** must be exact.  Collating sequences are not used.
95303 */
95304 static void replaceFunc(
95305   sqlite3_context *context,
95306   int argc,
95307   sqlite3_value **argv
95308 ){
95309   const unsigned char *zStr;        /* The input string A */
95310   const unsigned char *zPattern;    /* The pattern string B */
95311   const unsigned char *zRep;        /* The replacement string C */
95312   unsigned char *zOut;              /* The output */
95313   int nStr;                /* Size of zStr */
95314   int nPattern;            /* Size of zPattern */
95315   int nRep;                /* Size of zRep */
95316   i64 nOut;                /* Maximum size of zOut */
95317   int loopLimit;           /* Last zStr[] that might match zPattern[] */
95318   int i, j;                /* Loop counters */
95319 
95320   assert( argc==3 );
95321   UNUSED_PARAMETER(argc);
95322   zStr = sqlite3_value_text(argv[0]);
95323   if( zStr==0 ) return;
95324   nStr = sqlite3_value_bytes(argv[0]);
95325   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
95326   zPattern = sqlite3_value_text(argv[1]);
95327   if( zPattern==0 ){
95328     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
95329             || sqlite3_context_db_handle(context)->mallocFailed );
95330     return;
95331   }
95332   if( zPattern[0]==0 ){
95333     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
95334     sqlite3_result_value(context, argv[0]);
95335     return;
95336   }
95337   nPattern = sqlite3_value_bytes(argv[1]);
95338   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
95339   zRep = sqlite3_value_text(argv[2]);
95340   if( zRep==0 ) return;
95341   nRep = sqlite3_value_bytes(argv[2]);
95342   assert( zRep==sqlite3_value_text(argv[2]) );
95343   nOut = nStr + 1;
95344   assert( nOut<SQLITE_MAX_LENGTH );
95345   zOut = contextMalloc(context, (i64)nOut);
95346   if( zOut==0 ){
95347     return;
95348   }
95349   loopLimit = nStr - nPattern;
95350   for(i=j=0; i<=loopLimit; i++){
95351     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
95352       zOut[j++] = zStr[i];
95353     }else{
95354       u8 *zOld;
95355       sqlite3 *db = sqlite3_context_db_handle(context);
95356       nOut += nRep - nPattern;
95357       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
95358       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
95359       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
95360         sqlite3_result_error_toobig(context);
95361         sqlite3_free(zOut);
95362         return;
95363       }
95364       zOld = zOut;
95365       zOut = sqlite3_realloc(zOut, (int)nOut);
95366       if( zOut==0 ){
95367         sqlite3_result_error_nomem(context);
95368         sqlite3_free(zOld);
95369         return;
95370       }
95371       memcpy(&zOut[j], zRep, nRep);
95372       j += nRep;
95373       i += nPattern-1;
95374     }
95375   }
95376   assert( j+nStr-i+1==nOut );
95377   memcpy(&zOut[j], &zStr[i], nStr-i);
95378   j += nStr - i;
95379   assert( j<=nOut );
95380   zOut[j] = 0;
95381   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
95382 }
95383 
95384 /*
95385 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
95386 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
95387 */
95388 static void trimFunc(
95389   sqlite3_context *context,
95390   int argc,
95391   sqlite3_value **argv
95392 ){
95393   const unsigned char *zIn;         /* Input string */
95394   const unsigned char *zCharSet;    /* Set of characters to trim */
95395   int nIn;                          /* Number of bytes in input */
95396   int flags;                        /* 1: trimleft  2: trimright  3: trim */
95397   int i;                            /* Loop counter */
95398   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
95399   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
95400   int nChar;                        /* Number of characters in zCharSet */
95401 
95402   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
95403     return;
95404   }
95405   zIn = sqlite3_value_text(argv[0]);
95406   if( zIn==0 ) return;
95407   nIn = sqlite3_value_bytes(argv[0]);
95408   assert( zIn==sqlite3_value_text(argv[0]) );
95409   if( argc==1 ){
95410     static const unsigned char lenOne[] = { 1 };
95411     static unsigned char * const azOne[] = { (u8*)" " };
95412     nChar = 1;
95413     aLen = (u8*)lenOne;
95414     azChar = (unsigned char **)azOne;
95415     zCharSet = 0;
95416   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
95417     return;
95418   }else{
95419     const unsigned char *z;
95420     for(z=zCharSet, nChar=0; *z; nChar++){
95421       SQLITE_SKIP_UTF8(z);
95422     }
95423     if( nChar>0 ){
95424       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
95425       if( azChar==0 ){
95426         return;
95427       }
95428       aLen = (unsigned char*)&azChar[nChar];
95429       for(z=zCharSet, nChar=0; *z; nChar++){
95430         azChar[nChar] = (unsigned char *)z;
95431         SQLITE_SKIP_UTF8(z);
95432         aLen[nChar] = (u8)(z - azChar[nChar]);
95433       }
95434     }
95435   }
95436   if( nChar>0 ){
95437     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
95438     if( flags & 1 ){
95439       while( nIn>0 ){
95440         int len = 0;
95441         for(i=0; i<nChar; i++){
95442           len = aLen[i];
95443           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
95444         }
95445         if( i>=nChar ) break;
95446         zIn += len;
95447         nIn -= len;
95448       }
95449     }
95450     if( flags & 2 ){
95451       while( nIn>0 ){
95452         int len = 0;
95453         for(i=0; i<nChar; i++){
95454           len = aLen[i];
95455           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
95456         }
95457         if( i>=nChar ) break;
95458         nIn -= len;
95459       }
95460     }
95461     if( zCharSet ){
95462       sqlite3_free(azChar);
95463     }
95464   }
95465   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
95466 }
95467 
95468 
95469 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
95470 ** is only available if the SQLITE_SOUNDEX compile-time option is used
95471 ** when SQLite is built.
95472 */
95473 #ifdef SQLITE_SOUNDEX
95474 /*
95475 ** Compute the soundex encoding of a word.
95476 **
95477 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
95478 ** soundex encoding of the string X.
95479 */
95480 static void soundexFunc(
95481   sqlite3_context *context,
95482   int argc,
95483   sqlite3_value **argv
95484 ){
95485   char zResult[8];
95486   const u8 *zIn;
95487   int i, j;
95488   static const unsigned char iCode[] = {
95489     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
95490     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
95491     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
95492     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
95493     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
95494     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
95495     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
95496     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
95497   };
95498   assert( argc==1 );
95499   zIn = (u8*)sqlite3_value_text(argv[0]);
95500   if( zIn==0 ) zIn = (u8*)"";
95501   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
95502   if( zIn[i] ){
95503     u8 prevcode = iCode[zIn[i]&0x7f];
95504     zResult[0] = sqlite3Toupper(zIn[i]);
95505     for(j=1; j<4 && zIn[i]; i++){
95506       int code = iCode[zIn[i]&0x7f];
95507       if( code>0 ){
95508         if( code!=prevcode ){
95509           prevcode = code;
95510           zResult[j++] = code + '0';
95511         }
95512       }else{
95513         prevcode = 0;
95514       }
95515     }
95516     while( j<4 ){
95517       zResult[j++] = '0';
95518     }
95519     zResult[j] = 0;
95520     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
95521   }else{
95522     /* IMP: R-64894-50321 The string "?000" is returned if the argument
95523     ** is NULL or contains no ASCII alphabetic characters. */
95524     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
95525   }
95526 }
95527 #endif /* SQLITE_SOUNDEX */
95528 
95529 #ifndef SQLITE_OMIT_LOAD_EXTENSION
95530 /*
95531 ** A function that loads a shared-library extension then returns NULL.
95532 */
95533 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
95534   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
95535   const char *zProc;
95536   sqlite3 *db = sqlite3_context_db_handle(context);
95537   char *zErrMsg = 0;
95538 
95539   if( argc==2 ){
95540     zProc = (const char *)sqlite3_value_text(argv[1]);
95541   }else{
95542     zProc = 0;
95543   }
95544   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
95545     sqlite3_result_error(context, zErrMsg, -1);
95546     sqlite3_free(zErrMsg);
95547   }
95548 }
95549 #endif
95550 
95551 
95552 /*
95553 ** An instance of the following structure holds the context of a
95554 ** sum() or avg() aggregate computation.
95555 */
95556 typedef struct SumCtx SumCtx;
95557 struct SumCtx {
95558   double rSum;      /* Floating point sum */
95559   i64 iSum;         /* Integer sum */
95560   i64 cnt;          /* Number of elements summed */
95561   u8 overflow;      /* True if integer overflow seen */
95562   u8 approx;        /* True if non-integer value was input to the sum */
95563 };
95564 
95565 /*
95566 ** Routines used to compute the sum, average, and total.
95567 **
95568 ** The SUM() function follows the (broken) SQL standard which means
95569 ** that it returns NULL if it sums over no inputs.  TOTAL returns
95570 ** 0.0 in that case.  In addition, TOTAL always returns a float where
95571 ** SUM might return an integer if it never encounters a floating point
95572 ** value.  TOTAL never fails, but SUM might through an exception if
95573 ** it overflows an integer.
95574 */
95575 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
95576   SumCtx *p;
95577   int type;
95578   assert( argc==1 );
95579   UNUSED_PARAMETER(argc);
95580   p = sqlite3_aggregate_context(context, sizeof(*p));
95581   type = sqlite3_value_numeric_type(argv[0]);
95582   if( p && type!=SQLITE_NULL ){
95583     p->cnt++;
95584     if( type==SQLITE_INTEGER ){
95585       i64 v = sqlite3_value_int64(argv[0]);
95586       p->rSum += v;
95587       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
95588         p->overflow = 1;
95589       }
95590     }else{
95591       p->rSum += sqlite3_value_double(argv[0]);
95592       p->approx = 1;
95593     }
95594   }
95595 }
95596 static void sumFinalize(sqlite3_context *context){
95597   SumCtx *p;
95598   p = sqlite3_aggregate_context(context, 0);
95599   if( p && p->cnt>0 ){
95600     if( p->overflow ){
95601       sqlite3_result_error(context,"integer overflow",-1);
95602     }else if( p->approx ){
95603       sqlite3_result_double(context, p->rSum);
95604     }else{
95605       sqlite3_result_int64(context, p->iSum);
95606     }
95607   }
95608 }
95609 static void avgFinalize(sqlite3_context *context){
95610   SumCtx *p;
95611   p = sqlite3_aggregate_context(context, 0);
95612   if( p && p->cnt>0 ){
95613     sqlite3_result_double(context, p->rSum/(double)p->cnt);
95614   }
95615 }
95616 static void totalFinalize(sqlite3_context *context){
95617   SumCtx *p;
95618   p = sqlite3_aggregate_context(context, 0);
95619   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
95620   sqlite3_result_double(context, p ? p->rSum : (double)0);
95621 }
95622 
95623 /*
95624 ** The following structure keeps track of state information for the
95625 ** count() aggregate function.
95626 */
95627 typedef struct CountCtx CountCtx;
95628 struct CountCtx {
95629   i64 n;
95630 };
95631 
95632 /*
95633 ** Routines to implement the count() aggregate function.
95634 */
95635 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
95636   CountCtx *p;
95637   p = sqlite3_aggregate_context(context, sizeof(*p));
95638   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
95639     p->n++;
95640   }
95641 
95642 #ifndef SQLITE_OMIT_DEPRECATED
95643   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
95644   ** sure it still operates correctly, verify that its count agrees with our
95645   ** internal count when using count(*) and when the total count can be
95646   ** expressed as a 32-bit integer. */
95647   assert( argc==1 || p==0 || p->n>0x7fffffff
95648           || p->n==sqlite3_aggregate_count(context) );
95649 #endif
95650 }
95651 static void countFinalize(sqlite3_context *context){
95652   CountCtx *p;
95653   p = sqlite3_aggregate_context(context, 0);
95654   sqlite3_result_int64(context, p ? p->n : 0);
95655 }
95656 
95657 /*
95658 ** Routines to implement min() and max() aggregate functions.
95659 */
95660 static void minmaxStep(
95661   sqlite3_context *context,
95662   int NotUsed,
95663   sqlite3_value **argv
95664 ){
95665   Mem *pArg  = (Mem *)argv[0];
95666   Mem *pBest;
95667   UNUSED_PARAMETER(NotUsed);
95668 
95669   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
95670   if( !pBest ) return;
95671 
95672   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
95673     if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
95674   }else if( pBest->flags ){
95675     int max;
95676     int cmp;
95677     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
95678     /* This step function is used for both the min() and max() aggregates,
95679     ** the only difference between the two being that the sense of the
95680     ** comparison is inverted. For the max() aggregate, the
95681     ** sqlite3_user_data() function returns (void *)-1. For min() it
95682     ** returns (void *)db, where db is the sqlite3* database pointer.
95683     ** Therefore the next statement sets variable 'max' to 1 for the max()
95684     ** aggregate, or 0 for min().
95685     */
95686     max = sqlite3_user_data(context)!=0;
95687     cmp = sqlite3MemCompare(pBest, pArg, pColl);
95688     if( (max && cmp<0) || (!max && cmp>0) ){
95689       sqlite3VdbeMemCopy(pBest, pArg);
95690     }else{
95691       sqlite3SkipAccumulatorLoad(context);
95692     }
95693   }else{
95694     pBest->db = sqlite3_context_db_handle(context);
95695     sqlite3VdbeMemCopy(pBest, pArg);
95696   }
95697 }
95698 static void minMaxFinalize(sqlite3_context *context){
95699   sqlite3_value *pRes;
95700   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
95701   if( pRes ){
95702     if( pRes->flags ){
95703       sqlite3_result_value(context, pRes);
95704     }
95705     sqlite3VdbeMemRelease(pRes);
95706   }
95707 }
95708 
95709 /*
95710 ** group_concat(EXPR, ?SEPARATOR?)
95711 */
95712 static void groupConcatStep(
95713   sqlite3_context *context,
95714   int argc,
95715   sqlite3_value **argv
95716 ){
95717   const char *zVal;
95718   StrAccum *pAccum;
95719   const char *zSep;
95720   int nVal, nSep;
95721   assert( argc==1 || argc==2 );
95722   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
95723   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
95724 
95725   if( pAccum ){
95726     sqlite3 *db = sqlite3_context_db_handle(context);
95727     int firstTerm = pAccum->useMalloc==0;
95728     pAccum->useMalloc = 2;
95729     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
95730     if( !firstTerm ){
95731       if( argc==2 ){
95732         zSep = (char*)sqlite3_value_text(argv[1]);
95733         nSep = sqlite3_value_bytes(argv[1]);
95734       }else{
95735         zSep = ",";
95736         nSep = 1;
95737       }
95738       if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
95739     }
95740     zVal = (char*)sqlite3_value_text(argv[0]);
95741     nVal = sqlite3_value_bytes(argv[0]);
95742     if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
95743   }
95744 }
95745 static void groupConcatFinalize(sqlite3_context *context){
95746   StrAccum *pAccum;
95747   pAccum = sqlite3_aggregate_context(context, 0);
95748   if( pAccum ){
95749     if( pAccum->accError==STRACCUM_TOOBIG ){
95750       sqlite3_result_error_toobig(context);
95751     }else if( pAccum->accError==STRACCUM_NOMEM ){
95752       sqlite3_result_error_nomem(context);
95753     }else{
95754       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
95755                           sqlite3_free);
95756     }
95757   }
95758 }
95759 
95760 /*
95761 ** This routine does per-connection function registration.  Most
95762 ** of the built-in functions above are part of the global function set.
95763 ** This routine only deals with those that are not global.
95764 */
95765 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
95766   int rc = sqlite3_overload_function(db, "MATCH", 2);
95767   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
95768   if( rc==SQLITE_NOMEM ){
95769     db->mallocFailed = 1;
95770   }
95771 }
95772 
95773 /*
95774 ** Set the LIKEOPT flag on the 2-argument function with the given name.
95775 */
95776 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
95777   FuncDef *pDef;
95778   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
95779                              2, SQLITE_UTF8, 0);
95780   if( ALWAYS(pDef) ){
95781     pDef->funcFlags |= flagVal;
95782   }
95783 }
95784 
95785 /*
95786 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
95787 ** parameter determines whether or not the LIKE operator is case
95788 ** sensitive.  GLOB is always case sensitive.
95789 */
95790 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
95791   struct compareInfo *pInfo;
95792   if( caseSensitive ){
95793     pInfo = (struct compareInfo*)&likeInfoAlt;
95794   }else{
95795     pInfo = (struct compareInfo*)&likeInfoNorm;
95796   }
95797   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
95798   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
95799   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
95800       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
95801   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
95802   setLikeOptFlag(db, "like",
95803       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
95804 }
95805 
95806 /*
95807 ** pExpr points to an expression which implements a function.  If
95808 ** it is appropriate to apply the LIKE optimization to that function
95809 ** then set aWc[0] through aWc[2] to the wildcard characters and
95810 ** return TRUE.  If the function is not a LIKE-style function then
95811 ** return FALSE.
95812 */
95813 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
95814   FuncDef *pDef;
95815   if( pExpr->op!=TK_FUNCTION
95816    || !pExpr->x.pList
95817    || pExpr->x.pList->nExpr!=2
95818   ){
95819     return 0;
95820   }
95821   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
95822   pDef = sqlite3FindFunction(db, pExpr->u.zToken,
95823                              sqlite3Strlen30(pExpr->u.zToken),
95824                              2, SQLITE_UTF8, 0);
95825   if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
95826     return 0;
95827   }
95828 
95829   /* The memcpy() statement assumes that the wildcard characters are
95830   ** the first three statements in the compareInfo structure.  The
95831   ** asserts() that follow verify that assumption
95832   */
95833   memcpy(aWc, pDef->pUserData, 3);
95834   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
95835   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
95836   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
95837   *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
95838   return 1;
95839 }
95840 
95841 /*
95842 ** All of the FuncDef structures in the aBuiltinFunc[] array above
95843 ** to the global function hash table.  This occurs at start-time (as
95844 ** a consequence of calling sqlite3_initialize()).
95845 **
95846 ** After this routine runs
95847 */
95848 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
95849   /*
95850   ** The following array holds FuncDef structures for all of the functions
95851   ** defined in this file.
95852   **
95853   ** The array cannot be constant since changes are made to the
95854   ** FuncDef.pHash elements at start-time.  The elements of this array
95855   ** are read-only after initialization is complete.
95856   */
95857   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
95858     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
95859     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
95860     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
95861     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
95862     FUNCTION(trim,               1, 3, 0, trimFunc         ),
95863     FUNCTION(trim,               2, 3, 0, trimFunc         ),
95864     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
95865     FUNCTION(min,                0, 0, 1, 0                ),
95866     AGGREGATE2(min,              1, 0, 1, minmaxStep,      minMaxFinalize,
95867                                           SQLITE_FUNC_MINMAX ),
95868     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
95869     FUNCTION(max,                0, 1, 1, 0                ),
95870     AGGREGATE2(max,              1, 1, 1, minmaxStep,      minMaxFinalize,
95871                                           SQLITE_FUNC_MINMAX ),
95872     FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
95873     FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
95874     FUNCTION(instr,              2, 0, 0, instrFunc        ),
95875     FUNCTION(substr,             2, 0, 0, substrFunc       ),
95876     FUNCTION(substr,             3, 0, 0, substrFunc       ),
95877     FUNCTION(printf,            -1, 0, 0, printfFunc       ),
95878     FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
95879     FUNCTION(char,              -1, 0, 0, charFunc         ),
95880     FUNCTION(abs,                1, 0, 0, absFunc          ),
95881 #ifndef SQLITE_OMIT_FLOATING_POINT
95882     FUNCTION(round,              1, 0, 0, roundFunc        ),
95883     FUNCTION(round,              2, 0, 0, roundFunc        ),
95884 #endif
95885     FUNCTION(upper,              1, 0, 0, upperFunc        ),
95886     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
95887     FUNCTION(coalesce,           1, 0, 0, 0                ),
95888     FUNCTION(coalesce,           0, 0, 0, 0                ),
95889     FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
95890     FUNCTION(hex,                1, 0, 0, hexFunc          ),
95891     FUNCTION2(ifnull,            2, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
95892     FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
95893     FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
95894     FUNCTION2(likely,            1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
95895     VFUNCTION(random,            0, 0, 0, randomFunc       ),
95896     VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
95897     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
95898     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
95899     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
95900     FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
95901 #if SQLITE_USER_AUTHENTICATION
95902     FUNCTION(sqlite_crypt,       2, 0, 0, sqlite3CryptFunc ),
95903 #endif
95904 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
95905     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
95906     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
95907 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
95908     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
95909     VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
95910     VFUNCTION(changes,           0, 0, 0, changes          ),
95911     VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
95912     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
95913     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
95914   #ifdef SQLITE_SOUNDEX
95915     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
95916   #endif
95917   #ifndef SQLITE_OMIT_LOAD_EXTENSION
95918     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
95919     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
95920   #endif
95921     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
95922     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
95923     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
95924     AGGREGATE2(count,            0, 0, 0, countStep,       countFinalize,
95925                SQLITE_FUNC_COUNT  ),
95926     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
95927     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
95928     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
95929 
95930     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
95931   #ifdef SQLITE_CASE_SENSITIVE_LIKE
95932     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
95933     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
95934   #else
95935     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
95936     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
95937   #endif
95938   };
95939 
95940   int i;
95941   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
95942   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
95943 
95944   for(i=0; i<ArraySize(aBuiltinFunc); i++){
95945     sqlite3FuncDefInsert(pHash, &aFunc[i]);
95946   }
95947   sqlite3RegisterDateTimeFunctions();
95948 #ifndef SQLITE_OMIT_ALTERTABLE
95949   sqlite3AlterFunctions();
95950 #endif
95951 #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
95952   sqlite3AnalyzeFunctions();
95953 #endif
95954 }
95955 
95956 /************** End of func.c ************************************************/
95957 /************** Begin file fkey.c ********************************************/
95958 /*
95959 **
95960 ** The author disclaims copyright to this source code.  In place of
95961 ** a legal notice, here is a blessing:
95962 **
95963 **    May you do good and not evil.
95964 **    May you find forgiveness for yourself and forgive others.
95965 **    May you share freely, never taking more than you give.
95966 **
95967 *************************************************************************
95968 ** This file contains code used by the compiler to add foreign key
95969 ** support to compiled SQL statements.
95970 */
95971 
95972 #ifndef SQLITE_OMIT_FOREIGN_KEY
95973 #ifndef SQLITE_OMIT_TRIGGER
95974 
95975 /*
95976 ** Deferred and Immediate FKs
95977 ** --------------------------
95978 **
95979 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
95980 ** If an immediate foreign key constraint is violated,
95981 ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
95982 ** statement transaction rolled back. If a
95983 ** deferred foreign key constraint is violated, no action is taken
95984 ** immediately. However if the application attempts to commit the
95985 ** transaction before fixing the constraint violation, the attempt fails.
95986 **
95987 ** Deferred constraints are implemented using a simple counter associated
95988 ** with the database handle. The counter is set to zero each time a
95989 ** database transaction is opened. Each time a statement is executed
95990 ** that causes a foreign key violation, the counter is incremented. Each
95991 ** time a statement is executed that removes an existing violation from
95992 ** the database, the counter is decremented. When the transaction is
95993 ** committed, the commit fails if the current value of the counter is
95994 ** greater than zero. This scheme has two big drawbacks:
95995 **
95996 **   * When a commit fails due to a deferred foreign key constraint,
95997 **     there is no way to tell which foreign constraint is not satisfied,
95998 **     or which row it is not satisfied for.
95999 **
96000 **   * If the database contains foreign key violations when the
96001 **     transaction is opened, this may cause the mechanism to malfunction.
96002 **
96003 ** Despite these problems, this approach is adopted as it seems simpler
96004 ** than the alternatives.
96005 **
96006 ** INSERT operations:
96007 **
96008 **   I.1) For each FK for which the table is the child table, search
96009 **        the parent table for a match. If none is found increment the
96010 **        constraint counter.
96011 **
96012 **   I.2) For each FK for which the table is the parent table,
96013 **        search the child table for rows that correspond to the new
96014 **        row in the parent table. Decrement the counter for each row
96015 **        found (as the constraint is now satisfied).
96016 **
96017 ** DELETE operations:
96018 **
96019 **   D.1) For each FK for which the table is the child table,
96020 **        search the parent table for a row that corresponds to the
96021 **        deleted row in the child table. If such a row is not found,
96022 **        decrement the counter.
96023 **
96024 **   D.2) For each FK for which the table is the parent table, search
96025 **        the child table for rows that correspond to the deleted row
96026 **        in the parent table. For each found increment the counter.
96027 **
96028 ** UPDATE operations:
96029 **
96030 **   An UPDATE command requires that all 4 steps above are taken, but only
96031 **   for FK constraints for which the affected columns are actually
96032 **   modified (values must be compared at runtime).
96033 **
96034 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
96035 ** This simplifies the implementation a bit.
96036 **
96037 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
96038 ** resolution is considered to delete rows before the new row is inserted.
96039 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
96040 ** is thrown, even if the FK constraint would be satisfied after the new
96041 ** row is inserted.
96042 **
96043 ** Immediate constraints are usually handled similarly. The only difference
96044 ** is that the counter used is stored as part of each individual statement
96045 ** object (struct Vdbe). If, after the statement has run, its immediate
96046 ** constraint counter is greater than zero,
96047 ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
96048 ** and the statement transaction is rolled back. An exception is an INSERT
96049 ** statement that inserts a single row only (no triggers). In this case,
96050 ** instead of using a counter, an exception is thrown immediately if the
96051 ** INSERT violates a foreign key constraint. This is necessary as such
96052 ** an INSERT does not open a statement transaction.
96053 **
96054 ** TODO: How should dropping a table be handled? How should renaming a
96055 ** table be handled?
96056 **
96057 **
96058 ** Query API Notes
96059 ** ---------------
96060 **
96061 ** Before coding an UPDATE or DELETE row operation, the code-generator
96062 ** for those two operations needs to know whether or not the operation
96063 ** requires any FK processing and, if so, which columns of the original
96064 ** row are required by the FK processing VDBE code (i.e. if FKs were
96065 ** implemented using triggers, which of the old.* columns would be
96066 ** accessed). No information is required by the code-generator before
96067 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
96068 ** generation code to query for this information are:
96069 **
96070 **   sqlite3FkRequired() - Test to see if FK processing is required.
96071 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
96072 **
96073 **
96074 ** Externally accessible module functions
96075 ** --------------------------------------
96076 **
96077 **   sqlite3FkCheck()    - Check for foreign key violations.
96078 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
96079 **   sqlite3FkDelete()   - Delete an FKey structure.
96080 */
96081 
96082 /*
96083 ** VDBE Calling Convention
96084 ** -----------------------
96085 **
96086 ** Example:
96087 **
96088 **   For the following INSERT statement:
96089 **
96090 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
96091 **     INSERT INTO t1 VALUES(1, 2, 3.1);
96092 **
96093 **   Register (x):        2    (type integer)
96094 **   Register (x+1):      1    (type integer)
96095 **   Register (x+2):      NULL (type NULL)
96096 **   Register (x+3):      3.1  (type real)
96097 */
96098 
96099 /*
96100 ** A foreign key constraint requires that the key columns in the parent
96101 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
96102 ** Given that pParent is the parent table for foreign key constraint pFKey,
96103 ** search the schema for a unique index on the parent key columns.
96104 **
96105 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
96106 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
96107 ** is set to point to the unique index.
96108 **
96109 ** If the parent key consists of a single column (the foreign key constraint
96110 ** is not a composite foreign key), output variable *paiCol is set to NULL.
96111 ** Otherwise, it is set to point to an allocated array of size N, where
96112 ** N is the number of columns in the parent key. The first element of the
96113 ** array is the index of the child table column that is mapped by the FK
96114 ** constraint to the parent table column stored in the left-most column
96115 ** of index *ppIdx. The second element of the array is the index of the
96116 ** child table column that corresponds to the second left-most column of
96117 ** *ppIdx, and so on.
96118 **
96119 ** If the required index cannot be found, either because:
96120 **
96121 **   1) The named parent key columns do not exist, or
96122 **
96123 **   2) The named parent key columns do exist, but are not subject to a
96124 **      UNIQUE or PRIMARY KEY constraint, or
96125 **
96126 **   3) No parent key columns were provided explicitly as part of the
96127 **      foreign key definition, and the parent table does not have a
96128 **      PRIMARY KEY, or
96129 **
96130 **   4) No parent key columns were provided explicitly as part of the
96131 **      foreign key definition, and the PRIMARY KEY of the parent table
96132 **      consists of a different number of columns to the child key in
96133 **      the child table.
96134 **
96135 ** then non-zero is returned, and a "foreign key mismatch" error loaded
96136 ** into pParse. If an OOM error occurs, non-zero is returned and the
96137 ** pParse->db->mallocFailed flag is set.
96138 */
96139 SQLITE_PRIVATE int sqlite3FkLocateIndex(
96140   Parse *pParse,                  /* Parse context to store any error in */
96141   Table *pParent,                 /* Parent table of FK constraint pFKey */
96142   FKey *pFKey,                    /* Foreign key to find index for */
96143   Index **ppIdx,                  /* OUT: Unique index on parent table */
96144   int **paiCol                    /* OUT: Map of index columns in pFKey */
96145 ){
96146   Index *pIdx = 0;                    /* Value to return via *ppIdx */
96147   int *aiCol = 0;                     /* Value to return via *paiCol */
96148   int nCol = pFKey->nCol;             /* Number of columns in parent key */
96149   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
96150 
96151   /* The caller is responsible for zeroing output parameters. */
96152   assert( ppIdx && *ppIdx==0 );
96153   assert( !paiCol || *paiCol==0 );
96154   assert( pParse );
96155 
96156   /* If this is a non-composite (single column) foreign key, check if it
96157   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
96158   ** and *paiCol set to zero and return early.
96159   **
96160   ** Otherwise, for a composite foreign key (more than one column), allocate
96161   ** space for the aiCol array (returned via output parameter *paiCol).
96162   ** Non-composite foreign keys do not require the aiCol array.
96163   */
96164   if( nCol==1 ){
96165     /* The FK maps to the IPK if any of the following are true:
96166     **
96167     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
96168     **      mapped to the primary key of table pParent, or
96169     **   2) The FK is explicitly mapped to a column declared as INTEGER
96170     **      PRIMARY KEY.
96171     */
96172     if( pParent->iPKey>=0 ){
96173       if( !zKey ) return 0;
96174       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
96175     }
96176   }else if( paiCol ){
96177     assert( nCol>1 );
96178     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
96179     if( !aiCol ) return 1;
96180     *paiCol = aiCol;
96181   }
96182 
96183   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
96184     if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){
96185       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
96186       ** of columns. If each indexed column corresponds to a foreign key
96187       ** column of pFKey, then this index is a winner.  */
96188 
96189       if( zKey==0 ){
96190         /* If zKey is NULL, then this foreign key is implicitly mapped to
96191         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
96192         ** identified by the test.  */
96193         if( IsPrimaryKeyIndex(pIdx) ){
96194           if( aiCol ){
96195             int i;
96196             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
96197           }
96198           break;
96199         }
96200       }else{
96201         /* If zKey is non-NULL, then this foreign key was declared to
96202         ** map to an explicit list of columns in table pParent. Check if this
96203         ** index matches those columns. Also, check that the index uses
96204         ** the default collation sequences for each column. */
96205         int i, j;
96206         for(i=0; i<nCol; i++){
96207           i16 iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
96208           char *zDfltColl;                  /* Def. collation for column */
96209           char *zIdxCol;                    /* Name of indexed column */
96210 
96211           /* If the index uses a collation sequence that is different from
96212           ** the default collation sequence for the column, this index is
96213           ** unusable. Bail out early in this case.  */
96214           zDfltColl = pParent->aCol[iCol].zColl;
96215           if( !zDfltColl ){
96216             zDfltColl = "BINARY";
96217           }
96218           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
96219 
96220           zIdxCol = pParent->aCol[iCol].zName;
96221           for(j=0; j<nCol; j++){
96222             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
96223               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
96224               break;
96225             }
96226           }
96227           if( j==nCol ) break;
96228         }
96229         if( i==nCol ) break;      /* pIdx is usable */
96230       }
96231     }
96232   }
96233 
96234   if( !pIdx ){
96235     if( !pParse->disableTriggers ){
96236       sqlite3ErrorMsg(pParse,
96237            "foreign key mismatch - \"%w\" referencing \"%w\"",
96238            pFKey->pFrom->zName, pFKey->zTo);
96239     }
96240     sqlite3DbFree(pParse->db, aiCol);
96241     return 1;
96242   }
96243 
96244   *ppIdx = pIdx;
96245   return 0;
96246 }
96247 
96248 /*
96249 ** This function is called when a row is inserted into or deleted from the
96250 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
96251 ** on the child table of pFKey, this function is invoked twice for each row
96252 ** affected - once to "delete" the old row, and then again to "insert" the
96253 ** new row.
96254 **
96255 ** Each time it is called, this function generates VDBE code to locate the
96256 ** row in the parent table that corresponds to the row being inserted into
96257 ** or deleted from the child table. If the parent row can be found, no
96258 ** special action is taken. Otherwise, if the parent row can *not* be
96259 ** found in the parent table:
96260 **
96261 **   Operation | FK type   | Action taken
96262 **   --------------------------------------------------------------------------
96263 **   INSERT      immediate   Increment the "immediate constraint counter".
96264 **
96265 **   DELETE      immediate   Decrement the "immediate constraint counter".
96266 **
96267 **   INSERT      deferred    Increment the "deferred constraint counter".
96268 **
96269 **   DELETE      deferred    Decrement the "deferred constraint counter".
96270 **
96271 ** These operations are identified in the comment at the top of this file
96272 ** (fkey.c) as "I.1" and "D.1".
96273 */
96274 static void fkLookupParent(
96275   Parse *pParse,        /* Parse context */
96276   int iDb,              /* Index of database housing pTab */
96277   Table *pTab,          /* Parent table of FK pFKey */
96278   Index *pIdx,          /* Unique index on parent key columns in pTab */
96279   FKey *pFKey,          /* Foreign key constraint */
96280   int *aiCol,           /* Map from parent key columns to child table columns */
96281   int regData,          /* Address of array containing child table row */
96282   int nIncr,            /* Increment constraint counter by this */
96283   int isIgnore          /* If true, pretend pTab contains all NULL values */
96284 ){
96285   int i;                                    /* Iterator variable */
96286   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
96287   int iCur = pParse->nTab - 1;              /* Cursor number to use */
96288   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
96289 
96290   /* If nIncr is less than zero, then check at runtime if there are any
96291   ** outstanding constraints to resolve. If there are not, there is no need
96292   ** to check if deleting this row resolves any outstanding violations.
96293   **
96294   ** Check if any of the key columns in the child table row are NULL. If
96295   ** any are, then the constraint is considered satisfied. No need to
96296   ** search for a matching row in the parent table.  */
96297   if( nIncr<0 ){
96298     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
96299     VdbeCoverage(v);
96300   }
96301   for(i=0; i<pFKey->nCol; i++){
96302     int iReg = aiCol[i] + regData + 1;
96303     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
96304   }
96305 
96306   if( isIgnore==0 ){
96307     if( pIdx==0 ){
96308       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
96309       ** column of the parent table (table pTab).  */
96310       int iMustBeInt;               /* Address of MustBeInt instruction */
96311       int regTemp = sqlite3GetTempReg(pParse);
96312 
96313       /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
96314       ** apply the affinity of the parent key). If this fails, then there
96315       ** is no matching parent key. Before using MustBeInt, make a copy of
96316       ** the value. Otherwise, the value inserted into the child key column
96317       ** will have INTEGER affinity applied to it, which may not be correct.  */
96318       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
96319       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
96320       VdbeCoverage(v);
96321 
96322       /* If the parent table is the same as the child table, and we are about
96323       ** to increment the constraint-counter (i.e. this is an INSERT operation),
96324       ** then check if the row being inserted matches itself. If so, do not
96325       ** increment the constraint-counter.  */
96326       if( pTab==pFKey->pFrom && nIncr==1 ){
96327         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
96328         sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
96329       }
96330 
96331       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
96332       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
96333       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
96334       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
96335       sqlite3VdbeJumpHere(v, iMustBeInt);
96336       sqlite3ReleaseTempReg(pParse, regTemp);
96337     }else{
96338       int nCol = pFKey->nCol;
96339       int regTemp = sqlite3GetTempRange(pParse, nCol);
96340       int regRec = sqlite3GetTempReg(pParse);
96341 
96342       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
96343       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
96344       for(i=0; i<nCol; i++){
96345         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
96346       }
96347 
96348       /* If the parent table is the same as the child table, and we are about
96349       ** to increment the constraint-counter (i.e. this is an INSERT operation),
96350       ** then check if the row being inserted matches itself. If so, do not
96351       ** increment the constraint-counter.
96352       **
96353       ** If any of the parent-key values are NULL, then the row cannot match
96354       ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
96355       ** of the parent-key values are NULL (at this point it is known that
96356       ** none of the child key values are).
96357       */
96358       if( pTab==pFKey->pFrom && nIncr==1 ){
96359         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
96360         for(i=0; i<nCol; i++){
96361           int iChild = aiCol[i]+1+regData;
96362           int iParent = pIdx->aiColumn[i]+1+regData;
96363           assert( aiCol[i]!=pTab->iPKey );
96364           if( pIdx->aiColumn[i]==pTab->iPKey ){
96365             /* The parent key is a composite key that includes the IPK column */
96366             iParent = regData;
96367           }
96368           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
96369           sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
96370         }
96371         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
96372       }
96373 
96374       sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
96375                         sqlite3IndexAffinityStr(v,pIdx), nCol);
96376       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
96377 
96378       sqlite3ReleaseTempReg(pParse, regRec);
96379       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
96380     }
96381   }
96382 
96383   if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
96384    && !pParse->pToplevel
96385    && !pParse->isMultiWrite
96386   ){
96387     /* Special case: If this is an INSERT statement that will insert exactly
96388     ** one row into the table, raise a constraint immediately instead of
96389     ** incrementing a counter. This is necessary as the VM code is being
96390     ** generated for will not open a statement transaction.  */
96391     assert( nIncr==1 );
96392     sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
96393         OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
96394   }else{
96395     if( nIncr>0 && pFKey->isDeferred==0 ){
96396       sqlite3ParseToplevel(pParse)->mayAbort = 1;
96397     }
96398     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
96399   }
96400 
96401   sqlite3VdbeResolveLabel(v, iOk);
96402   sqlite3VdbeAddOp1(v, OP_Close, iCur);
96403 }
96404 
96405 
96406 /*
96407 ** Return an Expr object that refers to a memory register corresponding
96408 ** to column iCol of table pTab.
96409 **
96410 ** regBase is the first of an array of register that contains the data
96411 ** for pTab.  regBase itself holds the rowid.  regBase+1 holds the first
96412 ** column.  regBase+2 holds the second column, and so forth.
96413 */
96414 static Expr *exprTableRegister(
96415   Parse *pParse,     /* Parsing and code generating context */
96416   Table *pTab,       /* The table whose content is at r[regBase]... */
96417   int regBase,       /* Contents of table pTab */
96418   i16 iCol           /* Which column of pTab is desired */
96419 ){
96420   Expr *pExpr;
96421   Column *pCol;
96422   const char *zColl;
96423   sqlite3 *db = pParse->db;
96424 
96425   pExpr = sqlite3Expr(db, TK_REGISTER, 0);
96426   if( pExpr ){
96427     if( iCol>=0 && iCol!=pTab->iPKey ){
96428       pCol = &pTab->aCol[iCol];
96429       pExpr->iTable = regBase + iCol + 1;
96430       pExpr->affinity = pCol->affinity;
96431       zColl = pCol->zColl;
96432       if( zColl==0 ) zColl = db->pDfltColl->zName;
96433       pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
96434     }else{
96435       pExpr->iTable = regBase;
96436       pExpr->affinity = SQLITE_AFF_INTEGER;
96437     }
96438   }
96439   return pExpr;
96440 }
96441 
96442 /*
96443 ** Return an Expr object that refers to column iCol of table pTab which
96444 ** has cursor iCur.
96445 */
96446 static Expr *exprTableColumn(
96447   sqlite3 *db,      /* The database connection */
96448   Table *pTab,      /* The table whose column is desired */
96449   int iCursor,      /* The open cursor on the table */
96450   i16 iCol          /* The column that is wanted */
96451 ){
96452   Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
96453   if( pExpr ){
96454     pExpr->pTab = pTab;
96455     pExpr->iTable = iCursor;
96456     pExpr->iColumn = iCol;
96457   }
96458   return pExpr;
96459 }
96460 
96461 /*
96462 ** This function is called to generate code executed when a row is deleted
96463 ** from the parent table of foreign key constraint pFKey and, if pFKey is
96464 ** deferred, when a row is inserted into the same table. When generating
96465 ** code for an SQL UPDATE operation, this function may be called twice -
96466 ** once to "delete" the old row and once to "insert" the new row.
96467 **
96468 ** The code generated by this function scans through the rows in the child
96469 ** table that correspond to the parent table row being deleted or inserted.
96470 ** For each child row found, one of the following actions is taken:
96471 **
96472 **   Operation | FK type   | Action taken
96473 **   --------------------------------------------------------------------------
96474 **   DELETE      immediate   Increment the "immediate constraint counter".
96475 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
96476 **                           throw a "FOREIGN KEY constraint failed" exception.
96477 **
96478 **   INSERT      immediate   Decrement the "immediate constraint counter".
96479 **
96480 **   DELETE      deferred    Increment the "deferred constraint counter".
96481 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
96482 **                           throw a "FOREIGN KEY constraint failed" exception.
96483 **
96484 **   INSERT      deferred    Decrement the "deferred constraint counter".
96485 **
96486 ** These operations are identified in the comment at the top of this file
96487 ** (fkey.c) as "I.2" and "D.2".
96488 */
96489 static void fkScanChildren(
96490   Parse *pParse,                  /* Parse context */
96491   SrcList *pSrc,                  /* The child table to be scanned */
96492   Table *pTab,                    /* The parent table */
96493   Index *pIdx,                    /* Index on parent covering the foreign key */
96494   FKey *pFKey,                    /* The foreign key linking pSrc to pTab */
96495   int *aiCol,                     /* Map from pIdx cols to child table cols */
96496   int regData,                    /* Parent row data starts here */
96497   int nIncr                       /* Amount to increment deferred counter by */
96498 ){
96499   sqlite3 *db = pParse->db;       /* Database handle */
96500   int i;                          /* Iterator variable */
96501   Expr *pWhere = 0;               /* WHERE clause to scan with */
96502   NameContext sNameContext;       /* Context used to resolve WHERE clause */
96503   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
96504   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
96505   Vdbe *v = sqlite3GetVdbe(pParse);
96506 
96507   assert( pIdx==0 || pIdx->pTable==pTab );
96508   assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
96509   assert( pIdx!=0 || pFKey->nCol==1 );
96510   assert( pIdx!=0 || HasRowid(pTab) );
96511 
96512   if( nIncr<0 ){
96513     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
96514     VdbeCoverage(v);
96515   }
96516 
96517   /* Create an Expr object representing an SQL expression like:
96518   **
96519   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
96520   **
96521   ** The collation sequence used for the comparison should be that of
96522   ** the parent key columns. The affinity of the parent key column should
96523   ** be applied to each child key value before the comparison takes place.
96524   */
96525   for(i=0; i<pFKey->nCol; i++){
96526     Expr *pLeft;                  /* Value from parent table row */
96527     Expr *pRight;                 /* Column ref to child table */
96528     Expr *pEq;                    /* Expression (pLeft = pRight) */
96529     i16 iCol;                     /* Index of column in child table */
96530     const char *zCol;             /* Name of column in child table */
96531 
96532     iCol = pIdx ? pIdx->aiColumn[i] : -1;
96533     pLeft = exprTableRegister(pParse, pTab, regData, iCol);
96534     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
96535     assert( iCol>=0 );
96536     zCol = pFKey->pFrom->aCol[iCol].zName;
96537     pRight = sqlite3Expr(db, TK_ID, zCol);
96538     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
96539     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
96540   }
96541 
96542   /* If the child table is the same as the parent table, then add terms
96543   ** to the WHERE clause that prevent this entry from being scanned.
96544   ** The added WHERE clause terms are like this:
96545   **
96546   **     $current_rowid!=rowid
96547   **     NOT( $current_a==a AND $current_b==b AND ... )
96548   **
96549   ** The first form is used for rowid tables.  The second form is used
96550   ** for WITHOUT ROWID tables.  In the second form, the primary key is
96551   ** (a,b,...)
96552   */
96553   if( pTab==pFKey->pFrom && nIncr>0 ){
96554     Expr *pNe;                    /* Expression (pLeft != pRight) */
96555     Expr *pLeft;                  /* Value from parent table row */
96556     Expr *pRight;                 /* Column ref to child table */
96557     if( HasRowid(pTab) ){
96558       pLeft = exprTableRegister(pParse, pTab, regData, -1);
96559       pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
96560       pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
96561     }else{
96562       Expr *pEq, *pAll = 0;
96563       Index *pPk = sqlite3PrimaryKeyIndex(pTab);
96564       assert( pIdx!=0 );
96565       for(i=0; i<pPk->nKeyCol; i++){
96566         i16 iCol = pIdx->aiColumn[i];
96567         pLeft = exprTableRegister(pParse, pTab, regData, iCol);
96568         pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
96569         pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
96570         pAll = sqlite3ExprAnd(db, pAll, pEq);
96571       }
96572       pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
96573     }
96574     pWhere = sqlite3ExprAnd(db, pWhere, pNe);
96575   }
96576 
96577   /* Resolve the references in the WHERE clause. */
96578   memset(&sNameContext, 0, sizeof(NameContext));
96579   sNameContext.pSrcList = pSrc;
96580   sNameContext.pParse = pParse;
96581   sqlite3ResolveExprNames(&sNameContext, pWhere);
96582 
96583   /* Create VDBE to loop through the entries in pSrc that match the WHERE
96584   ** clause. If the constraint is not deferred, throw an exception for
96585   ** each row found. Otherwise, for deferred constraints, increment the
96586   ** deferred constraint counter by nIncr for each row selected.  */
96587   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
96588   if( nIncr>0 && pFKey->isDeferred==0 ){
96589     sqlite3ParseToplevel(pParse)->mayAbort = 1;
96590   }
96591   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
96592   if( pWInfo ){
96593     sqlite3WhereEnd(pWInfo);
96594   }
96595 
96596   /* Clean up the WHERE clause constructed above. */
96597   sqlite3ExprDelete(db, pWhere);
96598   if( iFkIfZero ){
96599     sqlite3VdbeJumpHere(v, iFkIfZero);
96600   }
96601 }
96602 
96603 /*
96604 ** This function returns a linked list of FKey objects (connected by
96605 ** FKey.pNextTo) holding all children of table pTab.  For example,
96606 ** given the following schema:
96607 **
96608 **   CREATE TABLE t1(a PRIMARY KEY);
96609 **   CREATE TABLE t2(b REFERENCES t1(a);
96610 **
96611 ** Calling this function with table "t1" as an argument returns a pointer
96612 ** to the FKey structure representing the foreign key constraint on table
96613 ** "t2". Calling this function with "t2" as the argument would return a
96614 ** NULL pointer (as there are no FK constraints for which t2 is the parent
96615 ** table).
96616 */
96617 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
96618   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
96619 }
96620 
96621 /*
96622 ** The second argument is a Trigger structure allocated by the
96623 ** fkActionTrigger() routine. This function deletes the Trigger structure
96624 ** and all of its sub-components.
96625 **
96626 ** The Trigger structure or any of its sub-components may be allocated from
96627 ** the lookaside buffer belonging to database handle dbMem.
96628 */
96629 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
96630   if( p ){
96631     TriggerStep *pStep = p->step_list;
96632     sqlite3ExprDelete(dbMem, pStep->pWhere);
96633     sqlite3ExprListDelete(dbMem, pStep->pExprList);
96634     sqlite3SelectDelete(dbMem, pStep->pSelect);
96635     sqlite3ExprDelete(dbMem, p->pWhen);
96636     sqlite3DbFree(dbMem, p);
96637   }
96638 }
96639 
96640 /*
96641 ** This function is called to generate code that runs when table pTab is
96642 ** being dropped from the database. The SrcList passed as the second argument
96643 ** to this function contains a single entry guaranteed to resolve to
96644 ** table pTab.
96645 **
96646 ** Normally, no code is required. However, if either
96647 **
96648 **   (a) The table is the parent table of a FK constraint, or
96649 **   (b) The table is the child table of a deferred FK constraint and it is
96650 **       determined at runtime that there are outstanding deferred FK
96651 **       constraint violations in the database,
96652 **
96653 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
96654 ** the table from the database. Triggers are disabled while running this
96655 ** DELETE, but foreign key actions are not.
96656 */
96657 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
96658   sqlite3 *db = pParse->db;
96659   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
96660     int iSkip = 0;
96661     Vdbe *v = sqlite3GetVdbe(pParse);
96662 
96663     assert( v );                  /* VDBE has already been allocated */
96664     if( sqlite3FkReferences(pTab)==0 ){
96665       /* Search for a deferred foreign key constraint for which this table
96666       ** is the child table. If one cannot be found, return without
96667       ** generating any VDBE code. If one can be found, then jump over
96668       ** the entire DELETE if there are no outstanding deferred constraints
96669       ** when this statement is run.  */
96670       FKey *p;
96671       for(p=pTab->pFKey; p; p=p->pNextFrom){
96672         if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
96673       }
96674       if( !p ) return;
96675       iSkip = sqlite3VdbeMakeLabel(v);
96676       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
96677     }
96678 
96679     pParse->disableTriggers = 1;
96680     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
96681     pParse->disableTriggers = 0;
96682 
96683     /* If the DELETE has generated immediate foreign key constraint
96684     ** violations, halt the VDBE and return an error at this point, before
96685     ** any modifications to the schema are made. This is because statement
96686     ** transactions are not able to rollback schema changes.
96687     **
96688     ** If the SQLITE_DeferFKs flag is set, then this is not required, as
96689     ** the statement transaction will not be rolled back even if FK
96690     ** constraints are violated.
96691     */
96692     if( (db->flags & SQLITE_DeferFKs)==0 ){
96693       sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
96694       VdbeCoverage(v);
96695       sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
96696           OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
96697     }
96698 
96699     if( iSkip ){
96700       sqlite3VdbeResolveLabel(v, iSkip);
96701     }
96702   }
96703 }
96704 
96705 
96706 /*
96707 ** The second argument points to an FKey object representing a foreign key
96708 ** for which pTab is the child table. An UPDATE statement against pTab
96709 ** is currently being processed. For each column of the table that is
96710 ** actually updated, the corresponding element in the aChange[] array
96711 ** is zero or greater (if a column is unmodified the corresponding element
96712 ** is set to -1). If the rowid column is modified by the UPDATE statement
96713 ** the bChngRowid argument is non-zero.
96714 **
96715 ** This function returns true if any of the columns that are part of the
96716 ** child key for FK constraint *p are modified.
96717 */
96718 static int fkChildIsModified(
96719   Table *pTab,                    /* Table being updated */
96720   FKey *p,                        /* Foreign key for which pTab is the child */
96721   int *aChange,                   /* Array indicating modified columns */
96722   int bChngRowid                  /* True if rowid is modified by this update */
96723 ){
96724   int i;
96725   for(i=0; i<p->nCol; i++){
96726     int iChildKey = p->aCol[i].iFrom;
96727     if( aChange[iChildKey]>=0 ) return 1;
96728     if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
96729   }
96730   return 0;
96731 }
96732 
96733 /*
96734 ** The second argument points to an FKey object representing a foreign key
96735 ** for which pTab is the parent table. An UPDATE statement against pTab
96736 ** is currently being processed. For each column of the table that is
96737 ** actually updated, the corresponding element in the aChange[] array
96738 ** is zero or greater (if a column is unmodified the corresponding element
96739 ** is set to -1). If the rowid column is modified by the UPDATE statement
96740 ** the bChngRowid argument is non-zero.
96741 **
96742 ** This function returns true if any of the columns that are part of the
96743 ** parent key for FK constraint *p are modified.
96744 */
96745 static int fkParentIsModified(
96746   Table *pTab,
96747   FKey *p,
96748   int *aChange,
96749   int bChngRowid
96750 ){
96751   int i;
96752   for(i=0; i<p->nCol; i++){
96753     char *zKey = p->aCol[i].zCol;
96754     int iKey;
96755     for(iKey=0; iKey<pTab->nCol; iKey++){
96756       if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
96757         Column *pCol = &pTab->aCol[iKey];
96758         if( zKey ){
96759           if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
96760         }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
96761           return 1;
96762         }
96763       }
96764     }
96765   }
96766   return 0;
96767 }
96768 
96769 /*
96770 ** This function is called when inserting, deleting or updating a row of
96771 ** table pTab to generate VDBE code to perform foreign key constraint
96772 ** processing for the operation.
96773 **
96774 ** For a DELETE operation, parameter regOld is passed the index of the
96775 ** first register in an array of (pTab->nCol+1) registers containing the
96776 ** rowid of the row being deleted, followed by each of the column values
96777 ** of the row being deleted, from left to right. Parameter regNew is passed
96778 ** zero in this case.
96779 **
96780 ** For an INSERT operation, regOld is passed zero and regNew is passed the
96781 ** first register of an array of (pTab->nCol+1) registers containing the new
96782 ** row data.
96783 **
96784 ** For an UPDATE operation, this function is called twice. Once before
96785 ** the original record is deleted from the table using the calling convention
96786 ** described for DELETE. Then again after the original record is deleted
96787 ** but before the new record is inserted using the INSERT convention.
96788 */
96789 SQLITE_PRIVATE void sqlite3FkCheck(
96790   Parse *pParse,                  /* Parse context */
96791   Table *pTab,                    /* Row is being deleted from this table */
96792   int regOld,                     /* Previous row data is stored here */
96793   int regNew,                     /* New row data is stored here */
96794   int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
96795   int bChngRowid                  /* True if rowid is UPDATEd */
96796 ){
96797   sqlite3 *db = pParse->db;       /* Database handle */
96798   FKey *pFKey;                    /* Used to iterate through FKs */
96799   int iDb;                        /* Index of database containing pTab */
96800   const char *zDb;                /* Name of database containing pTab */
96801   int isIgnoreErrors = pParse->disableTriggers;
96802 
96803   /* Exactly one of regOld and regNew should be non-zero. */
96804   assert( (regOld==0)!=(regNew==0) );
96805 
96806   /* If foreign-keys are disabled, this function is a no-op. */
96807   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
96808 
96809   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
96810   zDb = db->aDb[iDb].zName;
96811 
96812   /* Loop through all the foreign key constraints for which pTab is the
96813   ** child table (the table that the foreign key definition is part of).  */
96814   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
96815     Table *pTo;                   /* Parent table of foreign key pFKey */
96816     Index *pIdx = 0;              /* Index on key columns in pTo */
96817     int *aiFree = 0;
96818     int *aiCol;
96819     int iCol;
96820     int i;
96821     int isIgnore = 0;
96822 
96823     if( aChange
96824      && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
96825      && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
96826     ){
96827       continue;
96828     }
96829 
96830     /* Find the parent table of this foreign key. Also find a unique index
96831     ** on the parent key columns in the parent table. If either of these
96832     ** schema items cannot be located, set an error in pParse and return
96833     ** early.  */
96834     if( pParse->disableTriggers ){
96835       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
96836     }else{
96837       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
96838     }
96839     if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
96840       assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
96841       if( !isIgnoreErrors || db->mallocFailed ) return;
96842       if( pTo==0 ){
96843         /* If isIgnoreErrors is true, then a table is being dropped. In this
96844         ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
96845         ** before actually dropping it in order to check FK constraints.
96846         ** If the parent table of an FK constraint on the current table is
96847         ** missing, behave as if it is empty. i.e. decrement the relevant
96848         ** FK counter for each row of the current table with non-NULL keys.
96849         */
96850         Vdbe *v = sqlite3GetVdbe(pParse);
96851         int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
96852         for(i=0; i<pFKey->nCol; i++){
96853           int iReg = pFKey->aCol[i].iFrom + regOld + 1;
96854           sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
96855         }
96856         sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
96857       }
96858       continue;
96859     }
96860     assert( pFKey->nCol==1 || (aiFree && pIdx) );
96861 
96862     if( aiFree ){
96863       aiCol = aiFree;
96864     }else{
96865       iCol = pFKey->aCol[0].iFrom;
96866       aiCol = &iCol;
96867     }
96868     for(i=0; i<pFKey->nCol; i++){
96869       if( aiCol[i]==pTab->iPKey ){
96870         aiCol[i] = -1;
96871       }
96872 #ifndef SQLITE_OMIT_AUTHORIZATION
96873       /* Request permission to read the parent key columns. If the
96874       ** authorization callback returns SQLITE_IGNORE, behave as if any
96875       ** values read from the parent table are NULL. */
96876       if( db->xAuth ){
96877         int rcauth;
96878         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
96879         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
96880         isIgnore = (rcauth==SQLITE_IGNORE);
96881       }
96882 #endif
96883     }
96884 
96885     /* Take a shared-cache advisory read-lock on the parent table. Allocate
96886     ** a cursor to use to search the unique index on the parent key columns
96887     ** in the parent table.  */
96888     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
96889     pParse->nTab++;
96890 
96891     if( regOld!=0 ){
96892       /* A row is being removed from the child table. Search for the parent.
96893       ** If the parent does not exist, removing the child row resolves an
96894       ** outstanding foreign key constraint violation. */
96895       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
96896     }
96897     if( regNew!=0 ){
96898       /* A row is being added to the child table. If a parent row cannot
96899       ** be found, adding the child row has violated the FK constraint. */
96900       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
96901     }
96902 
96903     sqlite3DbFree(db, aiFree);
96904   }
96905 
96906   /* Loop through all the foreign key constraints that refer to this table.
96907   ** (the "child" constraints) */
96908   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
96909     Index *pIdx = 0;              /* Foreign key index for pFKey */
96910     SrcList *pSrc;
96911     int *aiCol = 0;
96912 
96913     if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
96914       continue;
96915     }
96916 
96917     if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
96918      && !pParse->pToplevel && !pParse->isMultiWrite
96919     ){
96920       assert( regOld==0 && regNew!=0 );
96921       /* Inserting a single row into a parent table cannot cause an immediate
96922       ** foreign key violation. So do nothing in this case.  */
96923       continue;
96924     }
96925 
96926     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
96927       if( !isIgnoreErrors || db->mallocFailed ) return;
96928       continue;
96929     }
96930     assert( aiCol || pFKey->nCol==1 );
96931 
96932     /* Create a SrcList structure containing the child table.  We need the
96933     ** child table as a SrcList for sqlite3WhereBegin() */
96934     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
96935     if( pSrc ){
96936       struct SrcList_item *pItem = pSrc->a;
96937       pItem->pTab = pFKey->pFrom;
96938       pItem->zName = pFKey->pFrom->zName;
96939       pItem->pTab->nRef++;
96940       pItem->iCursor = pParse->nTab++;
96941 
96942       if( regNew!=0 ){
96943         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
96944       }
96945       if( regOld!=0 ){
96946         /* If there is a RESTRICT action configured for the current operation
96947         ** on the parent table of this FK, then throw an exception
96948         ** immediately if the FK constraint is violated, even if this is a
96949         ** deferred trigger. That's what RESTRICT means. To defer checking
96950         ** the constraint, the FK should specify NO ACTION (represented
96951         ** using OE_None). NO ACTION is the default.  */
96952         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
96953       }
96954       pItem->zName = 0;
96955       sqlite3SrcListDelete(db, pSrc);
96956     }
96957     sqlite3DbFree(db, aiCol);
96958   }
96959 }
96960 
96961 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
96962 
96963 /*
96964 ** This function is called before generating code to update or delete a
96965 ** row contained in table pTab.
96966 */
96967 SQLITE_PRIVATE u32 sqlite3FkOldmask(
96968   Parse *pParse,                  /* Parse context */
96969   Table *pTab                     /* Table being modified */
96970 ){
96971   u32 mask = 0;
96972   if( pParse->db->flags&SQLITE_ForeignKeys ){
96973     FKey *p;
96974     int i;
96975     for(p=pTab->pFKey; p; p=p->pNextFrom){
96976       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
96977     }
96978     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
96979       Index *pIdx = 0;
96980       sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
96981       if( pIdx ){
96982         for(i=0; i<pIdx->nKeyCol; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
96983       }
96984     }
96985   }
96986   return mask;
96987 }
96988 
96989 
96990 /*
96991 ** This function is called before generating code to update or delete a
96992 ** row contained in table pTab. If the operation is a DELETE, then
96993 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
96994 ** to an array of size N, where N is the number of columns in table pTab.
96995 ** If the i'th column is not modified by the UPDATE, then the corresponding
96996 ** entry in the aChange[] array is set to -1. If the column is modified,
96997 ** the value is 0 or greater. Parameter chngRowid is set to true if the
96998 ** UPDATE statement modifies the rowid fields of the table.
96999 **
97000 ** If any foreign key processing will be required, this function returns
97001 ** true. If there is no foreign key related processing, this function
97002 ** returns false.
97003 */
97004 SQLITE_PRIVATE int sqlite3FkRequired(
97005   Parse *pParse,                  /* Parse context */
97006   Table *pTab,                    /* Table being modified */
97007   int *aChange,                   /* Non-NULL for UPDATE operations */
97008   int chngRowid                   /* True for UPDATE that affects rowid */
97009 ){
97010   if( pParse->db->flags&SQLITE_ForeignKeys ){
97011     if( !aChange ){
97012       /* A DELETE operation. Foreign key processing is required if the
97013       ** table in question is either the child or parent table for any
97014       ** foreign key constraint.  */
97015       return (sqlite3FkReferences(pTab) || pTab->pFKey);
97016     }else{
97017       /* This is an UPDATE. Foreign key processing is only required if the
97018       ** operation modifies one or more child or parent key columns. */
97019       FKey *p;
97020 
97021       /* Check if any child key columns are being modified. */
97022       for(p=pTab->pFKey; p; p=p->pNextFrom){
97023         if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
97024       }
97025 
97026       /* Check if any parent key columns are being modified. */
97027       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
97028         if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
97029       }
97030     }
97031   }
97032   return 0;
97033 }
97034 
97035 /*
97036 ** This function is called when an UPDATE or DELETE operation is being
97037 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
97038 ** If the current operation is an UPDATE, then the pChanges parameter is
97039 ** passed a pointer to the list of columns being modified. If it is a
97040 ** DELETE, pChanges is passed a NULL pointer.
97041 **
97042 ** It returns a pointer to a Trigger structure containing a trigger
97043 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
97044 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
97045 ** returned (these actions require no special handling by the triggers
97046 ** sub-system, code for them is created by fkScanChildren()).
97047 **
97048 ** For example, if pFKey is the foreign key and pTab is table "p" in
97049 ** the following schema:
97050 **
97051 **   CREATE TABLE p(pk PRIMARY KEY);
97052 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
97053 **
97054 ** then the returned trigger structure is equivalent to:
97055 **
97056 **   CREATE TRIGGER ... DELETE ON p BEGIN
97057 **     DELETE FROM c WHERE ck = old.pk;
97058 **   END;
97059 **
97060 ** The returned pointer is cached as part of the foreign key object. It
97061 ** is eventually freed along with the rest of the foreign key object by
97062 ** sqlite3FkDelete().
97063 */
97064 static Trigger *fkActionTrigger(
97065   Parse *pParse,                  /* Parse context */
97066   Table *pTab,                    /* Table being updated or deleted from */
97067   FKey *pFKey,                    /* Foreign key to get action for */
97068   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
97069 ){
97070   sqlite3 *db = pParse->db;       /* Database handle */
97071   int action;                     /* One of OE_None, OE_Cascade etc. */
97072   Trigger *pTrigger;              /* Trigger definition to return */
97073   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
97074 
97075   action = pFKey->aAction[iAction];
97076   pTrigger = pFKey->apTrigger[iAction];
97077 
97078   if( action!=OE_None && !pTrigger ){
97079     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
97080     char const *zFrom;            /* Name of child table */
97081     int nFrom;                    /* Length in bytes of zFrom */
97082     Index *pIdx = 0;              /* Parent key index for this FK */
97083     int *aiCol = 0;               /* child table cols -> parent key cols */
97084     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
97085     Expr *pWhere = 0;             /* WHERE clause of trigger step */
97086     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
97087     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
97088     int i;                        /* Iterator variable */
97089     Expr *pWhen = 0;              /* WHEN clause for the trigger */
97090 
97091     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
97092     assert( aiCol || pFKey->nCol==1 );
97093 
97094     for(i=0; i<pFKey->nCol; i++){
97095       Token tOld = { "old", 3 };  /* Literal "old" token */
97096       Token tNew = { "new", 3 };  /* Literal "new" token */
97097       Token tFromCol;             /* Name of column in child table */
97098       Token tToCol;               /* Name of column in parent table */
97099       int iFromCol;               /* Idx of column in child table */
97100       Expr *pEq;                  /* tFromCol = OLD.tToCol */
97101 
97102       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
97103       assert( iFromCol>=0 );
97104       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
97105       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
97106 
97107       tToCol.n = sqlite3Strlen30(tToCol.z);
97108       tFromCol.n = sqlite3Strlen30(tFromCol.z);
97109 
97110       /* Create the expression "OLD.zToCol = zFromCol". It is important
97111       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
97112       ** that the affinity and collation sequence associated with the
97113       ** parent table are used for the comparison. */
97114       pEq = sqlite3PExpr(pParse, TK_EQ,
97115           sqlite3PExpr(pParse, TK_DOT,
97116             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
97117             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
97118           , 0),
97119           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
97120       , 0);
97121       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
97122 
97123       /* For ON UPDATE, construct the next term of the WHEN clause.
97124       ** The final WHEN clause will be like this:
97125       **
97126       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
97127       */
97128       if( pChanges ){
97129         pEq = sqlite3PExpr(pParse, TK_IS,
97130             sqlite3PExpr(pParse, TK_DOT,
97131               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
97132               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
97133               0),
97134             sqlite3PExpr(pParse, TK_DOT,
97135               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
97136               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
97137               0),
97138             0);
97139         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
97140       }
97141 
97142       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
97143         Expr *pNew;
97144         if( action==OE_Cascade ){
97145           pNew = sqlite3PExpr(pParse, TK_DOT,
97146             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
97147             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
97148           , 0);
97149         }else if( action==OE_SetDflt ){
97150           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
97151           if( pDflt ){
97152             pNew = sqlite3ExprDup(db, pDflt, 0);
97153           }else{
97154             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
97155           }
97156         }else{
97157           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
97158         }
97159         pList = sqlite3ExprListAppend(pParse, pList, pNew);
97160         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
97161       }
97162     }
97163     sqlite3DbFree(db, aiCol);
97164 
97165     zFrom = pFKey->pFrom->zName;
97166     nFrom = sqlite3Strlen30(zFrom);
97167 
97168     if( action==OE_Restrict ){
97169       Token tFrom;
97170       Expr *pRaise;
97171 
97172       tFrom.z = zFrom;
97173       tFrom.n = nFrom;
97174       pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
97175       if( pRaise ){
97176         pRaise->affinity = OE_Abort;
97177       }
97178       pSelect = sqlite3SelectNew(pParse,
97179           sqlite3ExprListAppend(pParse, 0, pRaise),
97180           sqlite3SrcListAppend(db, 0, &tFrom, 0),
97181           pWhere,
97182           0, 0, 0, 0, 0, 0
97183       );
97184       pWhere = 0;
97185     }
97186 
97187     /* Disable lookaside memory allocation */
97188     enableLookaside = db->lookaside.bEnabled;
97189     db->lookaside.bEnabled = 0;
97190 
97191     pTrigger = (Trigger *)sqlite3DbMallocZero(db,
97192         sizeof(Trigger) +         /* struct Trigger */
97193         sizeof(TriggerStep) +     /* Single step in trigger program */
97194         nFrom + 1                 /* Space for pStep->target.z */
97195     );
97196     if( pTrigger ){
97197       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
97198       pStep->target.z = (char *)&pStep[1];
97199       pStep->target.n = nFrom;
97200       memcpy((char *)pStep->target.z, zFrom, nFrom);
97201 
97202       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
97203       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
97204       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
97205       if( pWhen ){
97206         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
97207         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
97208       }
97209     }
97210 
97211     /* Re-enable the lookaside buffer, if it was disabled earlier. */
97212     db->lookaside.bEnabled = enableLookaside;
97213 
97214     sqlite3ExprDelete(db, pWhere);
97215     sqlite3ExprDelete(db, pWhen);
97216     sqlite3ExprListDelete(db, pList);
97217     sqlite3SelectDelete(db, pSelect);
97218     if( db->mallocFailed==1 ){
97219       fkTriggerDelete(db, pTrigger);
97220       return 0;
97221     }
97222     assert( pStep!=0 );
97223 
97224     switch( action ){
97225       case OE_Restrict:
97226         pStep->op = TK_SELECT;
97227         break;
97228       case OE_Cascade:
97229         if( !pChanges ){
97230           pStep->op = TK_DELETE;
97231           break;
97232         }
97233       default:
97234         pStep->op = TK_UPDATE;
97235     }
97236     pStep->pTrig = pTrigger;
97237     pTrigger->pSchema = pTab->pSchema;
97238     pTrigger->pTabSchema = pTab->pSchema;
97239     pFKey->apTrigger[iAction] = pTrigger;
97240     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
97241   }
97242 
97243   return pTrigger;
97244 }
97245 
97246 /*
97247 ** This function is called when deleting or updating a row to implement
97248 ** any required CASCADE, SET NULL or SET DEFAULT actions.
97249 */
97250 SQLITE_PRIVATE void sqlite3FkActions(
97251   Parse *pParse,                  /* Parse context */
97252   Table *pTab,                    /* Table being updated or deleted from */
97253   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
97254   int regOld,                     /* Address of array containing old row */
97255   int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
97256   int bChngRowid                  /* True if rowid is UPDATEd */
97257 ){
97258   /* If foreign-key support is enabled, iterate through all FKs that
97259   ** refer to table pTab. If there is an action associated with the FK
97260   ** for this operation (either update or delete), invoke the associated
97261   ** trigger sub-program.  */
97262   if( pParse->db->flags&SQLITE_ForeignKeys ){
97263     FKey *pFKey;                  /* Iterator variable */
97264     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
97265       if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
97266         Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
97267         if( pAct ){
97268           sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
97269         }
97270       }
97271     }
97272   }
97273 }
97274 
97275 #endif /* ifndef SQLITE_OMIT_TRIGGER */
97276 
97277 /*
97278 ** Free all memory associated with foreign key definitions attached to
97279 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
97280 ** hash table.
97281 */
97282 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
97283   FKey *pFKey;                    /* Iterator variable */
97284   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
97285 
97286   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
97287   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
97288 
97289     /* Remove the FK from the fkeyHash hash table. */
97290     if( !db || db->pnBytesFreed==0 ){
97291       if( pFKey->pPrevTo ){
97292         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
97293       }else{
97294         void *p = (void *)pFKey->pNextTo;
97295         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
97296         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
97297       }
97298       if( pFKey->pNextTo ){
97299         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
97300       }
97301     }
97302 
97303     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
97304     ** classified as either immediate or deferred.
97305     */
97306     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
97307 
97308     /* Delete any triggers created to implement actions for this FK. */
97309 #ifndef SQLITE_OMIT_TRIGGER
97310     fkTriggerDelete(db, pFKey->apTrigger[0]);
97311     fkTriggerDelete(db, pFKey->apTrigger[1]);
97312 #endif
97313 
97314     pNext = pFKey->pNextFrom;
97315     sqlite3DbFree(db, pFKey);
97316   }
97317 }
97318 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
97319 
97320 /************** End of fkey.c ************************************************/
97321 /************** Begin file insert.c ******************************************/
97322 /*
97323 ** 2001 September 15
97324 **
97325 ** The author disclaims copyright to this source code.  In place of
97326 ** a legal notice, here is a blessing:
97327 **
97328 **    May you do good and not evil.
97329 **    May you find forgiveness for yourself and forgive others.
97330 **    May you share freely, never taking more than you give.
97331 **
97332 *************************************************************************
97333 ** This file contains C code routines that are called by the parser
97334 ** to handle INSERT statements in SQLite.
97335 */
97336 
97337 /*
97338 ** Generate code that will
97339 **
97340 **   (1) acquire a lock for table pTab then
97341 **   (2) open pTab as cursor iCur.
97342 **
97343 ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
97344 ** for that table that is actually opened.
97345 */
97346 SQLITE_PRIVATE void sqlite3OpenTable(
97347   Parse *pParse,  /* Generate code into this VDBE */
97348   int iCur,       /* The cursor number of the table */
97349   int iDb,        /* The database index in sqlite3.aDb[] */
97350   Table *pTab,    /* The table to be opened */
97351   int opcode      /* OP_OpenRead or OP_OpenWrite */
97352 ){
97353   Vdbe *v;
97354   assert( !IsVirtual(pTab) );
97355   v = sqlite3GetVdbe(pParse);
97356   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
97357   sqlite3TableLock(pParse, iDb, pTab->tnum,
97358                    (opcode==OP_OpenWrite)?1:0, pTab->zName);
97359   if( HasRowid(pTab) ){
97360     sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
97361     VdbeComment((v, "%s", pTab->zName));
97362   }else{
97363     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
97364     assert( pPk!=0 );
97365     assert( pPk->tnum=pTab->tnum );
97366     sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
97367     sqlite3VdbeSetP4KeyInfo(pParse, pPk);
97368     VdbeComment((v, "%s", pTab->zName));
97369   }
97370 }
97371 
97372 /*
97373 ** Return a pointer to the column affinity string associated with index
97374 ** pIdx. A column affinity string has one character for each column in
97375 ** the table, according to the affinity of the column:
97376 **
97377 **  Character      Column affinity
97378 **  ------------------------------
97379 **  'A'            NONE
97380 **  'B'            TEXT
97381 **  'C'            NUMERIC
97382 **  'D'            INTEGER
97383 **  'F'            REAL
97384 **
97385 ** An extra 'D' is appended to the end of the string to cover the
97386 ** rowid that appears as the last column in every index.
97387 **
97388 ** Memory for the buffer containing the column index affinity string
97389 ** is managed along with the rest of the Index structure. It will be
97390 ** released when sqlite3DeleteIndex() is called.
97391 */
97392 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
97393   if( !pIdx->zColAff ){
97394     /* The first time a column affinity string for a particular index is
97395     ** required, it is allocated and populated here. It is then stored as
97396     ** a member of the Index structure for subsequent use.
97397     **
97398     ** The column affinity string will eventually be deleted by
97399     ** sqliteDeleteIndex() when the Index structure itself is cleaned
97400     ** up.
97401     */
97402     int n;
97403     Table *pTab = pIdx->pTable;
97404     sqlite3 *db = sqlite3VdbeDb(v);
97405     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
97406     if( !pIdx->zColAff ){
97407       db->mallocFailed = 1;
97408       return 0;
97409     }
97410     for(n=0; n<pIdx->nColumn; n++){
97411       i16 x = pIdx->aiColumn[n];
97412       pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity;
97413     }
97414     pIdx->zColAff[n] = 0;
97415   }
97416 
97417   return pIdx->zColAff;
97418 }
97419 
97420 /*
97421 ** Compute the affinity string for table pTab, if it has not already been
97422 ** computed.  As an optimization, omit trailing SQLITE_AFF_NONE affinities.
97423 **
97424 ** If the affinity exists (if it is no entirely SQLITE_AFF_NONE values) and
97425 ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
97426 ** for register iReg and following.  Or if affinities exists and iReg==0,
97427 ** then just set the P4 operand of the previous opcode (which should  be
97428 ** an OP_MakeRecord) to the affinity string.
97429 **
97430 ** A column affinity string has one character per column:
97431 **
97432 **  Character      Column affinity
97433 **  ------------------------------
97434 **  'A'            NONE
97435 **  'B'            TEXT
97436 **  'C'            NUMERIC
97437 **  'D'            INTEGER
97438 **  'E'            REAL
97439 */
97440 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
97441   int i;
97442   char *zColAff = pTab->zColAff;
97443   if( zColAff==0 ){
97444     sqlite3 *db = sqlite3VdbeDb(v);
97445     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
97446     if( !zColAff ){
97447       db->mallocFailed = 1;
97448       return;
97449     }
97450 
97451     for(i=0; i<pTab->nCol; i++){
97452       zColAff[i] = pTab->aCol[i].affinity;
97453     }
97454     do{
97455       zColAff[i--] = 0;
97456     }while( i>=0 && zColAff[i]==SQLITE_AFF_NONE );
97457     pTab->zColAff = zColAff;
97458   }
97459   i = sqlite3Strlen30(zColAff);
97460   if( i ){
97461     if( iReg ){
97462       sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
97463     }else{
97464       sqlite3VdbeChangeP4(v, -1, zColAff, i);
97465     }
97466   }
97467 }
97468 
97469 /*
97470 ** Return non-zero if the table pTab in database iDb or any of its indices
97471 ** have been opened at any point in the VDBE program. This is used to see if
97472 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
97473 ** run without using a temporary table for the results of the SELECT.
97474 */
97475 static int readsTable(Parse *p, int iDb, Table *pTab){
97476   Vdbe *v = sqlite3GetVdbe(p);
97477   int i;
97478   int iEnd = sqlite3VdbeCurrentAddr(v);
97479 #ifndef SQLITE_OMIT_VIRTUALTABLE
97480   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
97481 #endif
97482 
97483   for(i=1; i<iEnd; i++){
97484     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
97485     assert( pOp!=0 );
97486     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
97487       Index *pIndex;
97488       int tnum = pOp->p2;
97489       if( tnum==pTab->tnum ){
97490         return 1;
97491       }
97492       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
97493         if( tnum==pIndex->tnum ){
97494           return 1;
97495         }
97496       }
97497     }
97498 #ifndef SQLITE_OMIT_VIRTUALTABLE
97499     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
97500       assert( pOp->p4.pVtab!=0 );
97501       assert( pOp->p4type==P4_VTAB );
97502       return 1;
97503     }
97504 #endif
97505   }
97506   return 0;
97507 }
97508 
97509 #ifndef SQLITE_OMIT_AUTOINCREMENT
97510 /*
97511 ** Locate or create an AutoincInfo structure associated with table pTab
97512 ** which is in database iDb.  Return the register number for the register
97513 ** that holds the maximum rowid.
97514 **
97515 ** There is at most one AutoincInfo structure per table even if the
97516 ** same table is autoincremented multiple times due to inserts within
97517 ** triggers.  A new AutoincInfo structure is created if this is the
97518 ** first use of table pTab.  On 2nd and subsequent uses, the original
97519 ** AutoincInfo structure is used.
97520 **
97521 ** Three memory locations are allocated:
97522 **
97523 **   (1)  Register to hold the name of the pTab table.
97524 **   (2)  Register to hold the maximum ROWID of pTab.
97525 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
97526 **
97527 ** The 2nd register is the one that is returned.  That is all the
97528 ** insert routine needs to know about.
97529 */
97530 static int autoIncBegin(
97531   Parse *pParse,      /* Parsing context */
97532   int iDb,            /* Index of the database holding pTab */
97533   Table *pTab         /* The table we are writing to */
97534 ){
97535   int memId = 0;      /* Register holding maximum rowid */
97536   if( pTab->tabFlags & TF_Autoincrement ){
97537     Parse *pToplevel = sqlite3ParseToplevel(pParse);
97538     AutoincInfo *pInfo;
97539 
97540     pInfo = pToplevel->pAinc;
97541     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
97542     if( pInfo==0 ){
97543       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
97544       if( pInfo==0 ) return 0;
97545       pInfo->pNext = pToplevel->pAinc;
97546       pToplevel->pAinc = pInfo;
97547       pInfo->pTab = pTab;
97548       pInfo->iDb = iDb;
97549       pToplevel->nMem++;                  /* Register to hold name of table */
97550       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
97551       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
97552     }
97553     memId = pInfo->regCtr;
97554   }
97555   return memId;
97556 }
97557 
97558 /*
97559 ** This routine generates code that will initialize all of the
97560 ** register used by the autoincrement tracker.
97561 */
97562 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
97563   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
97564   sqlite3 *db = pParse->db;  /* The database connection */
97565   Db *pDb;                   /* Database only autoinc table */
97566   int memId;                 /* Register holding max rowid */
97567   int addr;                  /* A VDBE address */
97568   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
97569 
97570   /* This routine is never called during trigger-generation.  It is
97571   ** only called from the top-level */
97572   assert( pParse->pTriggerTab==0 );
97573   assert( pParse==sqlite3ParseToplevel(pParse) );
97574 
97575   assert( v );   /* We failed long ago if this is not so */
97576   for(p = pParse->pAinc; p; p = p->pNext){
97577     pDb = &db->aDb[p->iDb];
97578     memId = p->regCtr;
97579     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
97580     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
97581     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
97582     addr = sqlite3VdbeCurrentAddr(v);
97583     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
97584     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); VdbeCoverage(v);
97585     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
97586     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); VdbeCoverage(v);
97587     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
97588     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
97589     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
97590     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
97591     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); VdbeCoverage(v);
97592     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
97593     sqlite3VdbeAddOp0(v, OP_Close);
97594   }
97595 }
97596 
97597 /*
97598 ** Update the maximum rowid for an autoincrement calculation.
97599 **
97600 ** This routine should be called when the top of the stack holds a
97601 ** new rowid that is about to be inserted.  If that new rowid is
97602 ** larger than the maximum rowid in the memId memory cell, then the
97603 ** memory cell is updated.  The stack is unchanged.
97604 */
97605 static void autoIncStep(Parse *pParse, int memId, int regRowid){
97606   if( memId>0 ){
97607     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
97608   }
97609 }
97610 
97611 /*
97612 ** This routine generates the code needed to write autoincrement
97613 ** maximum rowid values back into the sqlite_sequence register.
97614 ** Every statement that might do an INSERT into an autoincrement
97615 ** table (either directly or through triggers) needs to call this
97616 ** routine just before the "exit" code.
97617 */
97618 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
97619   AutoincInfo *p;
97620   Vdbe *v = pParse->pVdbe;
97621   sqlite3 *db = pParse->db;
97622 
97623   assert( v );
97624   for(p = pParse->pAinc; p; p = p->pNext){
97625     Db *pDb = &db->aDb[p->iDb];
97626     int j1;
97627     int iRec;
97628     int memId = p->regCtr;
97629 
97630     iRec = sqlite3GetTempReg(pParse);
97631     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
97632     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
97633     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v);
97634     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
97635     sqlite3VdbeJumpHere(v, j1);
97636     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
97637     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
97638     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
97639     sqlite3VdbeAddOp0(v, OP_Close);
97640     sqlite3ReleaseTempReg(pParse, iRec);
97641   }
97642 }
97643 #else
97644 /*
97645 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
97646 ** above are all no-ops
97647 */
97648 # define autoIncBegin(A,B,C) (0)
97649 # define autoIncStep(A,B,C)
97650 #endif /* SQLITE_OMIT_AUTOINCREMENT */
97651 
97652 
97653 /* Forward declaration */
97654 static int xferOptimization(
97655   Parse *pParse,        /* Parser context */
97656   Table *pDest,         /* The table we are inserting into */
97657   Select *pSelect,      /* A SELECT statement to use as the data source */
97658   int onError,          /* How to handle constraint errors */
97659   int iDbDest           /* The database of pDest */
97660 );
97661 
97662 /*
97663 ** This routine is called to handle SQL of the following forms:
97664 **
97665 **    insert into TABLE (IDLIST) values(EXPRLIST)
97666 **    insert into TABLE (IDLIST) select
97667 **
97668 ** The IDLIST following the table name is always optional.  If omitted,
97669 ** then a list of all columns for the table is substituted.  The IDLIST
97670 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
97671 **
97672 ** The pList parameter holds EXPRLIST in the first form of the INSERT
97673 ** statement above, and pSelect is NULL.  For the second form, pList is
97674 ** NULL and pSelect is a pointer to the select statement used to generate
97675 ** data for the insert.
97676 **
97677 ** The code generated follows one of four templates.  For a simple
97678 ** insert with data coming from a VALUES clause, the code executes
97679 ** once straight down through.  Pseudo-code follows (we call this
97680 ** the "1st template"):
97681 **
97682 **         open write cursor to <table> and its indices
97683 **         put VALUES clause expressions into registers
97684 **         write the resulting record into <table>
97685 **         cleanup
97686 **
97687 ** The three remaining templates assume the statement is of the form
97688 **
97689 **   INSERT INTO <table> SELECT ...
97690 **
97691 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
97692 ** in other words if the SELECT pulls all columns from a single table
97693 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
97694 ** if <table2> and <table1> are distinct tables but have identical
97695 ** schemas, including all the same indices, then a special optimization
97696 ** is invoked that copies raw records from <table2> over to <table1>.
97697 ** See the xferOptimization() function for the implementation of this
97698 ** template.  This is the 2nd template.
97699 **
97700 **         open a write cursor to <table>
97701 **         open read cursor on <table2>
97702 **         transfer all records in <table2> over to <table>
97703 **         close cursors
97704 **         foreach index on <table>
97705 **           open a write cursor on the <table> index
97706 **           open a read cursor on the corresponding <table2> index
97707 **           transfer all records from the read to the write cursors
97708 **           close cursors
97709 **         end foreach
97710 **
97711 ** The 3rd template is for when the second template does not apply
97712 ** and the SELECT clause does not read from <table> at any time.
97713 ** The generated code follows this template:
97714 **
97715 **         X <- A
97716 **         goto B
97717 **      A: setup for the SELECT
97718 **         loop over the rows in the SELECT
97719 **           load values into registers R..R+n
97720 **           yield X
97721 **         end loop
97722 **         cleanup after the SELECT
97723 **         end-coroutine X
97724 **      B: open write cursor to <table> and its indices
97725 **      C: yield X, at EOF goto D
97726 **         insert the select result into <table> from R..R+n
97727 **         goto C
97728 **      D: cleanup
97729 **
97730 ** The 4th template is used if the insert statement takes its
97731 ** values from a SELECT but the data is being inserted into a table
97732 ** that is also read as part of the SELECT.  In the third form,
97733 ** we have to use an intermediate table to store the results of
97734 ** the select.  The template is like this:
97735 **
97736 **         X <- A
97737 **         goto B
97738 **      A: setup for the SELECT
97739 **         loop over the tables in the SELECT
97740 **           load value into register R..R+n
97741 **           yield X
97742 **         end loop
97743 **         cleanup after the SELECT
97744 **         end co-routine R
97745 **      B: open temp table
97746 **      L: yield X, at EOF goto M
97747 **         insert row from R..R+n into temp table
97748 **         goto L
97749 **      M: open write cursor to <table> and its indices
97750 **         rewind temp table
97751 **      C: loop over rows of intermediate table
97752 **           transfer values form intermediate table into <table>
97753 **         end loop
97754 **      D: cleanup
97755 */
97756 SQLITE_PRIVATE void sqlite3Insert(
97757   Parse *pParse,        /* Parser context */
97758   SrcList *pTabList,    /* Name of table into which we are inserting */
97759   Select *pSelect,      /* A SELECT statement to use as the data source */
97760   IdList *pColumn,      /* Column names corresponding to IDLIST. */
97761   int onError           /* How to handle constraint errors */
97762 ){
97763   sqlite3 *db;          /* The main database structure */
97764   Table *pTab;          /* The table to insert into.  aka TABLE */
97765   char *zTab;           /* Name of the table into which we are inserting */
97766   const char *zDb;      /* Name of the database holding this table */
97767   int i, j, idx;        /* Loop counters */
97768   Vdbe *v;              /* Generate code into this virtual machine */
97769   Index *pIdx;          /* For looping over indices of the table */
97770   int nColumn;          /* Number of columns in the data */
97771   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
97772   int iDataCur = 0;     /* VDBE cursor that is the main data repository */
97773   int iIdxCur = 0;      /* First index cursor */
97774   int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
97775   int endOfLoop;        /* Label for the end of the insertion loop */
97776   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
97777   int addrInsTop = 0;   /* Jump to label "D" */
97778   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
97779   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
97780   int iDb;              /* Index of database holding TABLE */
97781   Db *pDb;              /* The database containing table being inserted into */
97782   u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
97783   u8 appendFlag = 0;    /* True if the insert is likely to be an append */
97784   u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
97785   u8 bIdListInOrder = 1; /* True if IDLIST is in table order */
97786   ExprList *pList = 0;  /* List of VALUES() to be inserted  */
97787 
97788   /* Register allocations */
97789   int regFromSelect = 0;/* Base register for data coming from SELECT */
97790   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
97791   int regRowCount = 0;  /* Memory cell used for the row counter */
97792   int regIns;           /* Block of regs holding rowid+data being inserted */
97793   int regRowid;         /* registers holding insert rowid */
97794   int regData;          /* register holding first column to insert */
97795   int *aRegIdx = 0;     /* One register allocated to each index */
97796 
97797 #ifndef SQLITE_OMIT_TRIGGER
97798   int isView;                 /* True if attempting to insert into a view */
97799   Trigger *pTrigger;          /* List of triggers on pTab, if required */
97800   int tmask;                  /* Mask of trigger times */
97801 #endif
97802 
97803   db = pParse->db;
97804   memset(&dest, 0, sizeof(dest));
97805   if( pParse->nErr || db->mallocFailed ){
97806     goto insert_cleanup;
97807   }
97808 
97809   /* If the Select object is really just a simple VALUES() list with a
97810   ** single row values (the common case) then keep that one row of values
97811   ** and go ahead and discard the Select object
97812   */
97813   if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
97814     pList = pSelect->pEList;
97815     pSelect->pEList = 0;
97816     sqlite3SelectDelete(db, pSelect);
97817     pSelect = 0;
97818   }
97819 
97820   /* Locate the table into which we will be inserting new information.
97821   */
97822   assert( pTabList->nSrc==1 );
97823   zTab = pTabList->a[0].zName;
97824   if( NEVER(zTab==0) ) goto insert_cleanup;
97825   pTab = sqlite3SrcListLookup(pParse, pTabList);
97826   if( pTab==0 ){
97827     goto insert_cleanup;
97828   }
97829   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
97830   assert( iDb<db->nDb );
97831   pDb = &db->aDb[iDb];
97832   zDb = pDb->zName;
97833   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
97834     goto insert_cleanup;
97835   }
97836   withoutRowid = !HasRowid(pTab);
97837 
97838   /* Figure out if we have any triggers and if the table being
97839   ** inserted into is a view
97840   */
97841 #ifndef SQLITE_OMIT_TRIGGER
97842   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
97843   isView = pTab->pSelect!=0;
97844 #else
97845 # define pTrigger 0
97846 # define tmask 0
97847 # define isView 0
97848 #endif
97849 #ifdef SQLITE_OMIT_VIEW
97850 # undef isView
97851 # define isView 0
97852 #endif
97853   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
97854 
97855   /* If pTab is really a view, make sure it has been initialized.
97856   ** ViewGetColumnNames() is a no-op if pTab is not a view.
97857   */
97858   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
97859     goto insert_cleanup;
97860   }
97861 
97862   /* Cannot insert into a read-only table.
97863   */
97864   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
97865     goto insert_cleanup;
97866   }
97867 
97868   /* Allocate a VDBE
97869   */
97870   v = sqlite3GetVdbe(pParse);
97871   if( v==0 ) goto insert_cleanup;
97872   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
97873   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
97874 
97875 #ifndef SQLITE_OMIT_XFER_OPT
97876   /* If the statement is of the form
97877   **
97878   **       INSERT INTO <table1> SELECT * FROM <table2>;
97879   **
97880   ** Then special optimizations can be applied that make the transfer
97881   ** very fast and which reduce fragmentation of indices.
97882   **
97883   ** This is the 2nd template.
97884   */
97885   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
97886     assert( !pTrigger );
97887     assert( pList==0 );
97888     goto insert_end;
97889   }
97890 #endif /* SQLITE_OMIT_XFER_OPT */
97891 
97892   /* If this is an AUTOINCREMENT table, look up the sequence number in the
97893   ** sqlite_sequence table and store it in memory cell regAutoinc.
97894   */
97895   regAutoinc = autoIncBegin(pParse, iDb, pTab);
97896 
97897   /* Allocate registers for holding the rowid of the new row,
97898   ** the content of the new row, and the assembled row record.
97899   */
97900   regRowid = regIns = pParse->nMem+1;
97901   pParse->nMem += pTab->nCol + 1;
97902   if( IsVirtual(pTab) ){
97903     regRowid++;
97904     pParse->nMem++;
97905   }
97906   regData = regRowid+1;
97907 
97908   /* If the INSERT statement included an IDLIST term, then make sure
97909   ** all elements of the IDLIST really are columns of the table and
97910   ** remember the column indices.
97911   **
97912   ** If the table has an INTEGER PRIMARY KEY column and that column
97913   ** is named in the IDLIST, then record in the ipkColumn variable
97914   ** the index into IDLIST of the primary key column.  ipkColumn is
97915   ** the index of the primary key as it appears in IDLIST, not as
97916   ** is appears in the original table.  (The index of the INTEGER
97917   ** PRIMARY KEY in the original table is pTab->iPKey.)
97918   */
97919   if( pColumn ){
97920     for(i=0; i<pColumn->nId; i++){
97921       pColumn->a[i].idx = -1;
97922     }
97923     for(i=0; i<pColumn->nId; i++){
97924       for(j=0; j<pTab->nCol; j++){
97925         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
97926           pColumn->a[i].idx = j;
97927           if( i!=j ) bIdListInOrder = 0;
97928           if( j==pTab->iPKey ){
97929             ipkColumn = i;  assert( !withoutRowid );
97930           }
97931           break;
97932         }
97933       }
97934       if( j>=pTab->nCol ){
97935         if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
97936           ipkColumn = i;
97937           bIdListInOrder = 0;
97938         }else{
97939           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
97940               pTabList, 0, pColumn->a[i].zName);
97941           pParse->checkSchema = 1;
97942           goto insert_cleanup;
97943         }
97944       }
97945     }
97946   }
97947 
97948   /* Figure out how many columns of data are supplied.  If the data
97949   ** is coming from a SELECT statement, then generate a co-routine that
97950   ** produces a single row of the SELECT on each invocation.  The
97951   ** co-routine is the common header to the 3rd and 4th templates.
97952   */
97953   if( pSelect ){
97954     /* Data is coming from a SELECT.  Generate a co-routine to run the SELECT */
97955     int regYield;       /* Register holding co-routine entry-point */
97956     int addrTop;        /* Top of the co-routine */
97957     int rc;             /* Result code */
97958 
97959     regYield = ++pParse->nMem;
97960     addrTop = sqlite3VdbeCurrentAddr(v) + 1;
97961     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
97962     sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
97963     dest.iSdst = bIdListInOrder ? regData : 0;
97964     dest.nSdst = pTab->nCol;
97965     rc = sqlite3Select(pParse, pSelect, &dest);
97966     regFromSelect = dest.iSdst;
97967     assert( pParse->nErr==0 || rc );
97968     if( rc || db->mallocFailed ) goto insert_cleanup;
97969     sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
97970     sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
97971     assert( pSelect->pEList );
97972     nColumn = pSelect->pEList->nExpr;
97973 
97974     /* Set useTempTable to TRUE if the result of the SELECT statement
97975     ** should be written into a temporary table (template 4).  Set to
97976     ** FALSE if each output row of the SELECT can be written directly into
97977     ** the destination table (template 3).
97978     **
97979     ** A temp table must be used if the table being updated is also one
97980     ** of the tables being read by the SELECT statement.  Also use a
97981     ** temp table in the case of row triggers.
97982     */
97983     if( pTrigger || readsTable(pParse, iDb, pTab) ){
97984       useTempTable = 1;
97985     }
97986 
97987     if( useTempTable ){
97988       /* Invoke the coroutine to extract information from the SELECT
97989       ** and add it to a transient table srcTab.  The code generated
97990       ** here is from the 4th template:
97991       **
97992       **      B: open temp table
97993       **      L: yield X, goto M at EOF
97994       **         insert row from R..R+n into temp table
97995       **         goto L
97996       **      M: ...
97997       */
97998       int regRec;          /* Register to hold packed record */
97999       int regTempRowid;    /* Register to hold temp table ROWID */
98000       int addrL;           /* Label "L" */
98001 
98002       srcTab = pParse->nTab++;
98003       regRec = sqlite3GetTempReg(pParse);
98004       regTempRowid = sqlite3GetTempReg(pParse);
98005       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
98006       addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
98007       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
98008       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
98009       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
98010       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrL);
98011       sqlite3VdbeJumpHere(v, addrL);
98012       sqlite3ReleaseTempReg(pParse, regRec);
98013       sqlite3ReleaseTempReg(pParse, regTempRowid);
98014     }
98015   }else{
98016     /* This is the case if the data for the INSERT is coming from a VALUES
98017     ** clause
98018     */
98019     NameContext sNC;
98020     memset(&sNC, 0, sizeof(sNC));
98021     sNC.pParse = pParse;
98022     srcTab = -1;
98023     assert( useTempTable==0 );
98024     nColumn = pList ? pList->nExpr : 0;
98025     for(i=0; i<nColumn; i++){
98026       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
98027         goto insert_cleanup;
98028       }
98029     }
98030   }
98031 
98032   /* If there is no IDLIST term but the table has an integer primary
98033   ** key, the set the ipkColumn variable to the integer primary key
98034   ** column index in the original table definition.
98035   */
98036   if( pColumn==0 && nColumn>0 ){
98037     ipkColumn = pTab->iPKey;
98038   }
98039 
98040   /* Make sure the number of columns in the source data matches the number
98041   ** of columns to be inserted into the table.
98042   */
98043   if( IsVirtual(pTab) ){
98044     for(i=0; i<pTab->nCol; i++){
98045       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
98046     }
98047   }
98048   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
98049     sqlite3ErrorMsg(pParse,
98050        "table %S has %d columns but %d values were supplied",
98051        pTabList, 0, pTab->nCol-nHidden, nColumn);
98052     goto insert_cleanup;
98053   }
98054   if( pColumn!=0 && nColumn!=pColumn->nId ){
98055     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
98056     goto insert_cleanup;
98057   }
98058 
98059   /* Initialize the count of rows to be inserted
98060   */
98061   if( db->flags & SQLITE_CountRows ){
98062     regRowCount = ++pParse->nMem;
98063     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
98064   }
98065 
98066   /* If this is not a view, open the table and and all indices */
98067   if( !isView ){
98068     int nIdx;
98069     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1, 0,
98070                                       &iDataCur, &iIdxCur);
98071     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
98072     if( aRegIdx==0 ){
98073       goto insert_cleanup;
98074     }
98075     for(i=0; i<nIdx; i++){
98076       aRegIdx[i] = ++pParse->nMem;
98077     }
98078   }
98079 
98080   /* This is the top of the main insertion loop */
98081   if( useTempTable ){
98082     /* This block codes the top of loop only.  The complete loop is the
98083     ** following pseudocode (template 4):
98084     **
98085     **         rewind temp table, if empty goto D
98086     **      C: loop over rows of intermediate table
98087     **           transfer values form intermediate table into <table>
98088     **         end loop
98089     **      D: ...
98090     */
98091     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
98092     addrCont = sqlite3VdbeCurrentAddr(v);
98093   }else if( pSelect ){
98094     /* This block codes the top of loop only.  The complete loop is the
98095     ** following pseudocode (template 3):
98096     **
98097     **      C: yield X, at EOF goto D
98098     **         insert the select result into <table> from R..R+n
98099     **         goto C
98100     **      D: ...
98101     */
98102     addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
98103     VdbeCoverage(v);
98104   }
98105 
98106   /* Run the BEFORE and INSTEAD OF triggers, if there are any
98107   */
98108   endOfLoop = sqlite3VdbeMakeLabel(v);
98109   if( tmask & TRIGGER_BEFORE ){
98110     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
98111 
98112     /* build the NEW.* reference row.  Note that if there is an INTEGER
98113     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
98114     ** translated into a unique ID for the row.  But on a BEFORE trigger,
98115     ** we do not know what the unique ID will be (because the insert has
98116     ** not happened yet) so we substitute a rowid of -1
98117     */
98118     if( ipkColumn<0 ){
98119       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
98120     }else{
98121       int j1;
98122       assert( !withoutRowid );
98123       if( useTempTable ){
98124         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
98125       }else{
98126         assert( pSelect==0 );  /* Otherwise useTempTable is true */
98127         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
98128       }
98129       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
98130       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
98131       sqlite3VdbeJumpHere(v, j1);
98132       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
98133     }
98134 
98135     /* Cannot have triggers on a virtual table. If it were possible,
98136     ** this block would have to account for hidden column.
98137     */
98138     assert( !IsVirtual(pTab) );
98139 
98140     /* Create the new column data
98141     */
98142     for(i=0; i<pTab->nCol; i++){
98143       if( pColumn==0 ){
98144         j = i;
98145       }else{
98146         for(j=0; j<pColumn->nId; j++){
98147           if( pColumn->a[j].idx==i ) break;
98148         }
98149       }
98150       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
98151         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
98152       }else if( useTempTable ){
98153         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
98154       }else{
98155         assert( pSelect==0 ); /* Otherwise useTempTable is true */
98156         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
98157       }
98158     }
98159 
98160     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
98161     ** do not attempt any conversions before assembling the record.
98162     ** If this is a real table, attempt conversions as required by the
98163     ** table column affinities.
98164     */
98165     if( !isView ){
98166       sqlite3TableAffinity(v, pTab, regCols+1);
98167     }
98168 
98169     /* Fire BEFORE or INSTEAD OF triggers */
98170     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
98171         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
98172 
98173     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
98174   }
98175 
98176   /* Compute the content of the next row to insert into a range of
98177   ** registers beginning at regIns.
98178   */
98179   if( !isView ){
98180     if( IsVirtual(pTab) ){
98181       /* The row that the VUpdate opcode will delete: none */
98182       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
98183     }
98184     if( ipkColumn>=0 ){
98185       if( useTempTable ){
98186         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
98187       }else if( pSelect ){
98188         sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
98189       }else{
98190         VdbeOp *pOp;
98191         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
98192         pOp = sqlite3VdbeGetOp(v, -1);
98193         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
98194           appendFlag = 1;
98195           pOp->opcode = OP_NewRowid;
98196           pOp->p1 = iDataCur;
98197           pOp->p2 = regRowid;
98198           pOp->p3 = regAutoinc;
98199         }
98200       }
98201       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
98202       ** to generate a unique primary key value.
98203       */
98204       if( !appendFlag ){
98205         int j1;
98206         if( !IsVirtual(pTab) ){
98207           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
98208           sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
98209           sqlite3VdbeJumpHere(v, j1);
98210         }else{
98211           j1 = sqlite3VdbeCurrentAddr(v);
98212           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); VdbeCoverage(v);
98213         }
98214         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
98215       }
98216     }else if( IsVirtual(pTab) || withoutRowid ){
98217       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
98218     }else{
98219       sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
98220       appendFlag = 1;
98221     }
98222     autoIncStep(pParse, regAutoinc, regRowid);
98223 
98224     /* Compute data for all columns of the new entry, beginning
98225     ** with the first column.
98226     */
98227     nHidden = 0;
98228     for(i=0; i<pTab->nCol; i++){
98229       int iRegStore = regRowid+1+i;
98230       if( i==pTab->iPKey ){
98231         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
98232         ** Whenever this column is read, the rowid will be substituted
98233         ** in its place.  Hence, fill this column with a NULL to avoid
98234         ** taking up data space with information that will never be used.
98235         ** As there may be shallow copies of this value, make it a soft-NULL */
98236         sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
98237         continue;
98238       }
98239       if( pColumn==0 ){
98240         if( IsHiddenColumn(&pTab->aCol[i]) ){
98241           assert( IsVirtual(pTab) );
98242           j = -1;
98243           nHidden++;
98244         }else{
98245           j = i - nHidden;
98246         }
98247       }else{
98248         for(j=0; j<pColumn->nId; j++){
98249           if( pColumn->a[j].idx==i ) break;
98250         }
98251       }
98252       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
98253         sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
98254       }else if( useTempTable ){
98255         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
98256       }else if( pSelect ){
98257         if( regFromSelect!=regData ){
98258           sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
98259         }
98260       }else{
98261         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
98262       }
98263     }
98264 
98265     /* Generate code to check constraints and generate index keys and
98266     ** do the insertion.
98267     */
98268 #ifndef SQLITE_OMIT_VIRTUALTABLE
98269     if( IsVirtual(pTab) ){
98270       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
98271       sqlite3VtabMakeWritable(pParse, pTab);
98272       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
98273       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
98274       sqlite3MayAbort(pParse);
98275     }else
98276 #endif
98277     {
98278       int isReplace;    /* Set to true if constraints may cause a replace */
98279       sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
98280           regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace
98281       );
98282       sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
98283       sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
98284                                regIns, aRegIdx, 0, appendFlag, isReplace==0);
98285     }
98286   }
98287 
98288   /* Update the count of rows that are inserted
98289   */
98290   if( (db->flags & SQLITE_CountRows)!=0 ){
98291     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
98292   }
98293 
98294   if( pTrigger ){
98295     /* Code AFTER triggers */
98296     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
98297         pTab, regData-2-pTab->nCol, onError, endOfLoop);
98298   }
98299 
98300   /* The bottom of the main insertion loop, if the data source
98301   ** is a SELECT statement.
98302   */
98303   sqlite3VdbeResolveLabel(v, endOfLoop);
98304   if( useTempTable ){
98305     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
98306     sqlite3VdbeJumpHere(v, addrInsTop);
98307     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
98308   }else if( pSelect ){
98309     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
98310     sqlite3VdbeJumpHere(v, addrInsTop);
98311   }
98312 
98313   if( !IsVirtual(pTab) && !isView ){
98314     /* Close all tables opened */
98315     if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
98316     for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
98317       sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
98318     }
98319   }
98320 
98321 insert_end:
98322   /* Update the sqlite_sequence table by storing the content of the
98323   ** maximum rowid counter values recorded while inserting into
98324   ** autoincrement tables.
98325   */
98326   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
98327     sqlite3AutoincrementEnd(pParse);
98328   }
98329 
98330   /*
98331   ** Return the number of rows inserted. If this routine is
98332   ** generating code because of a call to sqlite3NestedParse(), do not
98333   ** invoke the callback function.
98334   */
98335   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
98336     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
98337     sqlite3VdbeSetNumCols(v, 1);
98338     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
98339   }
98340 
98341 insert_cleanup:
98342   sqlite3SrcListDelete(db, pTabList);
98343   sqlite3ExprListDelete(db, pList);
98344   sqlite3SelectDelete(db, pSelect);
98345   sqlite3IdListDelete(db, pColumn);
98346   sqlite3DbFree(db, aRegIdx);
98347 }
98348 
98349 /* Make sure "isView" and other macros defined above are undefined. Otherwise
98350 ** they may interfere with compilation of other functions in this file
98351 ** (or in another file, if this file becomes part of the amalgamation).  */
98352 #ifdef isView
98353  #undef isView
98354 #endif
98355 #ifdef pTrigger
98356  #undef pTrigger
98357 #endif
98358 #ifdef tmask
98359  #undef tmask
98360 #endif
98361 
98362 /*
98363 ** Generate code to do constraint checks prior to an INSERT or an UPDATE
98364 ** on table pTab.
98365 **
98366 ** The regNewData parameter is the first register in a range that contains
98367 ** the data to be inserted or the data after the update.  There will be
98368 ** pTab->nCol+1 registers in this range.  The first register (the one
98369 ** that regNewData points to) will contain the new rowid, or NULL in the
98370 ** case of a WITHOUT ROWID table.  The second register in the range will
98371 ** contain the content of the first table column.  The third register will
98372 ** contain the content of the second table column.  And so forth.
98373 **
98374 ** The regOldData parameter is similar to regNewData except that it contains
98375 ** the data prior to an UPDATE rather than afterwards.  regOldData is zero
98376 ** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
98377 ** checking regOldData for zero.
98378 **
98379 ** For an UPDATE, the pkChng boolean is true if the true primary key (the
98380 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
98381 ** might be modified by the UPDATE.  If pkChng is false, then the key of
98382 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
98383 **
98384 ** For an INSERT, the pkChng boolean indicates whether or not the rowid
98385 ** was explicitly specified as part of the INSERT statement.  If pkChng
98386 ** is zero, it means that the either rowid is computed automatically or
98387 ** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
98388 ** pkChng will only be true if the INSERT statement provides an integer
98389 ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
98390 **
98391 ** The code generated by this routine will store new index entries into
98392 ** registers identified by aRegIdx[].  No index entry is created for
98393 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
98394 ** the same as the order of indices on the linked list of indices
98395 ** at pTab->pIndex.
98396 **
98397 ** The caller must have already opened writeable cursors on the main
98398 ** table and all applicable indices (that is to say, all indices for which
98399 ** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
98400 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
98401 ** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
98402 ** for the first index in the pTab->pIndex list.  Cursors for other indices
98403 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
98404 **
98405 ** This routine also generates code to check constraints.  NOT NULL,
98406 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
98407 ** then the appropriate action is performed.  There are five possible
98408 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
98409 **
98410 **  Constraint type  Action       What Happens
98411 **  ---------------  ----------   ----------------------------------------
98412 **  any              ROLLBACK     The current transaction is rolled back and
98413 **                                sqlite3_step() returns immediately with a
98414 **                                return code of SQLITE_CONSTRAINT.
98415 **
98416 **  any              ABORT        Back out changes from the current command
98417 **                                only (do not do a complete rollback) then
98418 **                                cause sqlite3_step() to return immediately
98419 **                                with SQLITE_CONSTRAINT.
98420 **
98421 **  any              FAIL         Sqlite3_step() returns immediately with a
98422 **                                return code of SQLITE_CONSTRAINT.  The
98423 **                                transaction is not rolled back and any
98424 **                                changes to prior rows are retained.
98425 **
98426 **  any              IGNORE       The attempt in insert or update the current
98427 **                                row is skipped, without throwing an error.
98428 **                                Processing continues with the next row.
98429 **                                (There is an immediate jump to ignoreDest.)
98430 **
98431 **  NOT NULL         REPLACE      The NULL value is replace by the default
98432 **                                value for that column.  If the default value
98433 **                                is NULL, the action is the same as ABORT.
98434 **
98435 **  UNIQUE           REPLACE      The other row that conflicts with the row
98436 **                                being inserted is removed.
98437 **
98438 **  CHECK            REPLACE      Illegal.  The results in an exception.
98439 **
98440 ** Which action to take is determined by the overrideError parameter.
98441 ** Or if overrideError==OE_Default, then the pParse->onError parameter
98442 ** is used.  Or if pParse->onError==OE_Default then the onError value
98443 ** for the constraint is used.
98444 */
98445 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
98446   Parse *pParse,       /* The parser context */
98447   Table *pTab,         /* The table being inserted or updated */
98448   int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
98449   int iDataCur,        /* Canonical data cursor (main table or PK index) */
98450   int iIdxCur,         /* First index cursor */
98451   int regNewData,      /* First register in a range holding values to insert */
98452   int regOldData,      /* Previous content.  0 for INSERTs */
98453   u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
98454   u8 overrideError,    /* Override onError to this if not OE_Default */
98455   int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
98456   int *pbMayReplace    /* OUT: Set to true if constraint may cause a replace */
98457 ){
98458   Vdbe *v;             /* VDBE under constrution */
98459   Index *pIdx;         /* Pointer to one of the indices */
98460   Index *pPk = 0;      /* The PRIMARY KEY index */
98461   sqlite3 *db;         /* Database connection */
98462   int i;               /* loop counter */
98463   int ix;              /* Index loop counter */
98464   int nCol;            /* Number of columns */
98465   int onError;         /* Conflict resolution strategy */
98466   int j1;              /* Address of jump instruction */
98467   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
98468   int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
98469   int ipkTop = 0;      /* Top of the rowid change constraint check */
98470   int ipkBottom = 0;   /* Bottom of the rowid change constraint check */
98471   u8 isUpdate;         /* True if this is an UPDATE operation */
98472   u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
98473   int regRowid = -1;   /* Register holding ROWID value */
98474 
98475   isUpdate = regOldData!=0;
98476   db = pParse->db;
98477   v = sqlite3GetVdbe(pParse);
98478   assert( v!=0 );
98479   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
98480   nCol = pTab->nCol;
98481 
98482   /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
98483   ** normal rowid tables.  nPkField is the number of key fields in the
98484   ** pPk index or 1 for a rowid table.  In other words, nPkField is the
98485   ** number of fields in the true primary key of the table. */
98486   if( HasRowid(pTab) ){
98487     pPk = 0;
98488     nPkField = 1;
98489   }else{
98490     pPk = sqlite3PrimaryKeyIndex(pTab);
98491     nPkField = pPk->nKeyCol;
98492   }
98493 
98494   /* Record that this module has started */
98495   VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
98496                      iDataCur, iIdxCur, regNewData, regOldData, pkChng));
98497 
98498   /* Test all NOT NULL constraints.
98499   */
98500   for(i=0; i<nCol; i++){
98501     if( i==pTab->iPKey ){
98502       continue;
98503     }
98504     onError = pTab->aCol[i].notNull;
98505     if( onError==OE_None ) continue;
98506     if( overrideError!=OE_Default ){
98507       onError = overrideError;
98508     }else if( onError==OE_Default ){
98509       onError = OE_Abort;
98510     }
98511     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
98512       onError = OE_Abort;
98513     }
98514     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
98515         || onError==OE_Ignore || onError==OE_Replace );
98516     switch( onError ){
98517       case OE_Abort:
98518         sqlite3MayAbort(pParse);
98519         /* Fall through */
98520       case OE_Rollback:
98521       case OE_Fail: {
98522         char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
98523                                     pTab->aCol[i].zName);
98524         sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
98525                           regNewData+1+i, zMsg, P4_DYNAMIC);
98526         sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
98527         VdbeCoverage(v);
98528         break;
98529       }
98530       case OE_Ignore: {
98531         sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
98532         VdbeCoverage(v);
98533         break;
98534       }
98535       default: {
98536         assert( onError==OE_Replace );
98537         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); VdbeCoverage(v);
98538         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
98539         sqlite3VdbeJumpHere(v, j1);
98540         break;
98541       }
98542     }
98543   }
98544 
98545   /* Test all CHECK constraints
98546   */
98547 #ifndef SQLITE_OMIT_CHECK
98548   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
98549     ExprList *pCheck = pTab->pCheck;
98550     pParse->ckBase = regNewData+1;
98551     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
98552     for(i=0; i<pCheck->nExpr; i++){
98553       int allOk = sqlite3VdbeMakeLabel(v);
98554       sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
98555       if( onError==OE_Ignore ){
98556         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
98557       }else{
98558         char *zName = pCheck->a[i].zName;
98559         if( zName==0 ) zName = pTab->zName;
98560         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
98561         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
98562                               onError, zName, P4_TRANSIENT,
98563                               P5_ConstraintCheck);
98564       }
98565       sqlite3VdbeResolveLabel(v, allOk);
98566     }
98567   }
98568 #endif /* !defined(SQLITE_OMIT_CHECK) */
98569 
98570   /* If rowid is changing, make sure the new rowid does not previously
98571   ** exist in the table.
98572   */
98573   if( pkChng && pPk==0 ){
98574     int addrRowidOk = sqlite3VdbeMakeLabel(v);
98575 
98576     /* Figure out what action to take in case of a rowid collision */
98577     onError = pTab->keyConf;
98578     if( overrideError!=OE_Default ){
98579       onError = overrideError;
98580     }else if( onError==OE_Default ){
98581       onError = OE_Abort;
98582     }
98583 
98584     if( isUpdate ){
98585       /* pkChng!=0 does not mean that the rowid has change, only that
98586       ** it might have changed.  Skip the conflict logic below if the rowid
98587       ** is unchanged. */
98588       sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
98589       sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
98590       VdbeCoverage(v);
98591     }
98592 
98593     /* If the response to a rowid conflict is REPLACE but the response
98594     ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
98595     ** to defer the running of the rowid conflict checking until after
98596     ** the UNIQUE constraints have run.
98597     */
98598     if( onError==OE_Replace && overrideError!=OE_Replace ){
98599       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
98600         if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
98601           ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
98602           break;
98603         }
98604       }
98605     }
98606 
98607     /* Check to see if the new rowid already exists in the table.  Skip
98608     ** the following conflict logic if it does not. */
98609     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
98610     VdbeCoverage(v);
98611 
98612     /* Generate code that deals with a rowid collision */
98613     switch( onError ){
98614       default: {
98615         onError = OE_Abort;
98616         /* Fall thru into the next case */
98617       }
98618       case OE_Rollback:
98619       case OE_Abort:
98620       case OE_Fail: {
98621         sqlite3RowidConstraint(pParse, onError, pTab);
98622         break;
98623       }
98624       case OE_Replace: {
98625         /* If there are DELETE triggers on this table and the
98626         ** recursive-triggers flag is set, call GenerateRowDelete() to
98627         ** remove the conflicting row from the table. This will fire
98628         ** the triggers and remove both the table and index b-tree entries.
98629         **
98630         ** Otherwise, if there are no triggers or the recursive-triggers
98631         ** flag is not set, but the table has one or more indexes, call
98632         ** GenerateRowIndexDelete(). This removes the index b-tree entries
98633         ** only. The table b-tree entry will be replaced by the new entry
98634         ** when it is inserted.
98635         **
98636         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
98637         ** also invoke MultiWrite() to indicate that this VDBE may require
98638         ** statement rollback (if the statement is aborted after the delete
98639         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
98640         ** but being more selective here allows statements like:
98641         **
98642         **   REPLACE INTO t(rowid) VALUES($newrowid)
98643         **
98644         ** to run without a statement journal if there are no indexes on the
98645         ** table.
98646         */
98647         Trigger *pTrigger = 0;
98648         if( db->flags&SQLITE_RecTriggers ){
98649           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
98650         }
98651         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
98652           sqlite3MultiWrite(pParse);
98653           sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
98654                                    regNewData, 1, 0, OE_Replace, 1);
98655         }else if( pTab->pIndex ){
98656           sqlite3MultiWrite(pParse);
98657           sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
98658         }
98659         seenReplace = 1;
98660         break;
98661       }
98662       case OE_Ignore: {
98663         /*assert( seenReplace==0 );*/
98664         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
98665         break;
98666       }
98667     }
98668     sqlite3VdbeResolveLabel(v, addrRowidOk);
98669     if( ipkTop ){
98670       ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
98671       sqlite3VdbeJumpHere(v, ipkTop);
98672     }
98673   }
98674 
98675   /* Test all UNIQUE constraints by creating entries for each UNIQUE
98676   ** index and making sure that duplicate entries do not already exist.
98677   ** Compute the revised record entries for indices as we go.
98678   **
98679   ** This loop also handles the case of the PRIMARY KEY index for a
98680   ** WITHOUT ROWID table.
98681   */
98682   for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
98683     int regIdx;          /* Range of registers hold conent for pIdx */
98684     int regR;            /* Range of registers holding conflicting PK */
98685     int iThisCur;        /* Cursor for this UNIQUE index */
98686     int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
98687 
98688     if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
98689     if( bAffinityDone==0 ){
98690       sqlite3TableAffinity(v, pTab, regNewData+1);
98691       bAffinityDone = 1;
98692     }
98693     iThisCur = iIdxCur+ix;
98694     addrUniqueOk = sqlite3VdbeMakeLabel(v);
98695 
98696     /* Skip partial indices for which the WHERE clause is not true */
98697     if( pIdx->pPartIdxWhere ){
98698       sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
98699       pParse->ckBase = regNewData+1;
98700       sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
98701                          SQLITE_JUMPIFNULL);
98702       pParse->ckBase = 0;
98703     }
98704 
98705     /* Create a record for this index entry as it should appear after
98706     ** the insert or update.  Store that record in the aRegIdx[ix] register
98707     */
98708     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
98709     for(i=0; i<pIdx->nColumn; i++){
98710       int iField = pIdx->aiColumn[i];
98711       int x;
98712       if( iField<0 || iField==pTab->iPKey ){
98713         if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
98714         x = regNewData;
98715         regRowid =  pIdx->pPartIdxWhere ? -1 : regIdx+i;
98716       }else{
98717         x = iField + regNewData + 1;
98718       }
98719       sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
98720       VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
98721     }
98722     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
98723     VdbeComment((v, "for %s", pIdx->zName));
98724     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
98725 
98726     /* In an UPDATE operation, if this index is the PRIMARY KEY index
98727     ** of a WITHOUT ROWID table and there has been no change the
98728     ** primary key, then no collision is possible.  The collision detection
98729     ** logic below can all be skipped. */
98730     if( isUpdate && pPk==pIdx && pkChng==0 ){
98731       sqlite3VdbeResolveLabel(v, addrUniqueOk);
98732       continue;
98733     }
98734 
98735     /* Find out what action to take in case there is a uniqueness conflict */
98736     onError = pIdx->onError;
98737     if( onError==OE_None ){
98738       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
98739       sqlite3VdbeResolveLabel(v, addrUniqueOk);
98740       continue;  /* pIdx is not a UNIQUE index */
98741     }
98742     if( overrideError!=OE_Default ){
98743       onError = overrideError;
98744     }else if( onError==OE_Default ){
98745       onError = OE_Abort;
98746     }
98747 
98748     /* Check to see if the new index entry will be unique */
98749     sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
98750                          regIdx, pIdx->nKeyCol); VdbeCoverage(v);
98751 
98752     /* Generate code to handle collisions */
98753     regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
98754     if( isUpdate || onError==OE_Replace ){
98755       if( HasRowid(pTab) ){
98756         sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
98757         /* Conflict only if the rowid of the existing index entry
98758         ** is different from old-rowid */
98759         if( isUpdate ){
98760           sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
98761           sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
98762           VdbeCoverage(v);
98763         }
98764       }else{
98765         int x;
98766         /* Extract the PRIMARY KEY from the end of the index entry and
98767         ** store it in registers regR..regR+nPk-1 */
98768         if( pIdx!=pPk ){
98769           for(i=0; i<pPk->nKeyCol; i++){
98770             x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
98771             sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
98772             VdbeComment((v, "%s.%s", pTab->zName,
98773                          pTab->aCol[pPk->aiColumn[i]].zName));
98774           }
98775         }
98776         if( isUpdate ){
98777           /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
98778           ** table, only conflict if the new PRIMARY KEY values are actually
98779           ** different from the old.
98780           **
98781           ** For a UNIQUE index, only conflict if the PRIMARY KEY values
98782           ** of the matched index row are different from the original PRIMARY
98783           ** KEY values of this row before the update.  */
98784           int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
98785           int op = OP_Ne;
98786           int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
98787 
98788           for(i=0; i<pPk->nKeyCol; i++){
98789             char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
98790             x = pPk->aiColumn[i];
98791             if( i==(pPk->nKeyCol-1) ){
98792               addrJump = addrUniqueOk;
98793               op = OP_Eq;
98794             }
98795             sqlite3VdbeAddOp4(v, op,
98796                 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
98797             );
98798             sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
98799             VdbeCoverageIf(v, op==OP_Eq);
98800             VdbeCoverageIf(v, op==OP_Ne);
98801           }
98802         }
98803       }
98804     }
98805 
98806     /* Generate code that executes if the new index entry is not unique */
98807     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
98808         || onError==OE_Ignore || onError==OE_Replace );
98809     switch( onError ){
98810       case OE_Rollback:
98811       case OE_Abort:
98812       case OE_Fail: {
98813         sqlite3UniqueConstraint(pParse, onError, pIdx);
98814         break;
98815       }
98816       case OE_Ignore: {
98817         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
98818         break;
98819       }
98820       default: {
98821         Trigger *pTrigger = 0;
98822         assert( onError==OE_Replace );
98823         sqlite3MultiWrite(pParse);
98824         if( db->flags&SQLITE_RecTriggers ){
98825           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
98826         }
98827         sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
98828                                  regR, nPkField, 0, OE_Replace, pIdx==pPk);
98829         seenReplace = 1;
98830         break;
98831       }
98832     }
98833     sqlite3VdbeResolveLabel(v, addrUniqueOk);
98834     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
98835     if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
98836   }
98837   if( ipkTop ){
98838     sqlite3VdbeAddOp2(v, OP_Goto, 0, ipkTop+1);
98839     sqlite3VdbeJumpHere(v, ipkBottom);
98840   }
98841 
98842   *pbMayReplace = seenReplace;
98843   VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
98844 }
98845 
98846 /*
98847 ** This routine generates code to finish the INSERT or UPDATE operation
98848 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
98849 ** A consecutive range of registers starting at regNewData contains the
98850 ** rowid and the content to be inserted.
98851 **
98852 ** The arguments to this routine should be the same as the first six
98853 ** arguments to sqlite3GenerateConstraintChecks.
98854 */
98855 SQLITE_PRIVATE void sqlite3CompleteInsertion(
98856   Parse *pParse,      /* The parser context */
98857   Table *pTab,        /* the table into which we are inserting */
98858   int iDataCur,       /* Cursor of the canonical data source */
98859   int iIdxCur,        /* First index cursor */
98860   int regNewData,     /* Range of content */
98861   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
98862   int isUpdate,       /* True for UPDATE, False for INSERT */
98863   int appendBias,     /* True if this is likely to be an append */
98864   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
98865 ){
98866   Vdbe *v;            /* Prepared statements under construction */
98867   Index *pIdx;        /* An index being inserted or updated */
98868   u8 pik_flags;       /* flag values passed to the btree insert */
98869   int regData;        /* Content registers (after the rowid) */
98870   int regRec;         /* Register holding assembled record for the table */
98871   int i;              /* Loop counter */
98872   u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
98873 
98874   v = sqlite3GetVdbe(pParse);
98875   assert( v!=0 );
98876   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
98877   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
98878     if( aRegIdx[i]==0 ) continue;
98879     bAffinityDone = 1;
98880     if( pIdx->pPartIdxWhere ){
98881       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
98882       VdbeCoverage(v);
98883     }
98884     sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
98885     pik_flags = 0;
98886     if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
98887     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
98888       assert( pParse->nested==0 );
98889       pik_flags |= OPFLAG_NCHANGE;
98890     }
98891     if( pik_flags )  sqlite3VdbeChangeP5(v, pik_flags);
98892   }
98893   if( !HasRowid(pTab) ) return;
98894   regData = regNewData + 1;
98895   regRec = sqlite3GetTempReg(pParse);
98896   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
98897   if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
98898   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
98899   if( pParse->nested ){
98900     pik_flags = 0;
98901   }else{
98902     pik_flags = OPFLAG_NCHANGE;
98903     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
98904   }
98905   if( appendBias ){
98906     pik_flags |= OPFLAG_APPEND;
98907   }
98908   if( useSeekResult ){
98909     pik_flags |= OPFLAG_USESEEKRESULT;
98910   }
98911   sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
98912   if( !pParse->nested ){
98913     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
98914   }
98915   sqlite3VdbeChangeP5(v, pik_flags);
98916 }
98917 
98918 /*
98919 ** Allocate cursors for the pTab table and all its indices and generate
98920 ** code to open and initialized those cursors.
98921 **
98922 ** The cursor for the object that contains the complete data (normally
98923 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
98924 ** ROWID table) is returned in *piDataCur.  The first index cursor is
98925 ** returned in *piIdxCur.  The number of indices is returned.
98926 **
98927 ** Use iBase as the first cursor (either the *piDataCur for rowid tables
98928 ** or the first index for WITHOUT ROWID tables) if it is non-negative.
98929 ** If iBase is negative, then allocate the next available cursor.
98930 **
98931 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
98932 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
98933 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
98934 ** pTab->pIndex list.
98935 **
98936 ** If pTab is a virtual table, then this routine is a no-op and the
98937 ** *piDataCur and *piIdxCur values are left uninitialized.
98938 */
98939 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
98940   Parse *pParse,   /* Parsing context */
98941   Table *pTab,     /* Table to be opened */
98942   int op,          /* OP_OpenRead or OP_OpenWrite */
98943   int iBase,       /* Use this for the table cursor, if there is one */
98944   u8 *aToOpen,     /* If not NULL: boolean for each table and index */
98945   int *piDataCur,  /* Write the database source cursor number here */
98946   int *piIdxCur    /* Write the first index cursor number here */
98947 ){
98948   int i;
98949   int iDb;
98950   int iDataCur;
98951   Index *pIdx;
98952   Vdbe *v;
98953 
98954   assert( op==OP_OpenRead || op==OP_OpenWrite );
98955   if( IsVirtual(pTab) ){
98956     /* This routine is a no-op for virtual tables. Leave the output
98957     ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
98958     ** can detect if they are used by mistake in the caller. */
98959     return 0;
98960   }
98961   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
98962   v = sqlite3GetVdbe(pParse);
98963   assert( v!=0 );
98964   if( iBase<0 ) iBase = pParse->nTab;
98965   iDataCur = iBase++;
98966   if( piDataCur ) *piDataCur = iDataCur;
98967   if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
98968     sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
98969   }else{
98970     sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
98971   }
98972   if( piIdxCur ) *piIdxCur = iBase;
98973   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
98974     int iIdxCur = iBase++;
98975     assert( pIdx->pSchema==pTab->pSchema );
98976     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) && piDataCur ){
98977       *piDataCur = iIdxCur;
98978     }
98979     if( aToOpen==0 || aToOpen[i+1] ){
98980       sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
98981       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
98982       VdbeComment((v, "%s", pIdx->zName));
98983     }
98984   }
98985   if( iBase>pParse->nTab ) pParse->nTab = iBase;
98986   return i;
98987 }
98988 
98989 
98990 #ifdef SQLITE_TEST
98991 /*
98992 ** The following global variable is incremented whenever the
98993 ** transfer optimization is used.  This is used for testing
98994 ** purposes only - to make sure the transfer optimization really
98995 ** is happening when it is supposed to.
98996 */
98997 SQLITE_API int sqlite3_xferopt_count;
98998 #endif /* SQLITE_TEST */
98999 
99000 
99001 #ifndef SQLITE_OMIT_XFER_OPT
99002 /*
99003 ** Check to collation names to see if they are compatible.
99004 */
99005 static int xferCompatibleCollation(const char *z1, const char *z2){
99006   if( z1==0 ){
99007     return z2==0;
99008   }
99009   if( z2==0 ){
99010     return 0;
99011   }
99012   return sqlite3StrICmp(z1, z2)==0;
99013 }
99014 
99015 
99016 /*
99017 ** Check to see if index pSrc is compatible as a source of data
99018 ** for index pDest in an insert transfer optimization.  The rules
99019 ** for a compatible index:
99020 **
99021 **    *   The index is over the same set of columns
99022 **    *   The same DESC and ASC markings occurs on all columns
99023 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
99024 **    *   The same collating sequence on each column
99025 **    *   The index has the exact same WHERE clause
99026 */
99027 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
99028   int i;
99029   assert( pDest && pSrc );
99030   assert( pDest->pTable!=pSrc->pTable );
99031   if( pDest->nKeyCol!=pSrc->nKeyCol ){
99032     return 0;   /* Different number of columns */
99033   }
99034   if( pDest->onError!=pSrc->onError ){
99035     return 0;   /* Different conflict resolution strategies */
99036   }
99037   for(i=0; i<pSrc->nKeyCol; i++){
99038     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
99039       return 0;   /* Different columns indexed */
99040     }
99041     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
99042       return 0;   /* Different sort orders */
99043     }
99044     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
99045       return 0;   /* Different collating sequences */
99046     }
99047   }
99048   if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
99049     return 0;     /* Different WHERE clauses */
99050   }
99051 
99052   /* If no test above fails then the indices must be compatible */
99053   return 1;
99054 }
99055 
99056 /*
99057 ** Attempt the transfer optimization on INSERTs of the form
99058 **
99059 **     INSERT INTO tab1 SELECT * FROM tab2;
99060 **
99061 ** The xfer optimization transfers raw records from tab2 over to tab1.
99062 ** Columns are not decoded and reassembled, which greatly improves
99063 ** performance.  Raw index records are transferred in the same way.
99064 **
99065 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
99066 ** There are lots of rules for determining compatibility - see comments
99067 ** embedded in the code for details.
99068 **
99069 ** This routine returns TRUE if the optimization is guaranteed to be used.
99070 ** Sometimes the xfer optimization will only work if the destination table
99071 ** is empty - a factor that can only be determined at run-time.  In that
99072 ** case, this routine generates code for the xfer optimization but also
99073 ** does a test to see if the destination table is empty and jumps over the
99074 ** xfer optimization code if the test fails.  In that case, this routine
99075 ** returns FALSE so that the caller will know to go ahead and generate
99076 ** an unoptimized transfer.  This routine also returns FALSE if there
99077 ** is no chance that the xfer optimization can be applied.
99078 **
99079 ** This optimization is particularly useful at making VACUUM run faster.
99080 */
99081 static int xferOptimization(
99082   Parse *pParse,        /* Parser context */
99083   Table *pDest,         /* The table we are inserting into */
99084   Select *pSelect,      /* A SELECT statement to use as the data source */
99085   int onError,          /* How to handle constraint errors */
99086   int iDbDest           /* The database of pDest */
99087 ){
99088   ExprList *pEList;                /* The result set of the SELECT */
99089   Table *pSrc;                     /* The table in the FROM clause of SELECT */
99090   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
99091   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
99092   int i;                           /* Loop counter */
99093   int iDbSrc;                      /* The database of pSrc */
99094   int iSrc, iDest;                 /* Cursors from source and destination */
99095   int addr1, addr2;                /* Loop addresses */
99096   int emptyDestTest = 0;           /* Address of test for empty pDest */
99097   int emptySrcTest = 0;            /* Address of test for empty pSrc */
99098   Vdbe *v;                         /* The VDBE we are building */
99099   int regAutoinc;                  /* Memory register used by AUTOINC */
99100   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
99101   int regData, regRowid;           /* Registers holding data and rowid */
99102 
99103   if( pSelect==0 ){
99104     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
99105   }
99106   if( pParse->pWith || pSelect->pWith ){
99107     /* Do not attempt to process this query if there are an WITH clauses
99108     ** attached to it. Proceeding may generate a false "no such table: xxx"
99109     ** error if pSelect reads from a CTE named "xxx".  */
99110     return 0;
99111   }
99112   if( sqlite3TriggerList(pParse, pDest) ){
99113     return 0;   /* tab1 must not have triggers */
99114   }
99115 #ifndef SQLITE_OMIT_VIRTUALTABLE
99116   if( pDest->tabFlags & TF_Virtual ){
99117     return 0;   /* tab1 must not be a virtual table */
99118   }
99119 #endif
99120   if( onError==OE_Default ){
99121     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
99122     if( onError==OE_Default ) onError = OE_Abort;
99123   }
99124   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
99125   if( pSelect->pSrc->nSrc!=1 ){
99126     return 0;   /* FROM clause must have exactly one term */
99127   }
99128   if( pSelect->pSrc->a[0].pSelect ){
99129     return 0;   /* FROM clause cannot contain a subquery */
99130   }
99131   if( pSelect->pWhere ){
99132     return 0;   /* SELECT may not have a WHERE clause */
99133   }
99134   if( pSelect->pOrderBy ){
99135     return 0;   /* SELECT may not have an ORDER BY clause */
99136   }
99137   /* Do not need to test for a HAVING clause.  If HAVING is present but
99138   ** there is no ORDER BY, we will get an error. */
99139   if( pSelect->pGroupBy ){
99140     return 0;   /* SELECT may not have a GROUP BY clause */
99141   }
99142   if( pSelect->pLimit ){
99143     return 0;   /* SELECT may not have a LIMIT clause */
99144   }
99145   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
99146   if( pSelect->pPrior ){
99147     return 0;   /* SELECT may not be a compound query */
99148   }
99149   if( pSelect->selFlags & SF_Distinct ){
99150     return 0;   /* SELECT may not be DISTINCT */
99151   }
99152   pEList = pSelect->pEList;
99153   assert( pEList!=0 );
99154   if( pEList->nExpr!=1 ){
99155     return 0;   /* The result set must have exactly one column */
99156   }
99157   assert( pEList->a[0].pExpr );
99158   if( pEList->a[0].pExpr->op!=TK_ALL ){
99159     return 0;   /* The result set must be the special operator "*" */
99160   }
99161 
99162   /* At this point we have established that the statement is of the
99163   ** correct syntactic form to participate in this optimization.  Now
99164   ** we have to check the semantics.
99165   */
99166   pItem = pSelect->pSrc->a;
99167   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
99168   if( pSrc==0 ){
99169     return 0;   /* FROM clause does not contain a real table */
99170   }
99171   if( pSrc==pDest ){
99172     return 0;   /* tab1 and tab2 may not be the same table */
99173   }
99174   if( HasRowid(pDest)!=HasRowid(pSrc) ){
99175     return 0;   /* source and destination must both be WITHOUT ROWID or not */
99176   }
99177 #ifndef SQLITE_OMIT_VIRTUALTABLE
99178   if( pSrc->tabFlags & TF_Virtual ){
99179     return 0;   /* tab2 must not be a virtual table */
99180   }
99181 #endif
99182   if( pSrc->pSelect ){
99183     return 0;   /* tab2 may not be a view */
99184   }
99185   if( pDest->nCol!=pSrc->nCol ){
99186     return 0;   /* Number of columns must be the same in tab1 and tab2 */
99187   }
99188   if( pDest->iPKey!=pSrc->iPKey ){
99189     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
99190   }
99191   for(i=0; i<pDest->nCol; i++){
99192     Column *pDestCol = &pDest->aCol[i];
99193     Column *pSrcCol = &pSrc->aCol[i];
99194     if( pDestCol->affinity!=pSrcCol->affinity ){
99195       return 0;    /* Affinity must be the same on all columns */
99196     }
99197     if( !xferCompatibleCollation(pDestCol->zColl, pSrcCol->zColl) ){
99198       return 0;    /* Collating sequence must be the same on all columns */
99199     }
99200     if( pDestCol->notNull && !pSrcCol->notNull ){
99201       return 0;    /* tab2 must be NOT NULL if tab1 is */
99202     }
99203     /* Default values for second and subsequent columns need to match. */
99204     if( i>0
99205      && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0)
99206          || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0))
99207     ){
99208       return 0;    /* Default values must be the same for all columns */
99209     }
99210   }
99211   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
99212     if( IsUniqueIndex(pDestIdx) ){
99213       destHasUniqueIdx = 1;
99214     }
99215     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
99216       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
99217     }
99218     if( pSrcIdx==0 ){
99219       return 0;    /* pDestIdx has no corresponding index in pSrc */
99220     }
99221   }
99222 #ifndef SQLITE_OMIT_CHECK
99223   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
99224     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
99225   }
99226 #endif
99227 #ifndef SQLITE_OMIT_FOREIGN_KEY
99228   /* Disallow the transfer optimization if the destination table constains
99229   ** any foreign key constraints.  This is more restrictive than necessary.
99230   ** But the main beneficiary of the transfer optimization is the VACUUM
99231   ** command, and the VACUUM command disables foreign key constraints.  So
99232   ** the extra complication to make this rule less restrictive is probably
99233   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
99234   */
99235   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
99236     return 0;
99237   }
99238 #endif
99239   if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
99240     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
99241   }
99242 
99243   /* If we get this far, it means that the xfer optimization is at
99244   ** least a possibility, though it might only work if the destination
99245   ** table (tab1) is initially empty.
99246   */
99247 #ifdef SQLITE_TEST
99248   sqlite3_xferopt_count++;
99249 #endif
99250   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
99251   v = sqlite3GetVdbe(pParse);
99252   sqlite3CodeVerifySchema(pParse, iDbSrc);
99253   iSrc = pParse->nTab++;
99254   iDest = pParse->nTab++;
99255   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
99256   regData = sqlite3GetTempReg(pParse);
99257   regRowid = sqlite3GetTempReg(pParse);
99258   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
99259   assert( HasRowid(pDest) || destHasUniqueIdx );
99260   if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
99261    || destHasUniqueIdx                              /* (2) */
99262    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
99263   ){
99264     /* In some circumstances, we are able to run the xfer optimization
99265     ** only if the destination table is initially empty.  This code makes
99266     ** that determination.  Conditions under which the destination must
99267     ** be empty:
99268     **
99269     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
99270     **     (If the destination is not initially empty, the rowid fields
99271     **     of index entries might need to change.)
99272     **
99273     ** (2) The destination has a unique index.  (The xfer optimization
99274     **     is unable to test uniqueness.)
99275     **
99276     ** (3) onError is something other than OE_Abort and OE_Rollback.
99277     */
99278     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
99279     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
99280     sqlite3VdbeJumpHere(v, addr1);
99281   }
99282   if( HasRowid(pSrc) ){
99283     sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
99284     emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
99285     if( pDest->iPKey>=0 ){
99286       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
99287       addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
99288       VdbeCoverage(v);
99289       sqlite3RowidConstraint(pParse, onError, pDest);
99290       sqlite3VdbeJumpHere(v, addr2);
99291       autoIncStep(pParse, regAutoinc, regRowid);
99292     }else if( pDest->pIndex==0 ){
99293       addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
99294     }else{
99295       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
99296       assert( (pDest->tabFlags & TF_Autoincrement)==0 );
99297     }
99298     sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
99299     sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
99300     sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
99301     sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
99302     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
99303     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
99304     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
99305   }else{
99306     sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
99307     sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
99308   }
99309   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
99310     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
99311       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
99312     }
99313     assert( pSrcIdx );
99314     sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
99315     sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
99316     VdbeComment((v, "%s", pSrcIdx->zName));
99317     sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
99318     sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
99319     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
99320     VdbeComment((v, "%s", pDestIdx->zName));
99321     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
99322     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
99323     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
99324     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
99325     sqlite3VdbeJumpHere(v, addr1);
99326     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
99327     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
99328   }
99329   if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
99330   sqlite3ReleaseTempReg(pParse, regRowid);
99331   sqlite3ReleaseTempReg(pParse, regData);
99332   if( emptyDestTest ){
99333     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
99334     sqlite3VdbeJumpHere(v, emptyDestTest);
99335     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
99336     return 0;
99337   }else{
99338     return 1;
99339   }
99340 }
99341 #endif /* SQLITE_OMIT_XFER_OPT */
99342 
99343 /************** End of insert.c **********************************************/
99344 /************** Begin file legacy.c ******************************************/
99345 /*
99346 ** 2001 September 15
99347 **
99348 ** The author disclaims copyright to this source code.  In place of
99349 ** a legal notice, here is a blessing:
99350 **
99351 **    May you do good and not evil.
99352 **    May you find forgiveness for yourself and forgive others.
99353 **    May you share freely, never taking more than you give.
99354 **
99355 *************************************************************************
99356 ** Main file for the SQLite library.  The routines in this file
99357 ** implement the programmer interface to the library.  Routines in
99358 ** other files are for internal use by SQLite and should not be
99359 ** accessed by users of the library.
99360 */
99361 
99362 
99363 /*
99364 ** Execute SQL code.  Return one of the SQLITE_ success/failure
99365 ** codes.  Also write an error message into memory obtained from
99366 ** malloc() and make *pzErrMsg point to that message.
99367 **
99368 ** If the SQL is a query, then for each row in the query result
99369 ** the xCallback() function is called.  pArg becomes the first
99370 ** argument to xCallback().  If xCallback=NULL then no callback
99371 ** is invoked, even for queries.
99372 */
99373 SQLITE_API int sqlite3_exec(
99374   sqlite3 *db,                /* The database on which the SQL executes */
99375   const char *zSql,           /* The SQL to be executed */
99376   sqlite3_callback xCallback, /* Invoke this callback routine */
99377   void *pArg,                 /* First argument to xCallback() */
99378   char **pzErrMsg             /* Write error messages here */
99379 ){
99380   int rc = SQLITE_OK;         /* Return code */
99381   const char *zLeftover;      /* Tail of unprocessed SQL */
99382   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
99383   char **azCols = 0;          /* Names of result columns */
99384   int callbackIsInit;         /* True if callback data is initialized */
99385 
99386   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
99387   if( zSql==0 ) zSql = "";
99388 
99389   sqlite3_mutex_enter(db->mutex);
99390   sqlite3Error(db, SQLITE_OK);
99391   while( rc==SQLITE_OK && zSql[0] ){
99392     int nCol;
99393     char **azVals = 0;
99394 
99395     pStmt = 0;
99396     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
99397     assert( rc==SQLITE_OK || pStmt==0 );
99398     if( rc!=SQLITE_OK ){
99399       continue;
99400     }
99401     if( !pStmt ){
99402       /* this happens for a comment or white-space */
99403       zSql = zLeftover;
99404       continue;
99405     }
99406 
99407     callbackIsInit = 0;
99408     nCol = sqlite3_column_count(pStmt);
99409 
99410     while( 1 ){
99411       int i;
99412       rc = sqlite3_step(pStmt);
99413 
99414       /* Invoke the callback function if required */
99415       if( xCallback && (SQLITE_ROW==rc ||
99416           (SQLITE_DONE==rc && !callbackIsInit
99417                            && db->flags&SQLITE_NullCallback)) ){
99418         if( !callbackIsInit ){
99419           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
99420           if( azCols==0 ){
99421             goto exec_out;
99422           }
99423           for(i=0; i<nCol; i++){
99424             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
99425             /* sqlite3VdbeSetColName() installs column names as UTF8
99426             ** strings so there is no way for sqlite3_column_name() to fail. */
99427             assert( azCols[i]!=0 );
99428           }
99429           callbackIsInit = 1;
99430         }
99431         if( rc==SQLITE_ROW ){
99432           azVals = &azCols[nCol];
99433           for(i=0; i<nCol; i++){
99434             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
99435             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
99436               db->mallocFailed = 1;
99437               goto exec_out;
99438             }
99439           }
99440         }
99441         if( xCallback(pArg, nCol, azVals, azCols) ){
99442           /* EVIDENCE-OF: R-38229-40159 If the callback function to
99443           ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
99444           ** return SQLITE_ABORT. */
99445           rc = SQLITE_ABORT;
99446           sqlite3VdbeFinalize((Vdbe *)pStmt);
99447           pStmt = 0;
99448           sqlite3Error(db, SQLITE_ABORT);
99449           goto exec_out;
99450         }
99451       }
99452 
99453       if( rc!=SQLITE_ROW ){
99454         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
99455         pStmt = 0;
99456         zSql = zLeftover;
99457         while( sqlite3Isspace(zSql[0]) ) zSql++;
99458         break;
99459       }
99460     }
99461 
99462     sqlite3DbFree(db, azCols);
99463     azCols = 0;
99464   }
99465 
99466 exec_out:
99467   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
99468   sqlite3DbFree(db, azCols);
99469 
99470   rc = sqlite3ApiExit(db, rc);
99471   if( rc!=SQLITE_OK && pzErrMsg ){
99472     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
99473     *pzErrMsg = sqlite3Malloc(nErrMsg);
99474     if( *pzErrMsg ){
99475       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
99476     }else{
99477       rc = SQLITE_NOMEM;
99478       sqlite3Error(db, SQLITE_NOMEM);
99479     }
99480   }else if( pzErrMsg ){
99481     *pzErrMsg = 0;
99482   }
99483 
99484   assert( (rc&db->errMask)==rc );
99485   sqlite3_mutex_leave(db->mutex);
99486   return rc;
99487 }
99488 
99489 /************** End of legacy.c **********************************************/
99490 /************** Begin file loadext.c *****************************************/
99491 /*
99492 ** 2006 June 7
99493 **
99494 ** The author disclaims copyright to this source code.  In place of
99495 ** a legal notice, here is a blessing:
99496 **
99497 **    May you do good and not evil.
99498 **    May you find forgiveness for yourself and forgive others.
99499 **    May you share freely, never taking more than you give.
99500 **
99501 *************************************************************************
99502 ** This file contains code used to dynamically load extensions into
99503 ** the SQLite library.
99504 */
99505 
99506 #ifndef SQLITE_CORE
99507   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
99508 #endif
99509 /************** Include sqlite3ext.h in the middle of loadext.c **************/
99510 /************** Begin file sqlite3ext.h **************************************/
99511 /*
99512 ** 2006 June 7
99513 **
99514 ** The author disclaims copyright to this source code.  In place of
99515 ** a legal notice, here is a blessing:
99516 **
99517 **    May you do good and not evil.
99518 **    May you find forgiveness for yourself and forgive others.
99519 **    May you share freely, never taking more than you give.
99520 **
99521 *************************************************************************
99522 ** This header file defines the SQLite interface for use by
99523 ** shared libraries that want to be imported as extensions into
99524 ** an SQLite instance.  Shared libraries that intend to be loaded
99525 ** as extensions by SQLite should #include this file instead of
99526 ** sqlite3.h.
99527 */
99528 #ifndef _SQLITE3EXT_H_
99529 #define _SQLITE3EXT_H_
99530 
99531 typedef struct sqlite3_api_routines sqlite3_api_routines;
99532 
99533 /*
99534 ** The following structure holds pointers to all of the SQLite API
99535 ** routines.
99536 **
99537 ** WARNING:  In order to maintain backwards compatibility, add new
99538 ** interfaces to the end of this structure only.  If you insert new
99539 ** interfaces in the middle of this structure, then older different
99540 ** versions of SQLite will not be able to load each other's shared
99541 ** libraries!
99542 */
99543 struct sqlite3_api_routines {
99544   void * (*aggregate_context)(sqlite3_context*,int nBytes);
99545   int  (*aggregate_count)(sqlite3_context*);
99546   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
99547   int  (*bind_double)(sqlite3_stmt*,int,double);
99548   int  (*bind_int)(sqlite3_stmt*,int,int);
99549   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
99550   int  (*bind_null)(sqlite3_stmt*,int);
99551   int  (*bind_parameter_count)(sqlite3_stmt*);
99552   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
99553   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
99554   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
99555   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
99556   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
99557   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
99558   int  (*busy_timeout)(sqlite3*,int ms);
99559   int  (*changes)(sqlite3*);
99560   int  (*close)(sqlite3*);
99561   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
99562                            int eTextRep,const char*));
99563   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
99564                              int eTextRep,const void*));
99565   const void * (*column_blob)(sqlite3_stmt*,int iCol);
99566   int  (*column_bytes)(sqlite3_stmt*,int iCol);
99567   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
99568   int  (*column_count)(sqlite3_stmt*pStmt);
99569   const char * (*column_database_name)(sqlite3_stmt*,int);
99570   const void * (*column_database_name16)(sqlite3_stmt*,int);
99571   const char * (*column_decltype)(sqlite3_stmt*,int i);
99572   const void * (*column_decltype16)(sqlite3_stmt*,int);
99573   double  (*column_double)(sqlite3_stmt*,int iCol);
99574   int  (*column_int)(sqlite3_stmt*,int iCol);
99575   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
99576   const char * (*column_name)(sqlite3_stmt*,int);
99577   const void * (*column_name16)(sqlite3_stmt*,int);
99578   const char * (*column_origin_name)(sqlite3_stmt*,int);
99579   const void * (*column_origin_name16)(sqlite3_stmt*,int);
99580   const char * (*column_table_name)(sqlite3_stmt*,int);
99581   const void * (*column_table_name16)(sqlite3_stmt*,int);
99582   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
99583   const void * (*column_text16)(sqlite3_stmt*,int iCol);
99584   int  (*column_type)(sqlite3_stmt*,int iCol);
99585   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
99586   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
99587   int  (*complete)(const char*sql);
99588   int  (*complete16)(const void*sql);
99589   int  (*create_collation)(sqlite3*,const char*,int,void*,
99590                            int(*)(void*,int,const void*,int,const void*));
99591   int  (*create_collation16)(sqlite3*,const void*,int,void*,
99592                              int(*)(void*,int,const void*,int,const void*));
99593   int  (*create_function)(sqlite3*,const char*,int,int,void*,
99594                           void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
99595                           void (*xStep)(sqlite3_context*,int,sqlite3_value**),
99596                           void (*xFinal)(sqlite3_context*));
99597   int  (*create_function16)(sqlite3*,const void*,int,int,void*,
99598                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
99599                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
99600                             void (*xFinal)(sqlite3_context*));
99601   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
99602   int  (*data_count)(sqlite3_stmt*pStmt);
99603   sqlite3 * (*db_handle)(sqlite3_stmt*);
99604   int (*declare_vtab)(sqlite3*,const char*);
99605   int  (*enable_shared_cache)(int);
99606   int  (*errcode)(sqlite3*db);
99607   const char * (*errmsg)(sqlite3*);
99608   const void * (*errmsg16)(sqlite3*);
99609   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
99610   int  (*expired)(sqlite3_stmt*);
99611   int  (*finalize)(sqlite3_stmt*pStmt);
99612   void  (*free)(void*);
99613   void  (*free_table)(char**result);
99614   int  (*get_autocommit)(sqlite3*);
99615   void * (*get_auxdata)(sqlite3_context*,int);
99616   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
99617   int  (*global_recover)(void);
99618   void  (*interruptx)(sqlite3*);
99619   sqlite_int64  (*last_insert_rowid)(sqlite3*);
99620   const char * (*libversion)(void);
99621   int  (*libversion_number)(void);
99622   void *(*malloc)(int);
99623   char * (*mprintf)(const char*,...);
99624   int  (*open)(const char*,sqlite3**);
99625   int  (*open16)(const void*,sqlite3**);
99626   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
99627   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
99628   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
99629   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
99630   void *(*realloc)(void*,int);
99631   int  (*reset)(sqlite3_stmt*pStmt);
99632   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
99633   void  (*result_double)(sqlite3_context*,double);
99634   void  (*result_error)(sqlite3_context*,const char*,int);
99635   void  (*result_error16)(sqlite3_context*,const void*,int);
99636   void  (*result_int)(sqlite3_context*,int);
99637   void  (*result_int64)(sqlite3_context*,sqlite_int64);
99638   void  (*result_null)(sqlite3_context*);
99639   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
99640   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
99641   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
99642   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
99643   void  (*result_value)(sqlite3_context*,sqlite3_value*);
99644   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
99645   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
99646                          const char*,const char*),void*);
99647   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
99648   char * (*snprintf)(int,char*,const char*,...);
99649   int  (*step)(sqlite3_stmt*);
99650   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
99651                                 char const**,char const**,int*,int*,int*);
99652   void  (*thread_cleanup)(void);
99653   int  (*total_changes)(sqlite3*);
99654   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
99655   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
99656   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
99657                                          sqlite_int64),void*);
99658   void * (*user_data)(sqlite3_context*);
99659   const void * (*value_blob)(sqlite3_value*);
99660   int  (*value_bytes)(sqlite3_value*);
99661   int  (*value_bytes16)(sqlite3_value*);
99662   double  (*value_double)(sqlite3_value*);
99663   int  (*value_int)(sqlite3_value*);
99664   sqlite_int64  (*value_int64)(sqlite3_value*);
99665   int  (*value_numeric_type)(sqlite3_value*);
99666   const unsigned char * (*value_text)(sqlite3_value*);
99667   const void * (*value_text16)(sqlite3_value*);
99668   const void * (*value_text16be)(sqlite3_value*);
99669   const void * (*value_text16le)(sqlite3_value*);
99670   int  (*value_type)(sqlite3_value*);
99671   char *(*vmprintf)(const char*,va_list);
99672   /* Added ??? */
99673   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
99674   /* Added by 3.3.13 */
99675   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
99676   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
99677   int (*clear_bindings)(sqlite3_stmt*);
99678   /* Added by 3.4.1 */
99679   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
99680                           void (*xDestroy)(void *));
99681   /* Added by 3.5.0 */
99682   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
99683   int (*blob_bytes)(sqlite3_blob*);
99684   int (*blob_close)(sqlite3_blob*);
99685   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
99686                    int,sqlite3_blob**);
99687   int (*blob_read)(sqlite3_blob*,void*,int,int);
99688   int (*blob_write)(sqlite3_blob*,const void*,int,int);
99689   int (*create_collation_v2)(sqlite3*,const char*,int,void*,
99690                              int(*)(void*,int,const void*,int,const void*),
99691                              void(*)(void*));
99692   int (*file_control)(sqlite3*,const char*,int,void*);
99693   sqlite3_int64 (*memory_highwater)(int);
99694   sqlite3_int64 (*memory_used)(void);
99695   sqlite3_mutex *(*mutex_alloc)(int);
99696   void (*mutex_enter)(sqlite3_mutex*);
99697   void (*mutex_free)(sqlite3_mutex*);
99698   void (*mutex_leave)(sqlite3_mutex*);
99699   int (*mutex_try)(sqlite3_mutex*);
99700   int (*open_v2)(const char*,sqlite3**,int,const char*);
99701   int (*release_memory)(int);
99702   void (*result_error_nomem)(sqlite3_context*);
99703   void (*result_error_toobig)(sqlite3_context*);
99704   int (*sleep)(int);
99705   void (*soft_heap_limit)(int);
99706   sqlite3_vfs *(*vfs_find)(const char*);
99707   int (*vfs_register)(sqlite3_vfs*,int);
99708   int (*vfs_unregister)(sqlite3_vfs*);
99709   int (*xthreadsafe)(void);
99710   void (*result_zeroblob)(sqlite3_context*,int);
99711   void (*result_error_code)(sqlite3_context*,int);
99712   int (*test_control)(int, ...);
99713   void (*randomness)(int,void*);
99714   sqlite3 *(*context_db_handle)(sqlite3_context*);
99715   int (*extended_result_codes)(sqlite3*,int);
99716   int (*limit)(sqlite3*,int,int);
99717   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
99718   const char *(*sql)(sqlite3_stmt*);
99719   int (*status)(int,int*,int*,int);
99720   int (*backup_finish)(sqlite3_backup*);
99721   sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
99722   int (*backup_pagecount)(sqlite3_backup*);
99723   int (*backup_remaining)(sqlite3_backup*);
99724   int (*backup_step)(sqlite3_backup*,int);
99725   const char *(*compileoption_get)(int);
99726   int (*compileoption_used)(const char*);
99727   int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
99728                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
99729                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
99730                             void (*xFinal)(sqlite3_context*),
99731                             void(*xDestroy)(void*));
99732   int (*db_config)(sqlite3*,int,...);
99733   sqlite3_mutex *(*db_mutex)(sqlite3*);
99734   int (*db_status)(sqlite3*,int,int*,int*,int);
99735   int (*extended_errcode)(sqlite3*);
99736   void (*log)(int,const char*,...);
99737   sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
99738   const char *(*sourceid)(void);
99739   int (*stmt_status)(sqlite3_stmt*,int,int);
99740   int (*strnicmp)(const char*,const char*,int);
99741   int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
99742   int (*wal_autocheckpoint)(sqlite3*,int);
99743   int (*wal_checkpoint)(sqlite3*,const char*);
99744   void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
99745   int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
99746   int (*vtab_config)(sqlite3*,int op,...);
99747   int (*vtab_on_conflict)(sqlite3*);
99748   /* Version 3.7.16 and later */
99749   int (*close_v2)(sqlite3*);
99750   const char *(*db_filename)(sqlite3*,const char*);
99751   int (*db_readonly)(sqlite3*,const char*);
99752   int (*db_release_memory)(sqlite3*);
99753   const char *(*errstr)(int);
99754   int (*stmt_busy)(sqlite3_stmt*);
99755   int (*stmt_readonly)(sqlite3_stmt*);
99756   int (*stricmp)(const char*,const char*);
99757   int (*uri_boolean)(const char*,const char*,int);
99758   sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
99759   const char *(*uri_parameter)(const char*,const char*);
99760   char *(*vsnprintf)(int,char*,const char*,va_list);
99761   int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
99762   /* Version 3.8.7 and later */
99763   int (*auto_extension)(void(*)(void));
99764   int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
99765                      void(*)(void*));
99766   int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
99767                       void(*)(void*),unsigned char);
99768   int (*cancel_auto_extension)(void(*)(void));
99769   int (*load_extension)(sqlite3*,const char*,const char*,char**);
99770   void *(*malloc64)(sqlite3_uint64);
99771   sqlite3_uint64 (*msize)(void*);
99772   void *(*realloc64)(void*,sqlite3_uint64);
99773   void (*reset_auto_extension)(void);
99774   void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
99775                         void(*)(void*));
99776   void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
99777                          void(*)(void*), unsigned char);
99778   int (*strglob)(const char*,const char*);
99779 };
99780 
99781 /*
99782 ** The following macros redefine the API routines so that they are
99783 ** redirected through the global sqlite3_api structure.
99784 **
99785 ** This header file is also used by the loadext.c source file
99786 ** (part of the main SQLite library - not an extension) so that
99787 ** it can get access to the sqlite3_api_routines structure
99788 ** definition.  But the main library does not want to redefine
99789 ** the API.  So the redefinition macros are only valid if the
99790 ** SQLITE_CORE macros is undefined.
99791 */
99792 #ifndef SQLITE_CORE
99793 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
99794 #ifndef SQLITE_OMIT_DEPRECATED
99795 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
99796 #endif
99797 #define sqlite3_bind_blob              sqlite3_api->bind_blob
99798 #define sqlite3_bind_double            sqlite3_api->bind_double
99799 #define sqlite3_bind_int               sqlite3_api->bind_int
99800 #define sqlite3_bind_int64             sqlite3_api->bind_int64
99801 #define sqlite3_bind_null              sqlite3_api->bind_null
99802 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
99803 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
99804 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
99805 #define sqlite3_bind_text              sqlite3_api->bind_text
99806 #define sqlite3_bind_text16            sqlite3_api->bind_text16
99807 #define sqlite3_bind_value             sqlite3_api->bind_value
99808 #define sqlite3_busy_handler           sqlite3_api->busy_handler
99809 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
99810 #define sqlite3_changes                sqlite3_api->changes
99811 #define sqlite3_close                  sqlite3_api->close
99812 #define sqlite3_collation_needed       sqlite3_api->collation_needed
99813 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
99814 #define sqlite3_column_blob            sqlite3_api->column_blob
99815 #define sqlite3_column_bytes           sqlite3_api->column_bytes
99816 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
99817 #define sqlite3_column_count           sqlite3_api->column_count
99818 #define sqlite3_column_database_name   sqlite3_api->column_database_name
99819 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
99820 #define sqlite3_column_decltype        sqlite3_api->column_decltype
99821 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
99822 #define sqlite3_column_double          sqlite3_api->column_double
99823 #define sqlite3_column_int             sqlite3_api->column_int
99824 #define sqlite3_column_int64           sqlite3_api->column_int64
99825 #define sqlite3_column_name            sqlite3_api->column_name
99826 #define sqlite3_column_name16          sqlite3_api->column_name16
99827 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
99828 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
99829 #define sqlite3_column_table_name      sqlite3_api->column_table_name
99830 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
99831 #define sqlite3_column_text            sqlite3_api->column_text
99832 #define sqlite3_column_text16          sqlite3_api->column_text16
99833 #define sqlite3_column_type            sqlite3_api->column_type
99834 #define sqlite3_column_value           sqlite3_api->column_value
99835 #define sqlite3_commit_hook            sqlite3_api->commit_hook
99836 #define sqlite3_complete               sqlite3_api->complete
99837 #define sqlite3_complete16             sqlite3_api->complete16
99838 #define sqlite3_create_collation       sqlite3_api->create_collation
99839 #define sqlite3_create_collation16     sqlite3_api->create_collation16
99840 #define sqlite3_create_function        sqlite3_api->create_function
99841 #define sqlite3_create_function16      sqlite3_api->create_function16
99842 #define sqlite3_create_module          sqlite3_api->create_module
99843 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
99844 #define sqlite3_data_count             sqlite3_api->data_count
99845 #define sqlite3_db_handle              sqlite3_api->db_handle
99846 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
99847 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
99848 #define sqlite3_errcode                sqlite3_api->errcode
99849 #define sqlite3_errmsg                 sqlite3_api->errmsg
99850 #define sqlite3_errmsg16               sqlite3_api->errmsg16
99851 #define sqlite3_exec                   sqlite3_api->exec
99852 #ifndef SQLITE_OMIT_DEPRECATED
99853 #define sqlite3_expired                sqlite3_api->expired
99854 #endif
99855 #define sqlite3_finalize               sqlite3_api->finalize
99856 #define sqlite3_free                   sqlite3_api->free
99857 #define sqlite3_free_table             sqlite3_api->free_table
99858 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
99859 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
99860 #define sqlite3_get_table              sqlite3_api->get_table
99861 #ifndef SQLITE_OMIT_DEPRECATED
99862 #define sqlite3_global_recover         sqlite3_api->global_recover
99863 #endif
99864 #define sqlite3_interrupt              sqlite3_api->interruptx
99865 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
99866 #define sqlite3_libversion             sqlite3_api->libversion
99867 #define sqlite3_libversion_number      sqlite3_api->libversion_number
99868 #define sqlite3_malloc                 sqlite3_api->malloc
99869 #define sqlite3_mprintf                sqlite3_api->mprintf
99870 #define sqlite3_open                   sqlite3_api->open
99871 #define sqlite3_open16                 sqlite3_api->open16
99872 #define sqlite3_prepare                sqlite3_api->prepare
99873 #define sqlite3_prepare16              sqlite3_api->prepare16
99874 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
99875 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
99876 #define sqlite3_profile                sqlite3_api->profile
99877 #define sqlite3_progress_handler       sqlite3_api->progress_handler
99878 #define sqlite3_realloc                sqlite3_api->realloc
99879 #define sqlite3_reset                  sqlite3_api->reset
99880 #define sqlite3_result_blob            sqlite3_api->result_blob
99881 #define sqlite3_result_double          sqlite3_api->result_double
99882 #define sqlite3_result_error           sqlite3_api->result_error
99883 #define sqlite3_result_error16         sqlite3_api->result_error16
99884 #define sqlite3_result_int             sqlite3_api->result_int
99885 #define sqlite3_result_int64           sqlite3_api->result_int64
99886 #define sqlite3_result_null            sqlite3_api->result_null
99887 #define sqlite3_result_text            sqlite3_api->result_text
99888 #define sqlite3_result_text16          sqlite3_api->result_text16
99889 #define sqlite3_result_text16be        sqlite3_api->result_text16be
99890 #define sqlite3_result_text16le        sqlite3_api->result_text16le
99891 #define sqlite3_result_value           sqlite3_api->result_value
99892 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
99893 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
99894 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
99895 #define sqlite3_snprintf               sqlite3_api->snprintf
99896 #define sqlite3_step                   sqlite3_api->step
99897 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
99898 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
99899 #define sqlite3_total_changes          sqlite3_api->total_changes
99900 #define sqlite3_trace                  sqlite3_api->trace
99901 #ifndef SQLITE_OMIT_DEPRECATED
99902 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
99903 #endif
99904 #define sqlite3_update_hook            sqlite3_api->update_hook
99905 #define sqlite3_user_data              sqlite3_api->user_data
99906 #define sqlite3_value_blob             sqlite3_api->value_blob
99907 #define sqlite3_value_bytes            sqlite3_api->value_bytes
99908 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
99909 #define sqlite3_value_double           sqlite3_api->value_double
99910 #define sqlite3_value_int              sqlite3_api->value_int
99911 #define sqlite3_value_int64            sqlite3_api->value_int64
99912 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
99913 #define sqlite3_value_text             sqlite3_api->value_text
99914 #define sqlite3_value_text16           sqlite3_api->value_text16
99915 #define sqlite3_value_text16be         sqlite3_api->value_text16be
99916 #define sqlite3_value_text16le         sqlite3_api->value_text16le
99917 #define sqlite3_value_type             sqlite3_api->value_type
99918 #define sqlite3_vmprintf               sqlite3_api->vmprintf
99919 #define sqlite3_overload_function      sqlite3_api->overload_function
99920 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
99921 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
99922 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
99923 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
99924 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
99925 #define sqlite3_blob_close             sqlite3_api->blob_close
99926 #define sqlite3_blob_open              sqlite3_api->blob_open
99927 #define sqlite3_blob_read              sqlite3_api->blob_read
99928 #define sqlite3_blob_write             sqlite3_api->blob_write
99929 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
99930 #define sqlite3_file_control           sqlite3_api->file_control
99931 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
99932 #define sqlite3_memory_used            sqlite3_api->memory_used
99933 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
99934 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
99935 #define sqlite3_mutex_free             sqlite3_api->mutex_free
99936 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
99937 #define sqlite3_mutex_try              sqlite3_api->mutex_try
99938 #define sqlite3_open_v2                sqlite3_api->open_v2
99939 #define sqlite3_release_memory         sqlite3_api->release_memory
99940 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
99941 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
99942 #define sqlite3_sleep                  sqlite3_api->sleep
99943 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
99944 #define sqlite3_vfs_find               sqlite3_api->vfs_find
99945 #define sqlite3_vfs_register           sqlite3_api->vfs_register
99946 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
99947 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
99948 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
99949 #define sqlite3_result_error_code      sqlite3_api->result_error_code
99950 #define sqlite3_test_control           sqlite3_api->test_control
99951 #define sqlite3_randomness             sqlite3_api->randomness
99952 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
99953 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
99954 #define sqlite3_limit                  sqlite3_api->limit
99955 #define sqlite3_next_stmt              sqlite3_api->next_stmt
99956 #define sqlite3_sql                    sqlite3_api->sql
99957 #define sqlite3_status                 sqlite3_api->status
99958 #define sqlite3_backup_finish          sqlite3_api->backup_finish
99959 #define sqlite3_backup_init            sqlite3_api->backup_init
99960 #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
99961 #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
99962 #define sqlite3_backup_step            sqlite3_api->backup_step
99963 #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
99964 #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
99965 #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
99966 #define sqlite3_db_config              sqlite3_api->db_config
99967 #define sqlite3_db_mutex               sqlite3_api->db_mutex
99968 #define sqlite3_db_status              sqlite3_api->db_status
99969 #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
99970 #define sqlite3_log                    sqlite3_api->log
99971 #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
99972 #define sqlite3_sourceid               sqlite3_api->sourceid
99973 #define sqlite3_stmt_status            sqlite3_api->stmt_status
99974 #define sqlite3_strnicmp               sqlite3_api->strnicmp
99975 #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
99976 #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
99977 #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
99978 #define sqlite3_wal_hook               sqlite3_api->wal_hook
99979 #define sqlite3_blob_reopen            sqlite3_api->blob_reopen
99980 #define sqlite3_vtab_config            sqlite3_api->vtab_config
99981 #define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
99982 /* Version 3.7.16 and later */
99983 #define sqlite3_close_v2               sqlite3_api->close_v2
99984 #define sqlite3_db_filename            sqlite3_api->db_filename
99985 #define sqlite3_db_readonly            sqlite3_api->db_readonly
99986 #define sqlite3_db_release_memory      sqlite3_api->db_release_memory
99987 #define sqlite3_errstr                 sqlite3_api->errstr
99988 #define sqlite3_stmt_busy              sqlite3_api->stmt_busy
99989 #define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
99990 #define sqlite3_stricmp                sqlite3_api->stricmp
99991 #define sqlite3_uri_boolean            sqlite3_api->uri_boolean
99992 #define sqlite3_uri_int64              sqlite3_api->uri_int64
99993 #define sqlite3_uri_parameter          sqlite3_api->uri_parameter
99994 #define sqlite3_uri_vsnprintf          sqlite3_api->vsnprintf
99995 #define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
99996 /* Version 3.8.7 and later */
99997 #define sqlite3_auto_extension         sqlite3_api->auto_extension
99998 #define sqlite3_bind_blob64            sqlite3_api->bind_blob64
99999 #define sqlite3_bind_text64            sqlite3_api->bind_text64
100000 #define sqlite3_cancel_auto_extension  sqlite3_api->cancel_auto_extension
100001 #define sqlite3_load_extension         sqlite3_api->load_extension
100002 #define sqlite3_malloc64               sqlite3_api->malloc64
100003 #define sqlite3_msize                  sqlite3_api->msize
100004 #define sqlite3_realloc64              sqlite3_api->realloc64
100005 #define sqlite3_reset_auto_extension   sqlite3_api->reset_auto_extension
100006 #define sqlite3_result_blob64          sqlite3_api->result_blob64
100007 #define sqlite3_result_text64          sqlite3_api->result_text64
100008 #define sqlite3_strglob                sqlite3_api->strglob
100009 #endif /* SQLITE_CORE */
100010 
100011 #ifndef SQLITE_CORE
100012   /* This case when the file really is being compiled as a loadable
100013   ** extension */
100014 # define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
100015 # define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
100016 # define SQLITE_EXTENSION_INIT3     \
100017     extern const sqlite3_api_routines *sqlite3_api;
100018 #else
100019   /* This case when the file is being statically linked into the
100020   ** application */
100021 # define SQLITE_EXTENSION_INIT1     /*no-op*/
100022 # define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
100023 # define SQLITE_EXTENSION_INIT3     /*no-op*/
100024 #endif
100025 
100026 #endif /* _SQLITE3EXT_H_ */
100027 
100028 /************** End of sqlite3ext.h ******************************************/
100029 /************** Continuing where we left off in loadext.c ********************/
100030 /* #include <string.h> */
100031 
100032 #ifndef SQLITE_OMIT_LOAD_EXTENSION
100033 
100034 /*
100035 ** Some API routines are omitted when various features are
100036 ** excluded from a build of SQLite.  Substitute a NULL pointer
100037 ** for any missing APIs.
100038 */
100039 #ifndef SQLITE_ENABLE_COLUMN_METADATA
100040 # define sqlite3_column_database_name   0
100041 # define sqlite3_column_database_name16 0
100042 # define sqlite3_column_table_name      0
100043 # define sqlite3_column_table_name16    0
100044 # define sqlite3_column_origin_name     0
100045 # define sqlite3_column_origin_name16   0
100046 # define sqlite3_table_column_metadata  0
100047 #endif
100048 
100049 #ifdef SQLITE_OMIT_AUTHORIZATION
100050 # define sqlite3_set_authorizer         0
100051 #endif
100052 
100053 #ifdef SQLITE_OMIT_UTF16
100054 # define sqlite3_bind_text16            0
100055 # define sqlite3_collation_needed16     0
100056 # define sqlite3_column_decltype16      0
100057 # define sqlite3_column_name16          0
100058 # define sqlite3_column_text16          0
100059 # define sqlite3_complete16             0
100060 # define sqlite3_create_collation16     0
100061 # define sqlite3_create_function16      0
100062 # define sqlite3_errmsg16               0
100063 # define sqlite3_open16                 0
100064 # define sqlite3_prepare16              0
100065 # define sqlite3_prepare16_v2           0
100066 # define sqlite3_result_error16         0
100067 # define sqlite3_result_text16          0
100068 # define sqlite3_result_text16be        0
100069 # define sqlite3_result_text16le        0
100070 # define sqlite3_value_text16           0
100071 # define sqlite3_value_text16be         0
100072 # define sqlite3_value_text16le         0
100073 # define sqlite3_column_database_name16 0
100074 # define sqlite3_column_table_name16    0
100075 # define sqlite3_column_origin_name16   0
100076 #endif
100077 
100078 #ifdef SQLITE_OMIT_COMPLETE
100079 # define sqlite3_complete 0
100080 # define sqlite3_complete16 0
100081 #endif
100082 
100083 #ifdef SQLITE_OMIT_DECLTYPE
100084 # define sqlite3_column_decltype16      0
100085 # define sqlite3_column_decltype        0
100086 #endif
100087 
100088 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
100089 # define sqlite3_progress_handler 0
100090 #endif
100091 
100092 #ifdef SQLITE_OMIT_VIRTUALTABLE
100093 # define sqlite3_create_module 0
100094 # define sqlite3_create_module_v2 0
100095 # define sqlite3_declare_vtab 0
100096 # define sqlite3_vtab_config 0
100097 # define sqlite3_vtab_on_conflict 0
100098 #endif
100099 
100100 #ifdef SQLITE_OMIT_SHARED_CACHE
100101 # define sqlite3_enable_shared_cache 0
100102 #endif
100103 
100104 #ifdef SQLITE_OMIT_TRACE
100105 # define sqlite3_profile       0
100106 # define sqlite3_trace         0
100107 #endif
100108 
100109 #ifdef SQLITE_OMIT_GET_TABLE
100110 # define sqlite3_free_table    0
100111 # define sqlite3_get_table     0
100112 #endif
100113 
100114 #ifdef SQLITE_OMIT_INCRBLOB
100115 #define sqlite3_bind_zeroblob  0
100116 #define sqlite3_blob_bytes     0
100117 #define sqlite3_blob_close     0
100118 #define sqlite3_blob_open      0
100119 #define sqlite3_blob_read      0
100120 #define sqlite3_blob_write     0
100121 #define sqlite3_blob_reopen    0
100122 #endif
100123 
100124 /*
100125 ** The following structure contains pointers to all SQLite API routines.
100126 ** A pointer to this structure is passed into extensions when they are
100127 ** loaded so that the extension can make calls back into the SQLite
100128 ** library.
100129 **
100130 ** When adding new APIs, add them to the bottom of this structure
100131 ** in order to preserve backwards compatibility.
100132 **
100133 ** Extensions that use newer APIs should first call the
100134 ** sqlite3_libversion_number() to make sure that the API they
100135 ** intend to use is supported by the library.  Extensions should
100136 ** also check to make sure that the pointer to the function is
100137 ** not NULL before calling it.
100138 */
100139 static const sqlite3_api_routines sqlite3Apis = {
100140   sqlite3_aggregate_context,
100141 #ifndef SQLITE_OMIT_DEPRECATED
100142   sqlite3_aggregate_count,
100143 #else
100144   0,
100145 #endif
100146   sqlite3_bind_blob,
100147   sqlite3_bind_double,
100148   sqlite3_bind_int,
100149   sqlite3_bind_int64,
100150   sqlite3_bind_null,
100151   sqlite3_bind_parameter_count,
100152   sqlite3_bind_parameter_index,
100153   sqlite3_bind_parameter_name,
100154   sqlite3_bind_text,
100155   sqlite3_bind_text16,
100156   sqlite3_bind_value,
100157   sqlite3_busy_handler,
100158   sqlite3_busy_timeout,
100159   sqlite3_changes,
100160   sqlite3_close,
100161   sqlite3_collation_needed,
100162   sqlite3_collation_needed16,
100163   sqlite3_column_blob,
100164   sqlite3_column_bytes,
100165   sqlite3_column_bytes16,
100166   sqlite3_column_count,
100167   sqlite3_column_database_name,
100168   sqlite3_column_database_name16,
100169   sqlite3_column_decltype,
100170   sqlite3_column_decltype16,
100171   sqlite3_column_double,
100172   sqlite3_column_int,
100173   sqlite3_column_int64,
100174   sqlite3_column_name,
100175   sqlite3_column_name16,
100176   sqlite3_column_origin_name,
100177   sqlite3_column_origin_name16,
100178   sqlite3_column_table_name,
100179   sqlite3_column_table_name16,
100180   sqlite3_column_text,
100181   sqlite3_column_text16,
100182   sqlite3_column_type,
100183   sqlite3_column_value,
100184   sqlite3_commit_hook,
100185   sqlite3_complete,
100186   sqlite3_complete16,
100187   sqlite3_create_collation,
100188   sqlite3_create_collation16,
100189   sqlite3_create_function,
100190   sqlite3_create_function16,
100191   sqlite3_create_module,
100192   sqlite3_data_count,
100193   sqlite3_db_handle,
100194   sqlite3_declare_vtab,
100195   sqlite3_enable_shared_cache,
100196   sqlite3_errcode,
100197   sqlite3_errmsg,
100198   sqlite3_errmsg16,
100199   sqlite3_exec,
100200 #ifndef SQLITE_OMIT_DEPRECATED
100201   sqlite3_expired,
100202 #else
100203   0,
100204 #endif
100205   sqlite3_finalize,
100206   sqlite3_free,
100207   sqlite3_free_table,
100208   sqlite3_get_autocommit,
100209   sqlite3_get_auxdata,
100210   sqlite3_get_table,
100211   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
100212   sqlite3_interrupt,
100213   sqlite3_last_insert_rowid,
100214   sqlite3_libversion,
100215   sqlite3_libversion_number,
100216   sqlite3_malloc,
100217   sqlite3_mprintf,
100218   sqlite3_open,
100219   sqlite3_open16,
100220   sqlite3_prepare,
100221   sqlite3_prepare16,
100222   sqlite3_profile,
100223   sqlite3_progress_handler,
100224   sqlite3_realloc,
100225   sqlite3_reset,
100226   sqlite3_result_blob,
100227   sqlite3_result_double,
100228   sqlite3_result_error,
100229   sqlite3_result_error16,
100230   sqlite3_result_int,
100231   sqlite3_result_int64,
100232   sqlite3_result_null,
100233   sqlite3_result_text,
100234   sqlite3_result_text16,
100235   sqlite3_result_text16be,
100236   sqlite3_result_text16le,
100237   sqlite3_result_value,
100238   sqlite3_rollback_hook,
100239   sqlite3_set_authorizer,
100240   sqlite3_set_auxdata,
100241   sqlite3_snprintf,
100242   sqlite3_step,
100243   sqlite3_table_column_metadata,
100244 #ifndef SQLITE_OMIT_DEPRECATED
100245   sqlite3_thread_cleanup,
100246 #else
100247   0,
100248 #endif
100249   sqlite3_total_changes,
100250   sqlite3_trace,
100251 #ifndef SQLITE_OMIT_DEPRECATED
100252   sqlite3_transfer_bindings,
100253 #else
100254   0,
100255 #endif
100256   sqlite3_update_hook,
100257   sqlite3_user_data,
100258   sqlite3_value_blob,
100259   sqlite3_value_bytes,
100260   sqlite3_value_bytes16,
100261   sqlite3_value_double,
100262   sqlite3_value_int,
100263   sqlite3_value_int64,
100264   sqlite3_value_numeric_type,
100265   sqlite3_value_text,
100266   sqlite3_value_text16,
100267   sqlite3_value_text16be,
100268   sqlite3_value_text16le,
100269   sqlite3_value_type,
100270   sqlite3_vmprintf,
100271   /*
100272   ** The original API set ends here.  All extensions can call any
100273   ** of the APIs above provided that the pointer is not NULL.  But
100274   ** before calling APIs that follow, extension should check the
100275   ** sqlite3_libversion_number() to make sure they are dealing with
100276   ** a library that is new enough to support that API.
100277   *************************************************************************
100278   */
100279   sqlite3_overload_function,
100280 
100281   /*
100282   ** Added after 3.3.13
100283   */
100284   sqlite3_prepare_v2,
100285   sqlite3_prepare16_v2,
100286   sqlite3_clear_bindings,
100287 
100288   /*
100289   ** Added for 3.4.1
100290   */
100291   sqlite3_create_module_v2,
100292 
100293   /*
100294   ** Added for 3.5.0
100295   */
100296   sqlite3_bind_zeroblob,
100297   sqlite3_blob_bytes,
100298   sqlite3_blob_close,
100299   sqlite3_blob_open,
100300   sqlite3_blob_read,
100301   sqlite3_blob_write,
100302   sqlite3_create_collation_v2,
100303   sqlite3_file_control,
100304   sqlite3_memory_highwater,
100305   sqlite3_memory_used,
100306 #ifdef SQLITE_MUTEX_OMIT
100307   0,
100308   0,
100309   0,
100310   0,
100311   0,
100312 #else
100313   sqlite3_mutex_alloc,
100314   sqlite3_mutex_enter,
100315   sqlite3_mutex_free,
100316   sqlite3_mutex_leave,
100317   sqlite3_mutex_try,
100318 #endif
100319   sqlite3_open_v2,
100320   sqlite3_release_memory,
100321   sqlite3_result_error_nomem,
100322   sqlite3_result_error_toobig,
100323   sqlite3_sleep,
100324   sqlite3_soft_heap_limit,
100325   sqlite3_vfs_find,
100326   sqlite3_vfs_register,
100327   sqlite3_vfs_unregister,
100328 
100329   /*
100330   ** Added for 3.5.8
100331   */
100332   sqlite3_threadsafe,
100333   sqlite3_result_zeroblob,
100334   sqlite3_result_error_code,
100335   sqlite3_test_control,
100336   sqlite3_randomness,
100337   sqlite3_context_db_handle,
100338 
100339   /*
100340   ** Added for 3.6.0
100341   */
100342   sqlite3_extended_result_codes,
100343   sqlite3_limit,
100344   sqlite3_next_stmt,
100345   sqlite3_sql,
100346   sqlite3_status,
100347 
100348   /*
100349   ** Added for 3.7.4
100350   */
100351   sqlite3_backup_finish,
100352   sqlite3_backup_init,
100353   sqlite3_backup_pagecount,
100354   sqlite3_backup_remaining,
100355   sqlite3_backup_step,
100356 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
100357   sqlite3_compileoption_get,
100358   sqlite3_compileoption_used,
100359 #else
100360   0,
100361   0,
100362 #endif
100363   sqlite3_create_function_v2,
100364   sqlite3_db_config,
100365   sqlite3_db_mutex,
100366   sqlite3_db_status,
100367   sqlite3_extended_errcode,
100368   sqlite3_log,
100369   sqlite3_soft_heap_limit64,
100370   sqlite3_sourceid,
100371   sqlite3_stmt_status,
100372   sqlite3_strnicmp,
100373 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
100374   sqlite3_unlock_notify,
100375 #else
100376   0,
100377 #endif
100378 #ifndef SQLITE_OMIT_WAL
100379   sqlite3_wal_autocheckpoint,
100380   sqlite3_wal_checkpoint,
100381   sqlite3_wal_hook,
100382 #else
100383   0,
100384   0,
100385   0,
100386 #endif
100387   sqlite3_blob_reopen,
100388   sqlite3_vtab_config,
100389   sqlite3_vtab_on_conflict,
100390   sqlite3_close_v2,
100391   sqlite3_db_filename,
100392   sqlite3_db_readonly,
100393   sqlite3_db_release_memory,
100394   sqlite3_errstr,
100395   sqlite3_stmt_busy,
100396   sqlite3_stmt_readonly,
100397   sqlite3_stricmp,
100398   sqlite3_uri_boolean,
100399   sqlite3_uri_int64,
100400   sqlite3_uri_parameter,
100401   sqlite3_vsnprintf,
100402   sqlite3_wal_checkpoint_v2,
100403   /* Version 3.8.7 and later */
100404   sqlite3_auto_extension,
100405   sqlite3_bind_blob64,
100406   sqlite3_bind_text64,
100407   sqlite3_cancel_auto_extension,
100408   sqlite3_load_extension,
100409   sqlite3_malloc64,
100410   sqlite3_msize,
100411   sqlite3_realloc64,
100412   sqlite3_reset_auto_extension,
100413   sqlite3_result_blob64,
100414   sqlite3_result_text64,
100415   sqlite3_strglob
100416 };
100417 
100418 /*
100419 ** Attempt to load an SQLite extension library contained in the file
100420 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
100421 ** default entry point name (sqlite3_extension_init) is used.  Use
100422 ** of the default name is recommended.
100423 **
100424 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
100425 **
100426 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
100427 ** error message text.  The calling function should free this memory
100428 ** by calling sqlite3DbFree(db, ).
100429 */
100430 static int sqlite3LoadExtension(
100431   sqlite3 *db,          /* Load the extension into this database connection */
100432   const char *zFile,    /* Name of the shared library containing extension */
100433   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
100434   char **pzErrMsg       /* Put error message here if not 0 */
100435 ){
100436   sqlite3_vfs *pVfs = db->pVfs;
100437   void *handle;
100438   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
100439   char *zErrmsg = 0;
100440   const char *zEntry;
100441   char *zAltEntry = 0;
100442   void **aHandle;
100443   int nMsg = 300 + sqlite3Strlen30(zFile);
100444   int ii;
100445 
100446   /* Shared library endings to try if zFile cannot be loaded as written */
100447   static const char *azEndings[] = {
100448 #if SQLITE_OS_WIN
100449      "dll"
100450 #elif defined(__APPLE__)
100451      "dylib"
100452 #else
100453      "so"
100454 #endif
100455   };
100456 
100457 
100458   if( pzErrMsg ) *pzErrMsg = 0;
100459 
100460   /* Ticket #1863.  To avoid a creating security problems for older
100461   ** applications that relink against newer versions of SQLite, the
100462   ** ability to run load_extension is turned off by default.  One
100463   ** must call sqlite3_enable_load_extension() to turn on extension
100464   ** loading.  Otherwise you get the following error.
100465   */
100466   if( (db->flags & SQLITE_LoadExtension)==0 ){
100467     if( pzErrMsg ){
100468       *pzErrMsg = sqlite3_mprintf("not authorized");
100469     }
100470     return SQLITE_ERROR;
100471   }
100472 
100473   zEntry = zProc ? zProc : "sqlite3_extension_init";
100474 
100475   handle = sqlite3OsDlOpen(pVfs, zFile);
100476 #if SQLITE_OS_UNIX || SQLITE_OS_WIN
100477   for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
100478     char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
100479     if( zAltFile==0 ) return SQLITE_NOMEM;
100480     handle = sqlite3OsDlOpen(pVfs, zAltFile);
100481     sqlite3_free(zAltFile);
100482   }
100483 #endif
100484   if( handle==0 ){
100485     if( pzErrMsg ){
100486       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
100487       if( zErrmsg ){
100488         sqlite3_snprintf(nMsg, zErrmsg,
100489             "unable to open shared library [%s]", zFile);
100490         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
100491       }
100492     }
100493     return SQLITE_ERROR;
100494   }
100495   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
100496                    sqlite3OsDlSym(pVfs, handle, zEntry);
100497 
100498   /* If no entry point was specified and the default legacy
100499   ** entry point name "sqlite3_extension_init" was not found, then
100500   ** construct an entry point name "sqlite3_X_init" where the X is
100501   ** replaced by the lowercase value of every ASCII alphabetic
100502   ** character in the filename after the last "/" upto the first ".",
100503   ** and eliding the first three characters if they are "lib".
100504   ** Examples:
100505   **
100506   **    /usr/local/lib/libExample5.4.3.so ==>  sqlite3_example_init
100507   **    C:/lib/mathfuncs.dll              ==>  sqlite3_mathfuncs_init
100508   */
100509   if( xInit==0 && zProc==0 ){
100510     int iFile, iEntry, c;
100511     int ncFile = sqlite3Strlen30(zFile);
100512     zAltEntry = sqlite3_malloc(ncFile+30);
100513     if( zAltEntry==0 ){
100514       sqlite3OsDlClose(pVfs, handle);
100515       return SQLITE_NOMEM;
100516     }
100517     memcpy(zAltEntry, "sqlite3_", 8);
100518     for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
100519     iFile++;
100520     if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
100521     for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
100522       if( sqlite3Isalpha(c) ){
100523         zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
100524       }
100525     }
100526     memcpy(zAltEntry+iEntry, "_init", 6);
100527     zEntry = zAltEntry;
100528     xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
100529                      sqlite3OsDlSym(pVfs, handle, zEntry);
100530   }
100531   if( xInit==0 ){
100532     if( pzErrMsg ){
100533       nMsg += sqlite3Strlen30(zEntry);
100534       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
100535       if( zErrmsg ){
100536         sqlite3_snprintf(nMsg, zErrmsg,
100537             "no entry point [%s] in shared library [%s]", zEntry, zFile);
100538         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
100539       }
100540     }
100541     sqlite3OsDlClose(pVfs, handle);
100542     sqlite3_free(zAltEntry);
100543     return SQLITE_ERROR;
100544   }
100545   sqlite3_free(zAltEntry);
100546   if( xInit(db, &zErrmsg, &sqlite3Apis) ){
100547     if( pzErrMsg ){
100548       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
100549     }
100550     sqlite3_free(zErrmsg);
100551     sqlite3OsDlClose(pVfs, handle);
100552     return SQLITE_ERROR;
100553   }
100554 
100555   /* Append the new shared library handle to the db->aExtension array. */
100556   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
100557   if( aHandle==0 ){
100558     return SQLITE_NOMEM;
100559   }
100560   if( db->nExtension>0 ){
100561     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
100562   }
100563   sqlite3DbFree(db, db->aExtension);
100564   db->aExtension = aHandle;
100565 
100566   db->aExtension[db->nExtension++] = handle;
100567   return SQLITE_OK;
100568 }
100569 SQLITE_API int sqlite3_load_extension(
100570   sqlite3 *db,          /* Load the extension into this database connection */
100571   const char *zFile,    /* Name of the shared library containing extension */
100572   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
100573   char **pzErrMsg       /* Put error message here if not 0 */
100574 ){
100575   int rc;
100576   sqlite3_mutex_enter(db->mutex);
100577   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
100578   rc = sqlite3ApiExit(db, rc);
100579   sqlite3_mutex_leave(db->mutex);
100580   return rc;
100581 }
100582 
100583 /*
100584 ** Call this routine when the database connection is closing in order
100585 ** to clean up loaded extensions
100586 */
100587 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
100588   int i;
100589   assert( sqlite3_mutex_held(db->mutex) );
100590   for(i=0; i<db->nExtension; i++){
100591     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
100592   }
100593   sqlite3DbFree(db, db->aExtension);
100594 }
100595 
100596 /*
100597 ** Enable or disable extension loading.  Extension loading is disabled by
100598 ** default so as not to open security holes in older applications.
100599 */
100600 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
100601   sqlite3_mutex_enter(db->mutex);
100602   if( onoff ){
100603     db->flags |= SQLITE_LoadExtension;
100604   }else{
100605     db->flags &= ~SQLITE_LoadExtension;
100606   }
100607   sqlite3_mutex_leave(db->mutex);
100608   return SQLITE_OK;
100609 }
100610 
100611 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
100612 
100613 /*
100614 ** The auto-extension code added regardless of whether or not extension
100615 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
100616 ** code if regular extension loading is not available.  This is that
100617 ** dummy pointer.
100618 */
100619 #ifdef SQLITE_OMIT_LOAD_EXTENSION
100620 static const sqlite3_api_routines sqlite3Apis = { 0 };
100621 #endif
100622 
100623 
100624 /*
100625 ** The following object holds the list of automatically loaded
100626 ** extensions.
100627 **
100628 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
100629 ** mutex must be held while accessing this list.
100630 */
100631 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
100632 static SQLITE_WSD struct sqlite3AutoExtList {
100633   int nExt;              /* Number of entries in aExt[] */
100634   void (**aExt)(void);   /* Pointers to the extension init functions */
100635 } sqlite3Autoext = { 0, 0 };
100636 
100637 /* The "wsdAutoext" macro will resolve to the autoextension
100638 ** state vector.  If writable static data is unsupported on the target,
100639 ** we have to locate the state vector at run-time.  In the more common
100640 ** case where writable static data is supported, wsdStat can refer directly
100641 ** to the "sqlite3Autoext" state vector declared above.
100642 */
100643 #ifdef SQLITE_OMIT_WSD
100644 # define wsdAutoextInit \
100645   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
100646 # define wsdAutoext x[0]
100647 #else
100648 # define wsdAutoextInit
100649 # define wsdAutoext sqlite3Autoext
100650 #endif
100651 
100652 
100653 /*
100654 ** Register a statically linked extension that is automatically
100655 ** loaded by every new database connection.
100656 */
100657 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
100658   int rc = SQLITE_OK;
100659 #ifndef SQLITE_OMIT_AUTOINIT
100660   rc = sqlite3_initialize();
100661   if( rc ){
100662     return rc;
100663   }else
100664 #endif
100665   {
100666     int i;
100667 #if SQLITE_THREADSAFE
100668     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
100669 #endif
100670     wsdAutoextInit;
100671     sqlite3_mutex_enter(mutex);
100672     for(i=0; i<wsdAutoext.nExt; i++){
100673       if( wsdAutoext.aExt[i]==xInit ) break;
100674     }
100675     if( i==wsdAutoext.nExt ){
100676       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
100677       void (**aNew)(void);
100678       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
100679       if( aNew==0 ){
100680         rc = SQLITE_NOMEM;
100681       }else{
100682         wsdAutoext.aExt = aNew;
100683         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
100684         wsdAutoext.nExt++;
100685       }
100686     }
100687     sqlite3_mutex_leave(mutex);
100688     assert( (rc&0xff)==rc );
100689     return rc;
100690   }
100691 }
100692 
100693 /*
100694 ** Cancel a prior call to sqlite3_auto_extension.  Remove xInit from the
100695 ** set of routines that is invoked for each new database connection, if it
100696 ** is currently on the list.  If xInit is not on the list, then this
100697 ** routine is a no-op.
100698 **
100699 ** Return 1 if xInit was found on the list and removed.  Return 0 if xInit
100700 ** was not on the list.
100701 */
100702 SQLITE_API int sqlite3_cancel_auto_extension(void (*xInit)(void)){
100703 #if SQLITE_THREADSAFE
100704   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
100705 #endif
100706   int i;
100707   int n = 0;
100708   wsdAutoextInit;
100709   sqlite3_mutex_enter(mutex);
100710   for(i=wsdAutoext.nExt-1; i>=0; i--){
100711     if( wsdAutoext.aExt[i]==xInit ){
100712       wsdAutoext.nExt--;
100713       wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
100714       n++;
100715       break;
100716     }
100717   }
100718   sqlite3_mutex_leave(mutex);
100719   return n;
100720 }
100721 
100722 /*
100723 ** Reset the automatic extension loading mechanism.
100724 */
100725 SQLITE_API void sqlite3_reset_auto_extension(void){
100726 #ifndef SQLITE_OMIT_AUTOINIT
100727   if( sqlite3_initialize()==SQLITE_OK )
100728 #endif
100729   {
100730 #if SQLITE_THREADSAFE
100731     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
100732 #endif
100733     wsdAutoextInit;
100734     sqlite3_mutex_enter(mutex);
100735     sqlite3_free(wsdAutoext.aExt);
100736     wsdAutoext.aExt = 0;
100737     wsdAutoext.nExt = 0;
100738     sqlite3_mutex_leave(mutex);
100739   }
100740 }
100741 
100742 /*
100743 ** Load all automatic extensions.
100744 **
100745 ** If anything goes wrong, set an error in the database connection.
100746 */
100747 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
100748   int i;
100749   int go = 1;
100750   int rc;
100751   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
100752 
100753   wsdAutoextInit;
100754   if( wsdAutoext.nExt==0 ){
100755     /* Common case: early out without every having to acquire a mutex */
100756     return;
100757   }
100758   for(i=0; go; i++){
100759     char *zErrmsg;
100760 #if SQLITE_THREADSAFE
100761     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
100762 #endif
100763     sqlite3_mutex_enter(mutex);
100764     if( i>=wsdAutoext.nExt ){
100765       xInit = 0;
100766       go = 0;
100767     }else{
100768       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
100769               wsdAutoext.aExt[i];
100770     }
100771     sqlite3_mutex_leave(mutex);
100772     zErrmsg = 0;
100773     if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
100774       sqlite3ErrorWithMsg(db, rc,
100775             "automatic extension loading failed: %s", zErrmsg);
100776       go = 0;
100777     }
100778     sqlite3_free(zErrmsg);
100779   }
100780 }
100781 
100782 /************** End of loadext.c *********************************************/
100783 /************** Begin file pragma.c ******************************************/
100784 /*
100785 ** 2003 April 6
100786 **
100787 ** The author disclaims copyright to this source code.  In place of
100788 ** a legal notice, here is a blessing:
100789 **
100790 **    May you do good and not evil.
100791 **    May you find forgiveness for yourself and forgive others.
100792 **    May you share freely, never taking more than you give.
100793 **
100794 *************************************************************************
100795 ** This file contains code used to implement the PRAGMA command.
100796 */
100797 
100798 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
100799 #  if defined(__APPLE__)
100800 #    define SQLITE_ENABLE_LOCKING_STYLE 1
100801 #  else
100802 #    define SQLITE_ENABLE_LOCKING_STYLE 0
100803 #  endif
100804 #endif
100805 
100806 /***************************************************************************
100807 ** The next block of code, including the PragTyp_XXXX macro definitions and
100808 ** the aPragmaName[] object is composed of generated code. DO NOT EDIT.
100809 **
100810 ** To add new pragmas, edit the code in ../tool/mkpragmatab.tcl and rerun
100811 ** that script.  Then copy/paste the output in place of the following:
100812 */
100813 #define PragTyp_HEADER_VALUE                   0
100814 #define PragTyp_AUTO_VACUUM                    1
100815 #define PragTyp_FLAG                           2
100816 #define PragTyp_BUSY_TIMEOUT                   3
100817 #define PragTyp_CACHE_SIZE                     4
100818 #define PragTyp_CASE_SENSITIVE_LIKE            5
100819 #define PragTyp_COLLATION_LIST                 6
100820 #define PragTyp_COMPILE_OPTIONS                7
100821 #define PragTyp_DATA_STORE_DIRECTORY           8
100822 #define PragTyp_DATABASE_LIST                  9
100823 #define PragTyp_DEFAULT_CACHE_SIZE            10
100824 #define PragTyp_ENCODING                      11
100825 #define PragTyp_FOREIGN_KEY_CHECK             12
100826 #define PragTyp_FOREIGN_KEY_LIST              13
100827 #define PragTyp_INCREMENTAL_VACUUM            14
100828 #define PragTyp_INDEX_INFO                    15
100829 #define PragTyp_INDEX_LIST                    16
100830 #define PragTyp_INTEGRITY_CHECK               17
100831 #define PragTyp_JOURNAL_MODE                  18
100832 #define PragTyp_JOURNAL_SIZE_LIMIT            19
100833 #define PragTyp_LOCK_PROXY_FILE               20
100834 #define PragTyp_LOCKING_MODE                  21
100835 #define PragTyp_PAGE_COUNT                    22
100836 #define PragTyp_MMAP_SIZE                     23
100837 #define PragTyp_PAGE_SIZE                     24
100838 #define PragTyp_SECURE_DELETE                 25
100839 #define PragTyp_SHRINK_MEMORY                 26
100840 #define PragTyp_SOFT_HEAP_LIMIT               27
100841 #define PragTyp_STATS                         28
100842 #define PragTyp_SYNCHRONOUS                   29
100843 #define PragTyp_TABLE_INFO                    30
100844 #define PragTyp_TEMP_STORE                    31
100845 #define PragTyp_TEMP_STORE_DIRECTORY          32
100846 #define PragTyp_THREADS                       33
100847 #define PragTyp_WAL_AUTOCHECKPOINT            34
100848 #define PragTyp_WAL_CHECKPOINT                35
100849 #define PragTyp_ACTIVATE_EXTENSIONS           36
100850 #define PragTyp_HEXKEY                        37
100851 #define PragTyp_KEY                           38
100852 #define PragTyp_REKEY                         39
100853 #define PragTyp_LOCK_STATUS                   40
100854 #define PragTyp_PARSER_TRACE                  41
100855 #define PragFlag_NeedSchema           0x01
100856 static const struct sPragmaNames {
100857   const char *const zName;  /* Name of pragma */
100858   u8 ePragTyp;              /* PragTyp_XXX value */
100859   u8 mPragFlag;             /* Zero or more PragFlag_XXX values */
100860   u32 iArg;                 /* Extra argument */
100861 } aPragmaNames[] = {
100862 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
100863   { /* zName:     */ "activate_extensions",
100864     /* ePragTyp:  */ PragTyp_ACTIVATE_EXTENSIONS,
100865     /* ePragFlag: */ 0,
100866     /* iArg:      */ 0 },
100867 #endif
100868 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
100869   { /* zName:     */ "application_id",
100870     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
100871     /* ePragFlag: */ 0,
100872     /* iArg:      */ 0 },
100873 #endif
100874 #if !defined(SQLITE_OMIT_AUTOVACUUM)
100875   { /* zName:     */ "auto_vacuum",
100876     /* ePragTyp:  */ PragTyp_AUTO_VACUUM,
100877     /* ePragFlag: */ PragFlag_NeedSchema,
100878     /* iArg:      */ 0 },
100879 #endif
100880 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
100881 #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
100882   { /* zName:     */ "automatic_index",
100883     /* ePragTyp:  */ PragTyp_FLAG,
100884     /* ePragFlag: */ 0,
100885     /* iArg:      */ SQLITE_AutoIndex },
100886 #endif
100887 #endif
100888   { /* zName:     */ "busy_timeout",
100889     /* ePragTyp:  */ PragTyp_BUSY_TIMEOUT,
100890     /* ePragFlag: */ 0,
100891     /* iArg:      */ 0 },
100892 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
100893   { /* zName:     */ "cache_size",
100894     /* ePragTyp:  */ PragTyp_CACHE_SIZE,
100895     /* ePragFlag: */ PragFlag_NeedSchema,
100896     /* iArg:      */ 0 },
100897 #endif
100898 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
100899   { /* zName:     */ "cache_spill",
100900     /* ePragTyp:  */ PragTyp_FLAG,
100901     /* ePragFlag: */ 0,
100902     /* iArg:      */ SQLITE_CacheSpill },
100903 #endif
100904   { /* zName:     */ "case_sensitive_like",
100905     /* ePragTyp:  */ PragTyp_CASE_SENSITIVE_LIKE,
100906     /* ePragFlag: */ 0,
100907     /* iArg:      */ 0 },
100908 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
100909   { /* zName:     */ "checkpoint_fullfsync",
100910     /* ePragTyp:  */ PragTyp_FLAG,
100911     /* ePragFlag: */ 0,
100912     /* iArg:      */ SQLITE_CkptFullFSync },
100913 #endif
100914 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
100915   { /* zName:     */ "collation_list",
100916     /* ePragTyp:  */ PragTyp_COLLATION_LIST,
100917     /* ePragFlag: */ 0,
100918     /* iArg:      */ 0 },
100919 #endif
100920 #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
100921   { /* zName:     */ "compile_options",
100922     /* ePragTyp:  */ PragTyp_COMPILE_OPTIONS,
100923     /* ePragFlag: */ 0,
100924     /* iArg:      */ 0 },
100925 #endif
100926 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
100927   { /* zName:     */ "count_changes",
100928     /* ePragTyp:  */ PragTyp_FLAG,
100929     /* ePragFlag: */ 0,
100930     /* iArg:      */ SQLITE_CountRows },
100931 #endif
100932 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
100933   { /* zName:     */ "data_store_directory",
100934     /* ePragTyp:  */ PragTyp_DATA_STORE_DIRECTORY,
100935     /* ePragFlag: */ 0,
100936     /* iArg:      */ 0 },
100937 #endif
100938 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
100939   { /* zName:     */ "database_list",
100940     /* ePragTyp:  */ PragTyp_DATABASE_LIST,
100941     /* ePragFlag: */ PragFlag_NeedSchema,
100942     /* iArg:      */ 0 },
100943 #endif
100944 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
100945   { /* zName:     */ "default_cache_size",
100946     /* ePragTyp:  */ PragTyp_DEFAULT_CACHE_SIZE,
100947     /* ePragFlag: */ PragFlag_NeedSchema,
100948     /* iArg:      */ 0 },
100949 #endif
100950 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
100951 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
100952   { /* zName:     */ "defer_foreign_keys",
100953     /* ePragTyp:  */ PragTyp_FLAG,
100954     /* ePragFlag: */ 0,
100955     /* iArg:      */ SQLITE_DeferFKs },
100956 #endif
100957 #endif
100958 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
100959   { /* zName:     */ "empty_result_callbacks",
100960     /* ePragTyp:  */ PragTyp_FLAG,
100961     /* ePragFlag: */ 0,
100962     /* iArg:      */ SQLITE_NullCallback },
100963 #endif
100964 #if !defined(SQLITE_OMIT_UTF16)
100965   { /* zName:     */ "encoding",
100966     /* ePragTyp:  */ PragTyp_ENCODING,
100967     /* ePragFlag: */ 0,
100968     /* iArg:      */ 0 },
100969 #endif
100970 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
100971   { /* zName:     */ "foreign_key_check",
100972     /* ePragTyp:  */ PragTyp_FOREIGN_KEY_CHECK,
100973     /* ePragFlag: */ PragFlag_NeedSchema,
100974     /* iArg:      */ 0 },
100975 #endif
100976 #if !defined(SQLITE_OMIT_FOREIGN_KEY)
100977   { /* zName:     */ "foreign_key_list",
100978     /* ePragTyp:  */ PragTyp_FOREIGN_KEY_LIST,
100979     /* ePragFlag: */ PragFlag_NeedSchema,
100980     /* iArg:      */ 0 },
100981 #endif
100982 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
100983 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
100984   { /* zName:     */ "foreign_keys",
100985     /* ePragTyp:  */ PragTyp_FLAG,
100986     /* ePragFlag: */ 0,
100987     /* iArg:      */ SQLITE_ForeignKeys },
100988 #endif
100989 #endif
100990 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
100991   { /* zName:     */ "freelist_count",
100992     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
100993     /* ePragFlag: */ 0,
100994     /* iArg:      */ 0 },
100995 #endif
100996 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
100997   { /* zName:     */ "full_column_names",
100998     /* ePragTyp:  */ PragTyp_FLAG,
100999     /* ePragFlag: */ 0,
101000     /* iArg:      */ SQLITE_FullColNames },
101001   { /* zName:     */ "fullfsync",
101002     /* ePragTyp:  */ PragTyp_FLAG,
101003     /* ePragFlag: */ 0,
101004     /* iArg:      */ SQLITE_FullFSync },
101005 #endif
101006 #if defined(SQLITE_HAS_CODEC)
101007   { /* zName:     */ "hexkey",
101008     /* ePragTyp:  */ PragTyp_HEXKEY,
101009     /* ePragFlag: */ 0,
101010     /* iArg:      */ 0 },
101011   { /* zName:     */ "hexrekey",
101012     /* ePragTyp:  */ PragTyp_HEXKEY,
101013     /* ePragFlag: */ 0,
101014     /* iArg:      */ 0 },
101015 #endif
101016 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101017 #if !defined(SQLITE_OMIT_CHECK)
101018   { /* zName:     */ "ignore_check_constraints",
101019     /* ePragTyp:  */ PragTyp_FLAG,
101020     /* ePragFlag: */ 0,
101021     /* iArg:      */ SQLITE_IgnoreChecks },
101022 #endif
101023 #endif
101024 #if !defined(SQLITE_OMIT_AUTOVACUUM)
101025   { /* zName:     */ "incremental_vacuum",
101026     /* ePragTyp:  */ PragTyp_INCREMENTAL_VACUUM,
101027     /* ePragFlag: */ PragFlag_NeedSchema,
101028     /* iArg:      */ 0 },
101029 #endif
101030 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
101031   { /* zName:     */ "index_info",
101032     /* ePragTyp:  */ PragTyp_INDEX_INFO,
101033     /* ePragFlag: */ PragFlag_NeedSchema,
101034     /* iArg:      */ 0 },
101035   { /* zName:     */ "index_list",
101036     /* ePragTyp:  */ PragTyp_INDEX_LIST,
101037     /* ePragFlag: */ PragFlag_NeedSchema,
101038     /* iArg:      */ 0 },
101039 #endif
101040 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
101041   { /* zName:     */ "integrity_check",
101042     /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
101043     /* ePragFlag: */ PragFlag_NeedSchema,
101044     /* iArg:      */ 0 },
101045 #endif
101046 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
101047   { /* zName:     */ "journal_mode",
101048     /* ePragTyp:  */ PragTyp_JOURNAL_MODE,
101049     /* ePragFlag: */ PragFlag_NeedSchema,
101050     /* iArg:      */ 0 },
101051   { /* zName:     */ "journal_size_limit",
101052     /* ePragTyp:  */ PragTyp_JOURNAL_SIZE_LIMIT,
101053     /* ePragFlag: */ 0,
101054     /* iArg:      */ 0 },
101055 #endif
101056 #if defined(SQLITE_HAS_CODEC)
101057   { /* zName:     */ "key",
101058     /* ePragTyp:  */ PragTyp_KEY,
101059     /* ePragFlag: */ 0,
101060     /* iArg:      */ 0 },
101061 #endif
101062 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101063   { /* zName:     */ "legacy_file_format",
101064     /* ePragTyp:  */ PragTyp_FLAG,
101065     /* ePragFlag: */ 0,
101066     /* iArg:      */ SQLITE_LegacyFileFmt },
101067 #endif
101068 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
101069   { /* zName:     */ "lock_proxy_file",
101070     /* ePragTyp:  */ PragTyp_LOCK_PROXY_FILE,
101071     /* ePragFlag: */ 0,
101072     /* iArg:      */ 0 },
101073 #endif
101074 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
101075   { /* zName:     */ "lock_status",
101076     /* ePragTyp:  */ PragTyp_LOCK_STATUS,
101077     /* ePragFlag: */ 0,
101078     /* iArg:      */ 0 },
101079 #endif
101080 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
101081   { /* zName:     */ "locking_mode",
101082     /* ePragTyp:  */ PragTyp_LOCKING_MODE,
101083     /* ePragFlag: */ 0,
101084     /* iArg:      */ 0 },
101085   { /* zName:     */ "max_page_count",
101086     /* ePragTyp:  */ PragTyp_PAGE_COUNT,
101087     /* ePragFlag: */ PragFlag_NeedSchema,
101088     /* iArg:      */ 0 },
101089   { /* zName:     */ "mmap_size",
101090     /* ePragTyp:  */ PragTyp_MMAP_SIZE,
101091     /* ePragFlag: */ 0,
101092     /* iArg:      */ 0 },
101093   { /* zName:     */ "page_count",
101094     /* ePragTyp:  */ PragTyp_PAGE_COUNT,
101095     /* ePragFlag: */ PragFlag_NeedSchema,
101096     /* iArg:      */ 0 },
101097   { /* zName:     */ "page_size",
101098     /* ePragTyp:  */ PragTyp_PAGE_SIZE,
101099     /* ePragFlag: */ 0,
101100     /* iArg:      */ 0 },
101101 #endif
101102 #if defined(SQLITE_DEBUG)
101103   { /* zName:     */ "parser_trace",
101104     /* ePragTyp:  */ PragTyp_PARSER_TRACE,
101105     /* ePragFlag: */ 0,
101106     /* iArg:      */ 0 },
101107 #endif
101108 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101109   { /* zName:     */ "query_only",
101110     /* ePragTyp:  */ PragTyp_FLAG,
101111     /* ePragFlag: */ 0,
101112     /* iArg:      */ SQLITE_QueryOnly },
101113 #endif
101114 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
101115   { /* zName:     */ "quick_check",
101116     /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
101117     /* ePragFlag: */ PragFlag_NeedSchema,
101118     /* iArg:      */ 0 },
101119 #endif
101120 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101121   { /* zName:     */ "read_uncommitted",
101122     /* ePragTyp:  */ PragTyp_FLAG,
101123     /* ePragFlag: */ 0,
101124     /* iArg:      */ SQLITE_ReadUncommitted },
101125   { /* zName:     */ "recursive_triggers",
101126     /* ePragTyp:  */ PragTyp_FLAG,
101127     /* ePragFlag: */ 0,
101128     /* iArg:      */ SQLITE_RecTriggers },
101129 #endif
101130 #if defined(SQLITE_HAS_CODEC)
101131   { /* zName:     */ "rekey",
101132     /* ePragTyp:  */ PragTyp_REKEY,
101133     /* ePragFlag: */ 0,
101134     /* iArg:      */ 0 },
101135 #endif
101136 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101137   { /* zName:     */ "reverse_unordered_selects",
101138     /* ePragTyp:  */ PragTyp_FLAG,
101139     /* ePragFlag: */ 0,
101140     /* iArg:      */ SQLITE_ReverseOrder },
101141 #endif
101142 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
101143   { /* zName:     */ "schema_version",
101144     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
101145     /* ePragFlag: */ 0,
101146     /* iArg:      */ 0 },
101147 #endif
101148 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
101149   { /* zName:     */ "secure_delete",
101150     /* ePragTyp:  */ PragTyp_SECURE_DELETE,
101151     /* ePragFlag: */ 0,
101152     /* iArg:      */ 0 },
101153 #endif
101154 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101155   { /* zName:     */ "short_column_names",
101156     /* ePragTyp:  */ PragTyp_FLAG,
101157     /* ePragFlag: */ 0,
101158     /* iArg:      */ SQLITE_ShortColNames },
101159 #endif
101160   { /* zName:     */ "shrink_memory",
101161     /* ePragTyp:  */ PragTyp_SHRINK_MEMORY,
101162     /* ePragFlag: */ 0,
101163     /* iArg:      */ 0 },
101164   { /* zName:     */ "soft_heap_limit",
101165     /* ePragTyp:  */ PragTyp_SOFT_HEAP_LIMIT,
101166     /* ePragFlag: */ 0,
101167     /* iArg:      */ 0 },
101168 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101169 #if defined(SQLITE_DEBUG)
101170   { /* zName:     */ "sql_trace",
101171     /* ePragTyp:  */ PragTyp_FLAG,
101172     /* ePragFlag: */ 0,
101173     /* iArg:      */ SQLITE_SqlTrace },
101174 #endif
101175 #endif
101176 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
101177   { /* zName:     */ "stats",
101178     /* ePragTyp:  */ PragTyp_STATS,
101179     /* ePragFlag: */ PragFlag_NeedSchema,
101180     /* iArg:      */ 0 },
101181 #endif
101182 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
101183   { /* zName:     */ "synchronous",
101184     /* ePragTyp:  */ PragTyp_SYNCHRONOUS,
101185     /* ePragFlag: */ PragFlag_NeedSchema,
101186     /* iArg:      */ 0 },
101187 #endif
101188 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
101189   { /* zName:     */ "table_info",
101190     /* ePragTyp:  */ PragTyp_TABLE_INFO,
101191     /* ePragFlag: */ PragFlag_NeedSchema,
101192     /* iArg:      */ 0 },
101193 #endif
101194 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
101195   { /* zName:     */ "temp_store",
101196     /* ePragTyp:  */ PragTyp_TEMP_STORE,
101197     /* ePragFlag: */ 0,
101198     /* iArg:      */ 0 },
101199   { /* zName:     */ "temp_store_directory",
101200     /* ePragTyp:  */ PragTyp_TEMP_STORE_DIRECTORY,
101201     /* ePragFlag: */ 0,
101202     /* iArg:      */ 0 },
101203 #endif
101204   { /* zName:     */ "threads",
101205     /* ePragTyp:  */ PragTyp_THREADS,
101206     /* ePragFlag: */ 0,
101207     /* iArg:      */ 0 },
101208 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
101209   { /* zName:     */ "user_version",
101210     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
101211     /* ePragFlag: */ 0,
101212     /* iArg:      */ 0 },
101213 #endif
101214 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101215 #if defined(SQLITE_DEBUG)
101216   { /* zName:     */ "vdbe_addoptrace",
101217     /* ePragTyp:  */ PragTyp_FLAG,
101218     /* ePragFlag: */ 0,
101219     /* iArg:      */ SQLITE_VdbeAddopTrace },
101220   { /* zName:     */ "vdbe_debug",
101221     /* ePragTyp:  */ PragTyp_FLAG,
101222     /* ePragFlag: */ 0,
101223     /* iArg:      */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
101224   { /* zName:     */ "vdbe_eqp",
101225     /* ePragTyp:  */ PragTyp_FLAG,
101226     /* ePragFlag: */ 0,
101227     /* iArg:      */ SQLITE_VdbeEQP },
101228   { /* zName:     */ "vdbe_listing",
101229     /* ePragTyp:  */ PragTyp_FLAG,
101230     /* ePragFlag: */ 0,
101231     /* iArg:      */ SQLITE_VdbeListing },
101232   { /* zName:     */ "vdbe_trace",
101233     /* ePragTyp:  */ PragTyp_FLAG,
101234     /* ePragFlag: */ 0,
101235     /* iArg:      */ SQLITE_VdbeTrace },
101236 #endif
101237 #endif
101238 #if !defined(SQLITE_OMIT_WAL)
101239   { /* zName:     */ "wal_autocheckpoint",
101240     /* ePragTyp:  */ PragTyp_WAL_AUTOCHECKPOINT,
101241     /* ePragFlag: */ 0,
101242     /* iArg:      */ 0 },
101243   { /* zName:     */ "wal_checkpoint",
101244     /* ePragTyp:  */ PragTyp_WAL_CHECKPOINT,
101245     /* ePragFlag: */ PragFlag_NeedSchema,
101246     /* iArg:      */ 0 },
101247 #endif
101248 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
101249   { /* zName:     */ "writable_schema",
101250     /* ePragTyp:  */ PragTyp_FLAG,
101251     /* ePragFlag: */ 0,
101252     /* iArg:      */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
101253 #endif
101254 };
101255 /* Number of pragmas: 57 on by default, 70 total. */
101256 /* End of the automatically generated pragma table.
101257 ***************************************************************************/
101258 
101259 /*
101260 ** Interpret the given string as a safety level.  Return 0 for OFF,
101261 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
101262 ** unrecognized string argument.  The FULL option is disallowed
101263 ** if the omitFull parameter it 1.
101264 **
101265 ** Note that the values returned are one less that the values that
101266 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
101267 ** to support legacy SQL code.  The safety level used to be boolean
101268 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
101269 */
101270 static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
101271                              /* 123456789 123456789 */
101272   static const char zText[] = "onoffalseyestruefull";
101273   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
101274   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
101275   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
101276   int i, n;
101277   if( sqlite3Isdigit(*z) ){
101278     return (u8)sqlite3Atoi(z);
101279   }
101280   n = sqlite3Strlen30(z);
101281   for(i=0; i<ArraySize(iLength)-omitFull; i++){
101282     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
101283       return iValue[i];
101284     }
101285   }
101286   return dflt;
101287 }
101288 
101289 /*
101290 ** Interpret the given string as a boolean value.
101291 */
101292 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
101293   return getSafetyLevel(z,1,dflt)!=0;
101294 }
101295 
101296 /* The sqlite3GetBoolean() function is used by other modules but the
101297 ** remainder of this file is specific to PRAGMA processing.  So omit
101298 ** the rest of the file if PRAGMAs are omitted from the build.
101299 */
101300 #if !defined(SQLITE_OMIT_PRAGMA)
101301 
101302 /*
101303 ** Interpret the given string as a locking mode value.
101304 */
101305 static int getLockingMode(const char *z){
101306   if( z ){
101307     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
101308     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
101309   }
101310   return PAGER_LOCKINGMODE_QUERY;
101311 }
101312 
101313 #ifndef SQLITE_OMIT_AUTOVACUUM
101314 /*
101315 ** Interpret the given string as an auto-vacuum mode value.
101316 **
101317 ** The following strings, "none", "full" and "incremental" are
101318 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
101319 */
101320 static int getAutoVacuum(const char *z){
101321   int i;
101322   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
101323   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
101324   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
101325   i = sqlite3Atoi(z);
101326   return (u8)((i>=0&&i<=2)?i:0);
101327 }
101328 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
101329 
101330 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
101331 /*
101332 ** Interpret the given string as a temp db location. Return 1 for file
101333 ** backed temporary databases, 2 for the Red-Black tree in memory database
101334 ** and 0 to use the compile-time default.
101335 */
101336 static int getTempStore(const char *z){
101337   if( z[0]>='0' && z[0]<='2' ){
101338     return z[0] - '0';
101339   }else if( sqlite3StrICmp(z, "file")==0 ){
101340     return 1;
101341   }else if( sqlite3StrICmp(z, "memory")==0 ){
101342     return 2;
101343   }else{
101344     return 0;
101345   }
101346 }
101347 #endif /* SQLITE_PAGER_PRAGMAS */
101348 
101349 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
101350 /*
101351 ** Invalidate temp storage, either when the temp storage is changed
101352 ** from default, or when 'file' and the temp_store_directory has changed
101353 */
101354 static int invalidateTempStorage(Parse *pParse){
101355   sqlite3 *db = pParse->db;
101356   if( db->aDb[1].pBt!=0 ){
101357     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
101358       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
101359         "from within a transaction");
101360       return SQLITE_ERROR;
101361     }
101362     sqlite3BtreeClose(db->aDb[1].pBt);
101363     db->aDb[1].pBt = 0;
101364     sqlite3ResetAllSchemasOfConnection(db);
101365   }
101366   return SQLITE_OK;
101367 }
101368 #endif /* SQLITE_PAGER_PRAGMAS */
101369 
101370 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
101371 /*
101372 ** If the TEMP database is open, close it and mark the database schema
101373 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
101374 ** or DEFAULT_TEMP_STORE pragmas.
101375 */
101376 static int changeTempStorage(Parse *pParse, const char *zStorageType){
101377   int ts = getTempStore(zStorageType);
101378   sqlite3 *db = pParse->db;
101379   if( db->temp_store==ts ) return SQLITE_OK;
101380   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
101381     return SQLITE_ERROR;
101382   }
101383   db->temp_store = (u8)ts;
101384   return SQLITE_OK;
101385 }
101386 #endif /* SQLITE_PAGER_PRAGMAS */
101387 
101388 /*
101389 ** Generate code to return a single integer value.
101390 */
101391 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
101392   Vdbe *v = sqlite3GetVdbe(pParse);
101393   int mem = ++pParse->nMem;
101394   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
101395   if( pI64 ){
101396     memcpy(pI64, &value, sizeof(value));
101397   }
101398   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
101399   sqlite3VdbeSetNumCols(v, 1);
101400   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
101401   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
101402 }
101403 
101404 
101405 /*
101406 ** Set the safety_level and pager flags for pager iDb.  Or if iDb<0
101407 ** set these values for all pagers.
101408 */
101409 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
101410 static void setAllPagerFlags(sqlite3 *db){
101411   if( db->autoCommit ){
101412     Db *pDb = db->aDb;
101413     int n = db->nDb;
101414     assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
101415     assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
101416     assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
101417     assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
101418              ==  PAGER_FLAGS_MASK );
101419     assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
101420     while( (n--) > 0 ){
101421       if( pDb->pBt ){
101422         sqlite3BtreeSetPagerFlags(pDb->pBt,
101423                  pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
101424       }
101425       pDb++;
101426     }
101427   }
101428 }
101429 #else
101430 # define setAllPagerFlags(X)  /* no-op */
101431 #endif
101432 
101433 
101434 /*
101435 ** Return a human-readable name for a constraint resolution action.
101436 */
101437 #ifndef SQLITE_OMIT_FOREIGN_KEY
101438 static const char *actionName(u8 action){
101439   const char *zName;
101440   switch( action ){
101441     case OE_SetNull:  zName = "SET NULL";        break;
101442     case OE_SetDflt:  zName = "SET DEFAULT";     break;
101443     case OE_Cascade:  zName = "CASCADE";         break;
101444     case OE_Restrict: zName = "RESTRICT";        break;
101445     default:          zName = "NO ACTION";
101446                       assert( action==OE_None ); break;
101447   }
101448   return zName;
101449 }
101450 #endif
101451 
101452 
101453 /*
101454 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
101455 ** defined in pager.h. This function returns the associated lowercase
101456 ** journal-mode name.
101457 */
101458 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
101459   static char * const azModeName[] = {
101460     "delete", "persist", "off", "truncate", "memory"
101461 #ifndef SQLITE_OMIT_WAL
101462      , "wal"
101463 #endif
101464   };
101465   assert( PAGER_JOURNALMODE_DELETE==0 );
101466   assert( PAGER_JOURNALMODE_PERSIST==1 );
101467   assert( PAGER_JOURNALMODE_OFF==2 );
101468   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
101469   assert( PAGER_JOURNALMODE_MEMORY==4 );
101470   assert( PAGER_JOURNALMODE_WAL==5 );
101471   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
101472 
101473   if( eMode==ArraySize(azModeName) ) return 0;
101474   return azModeName[eMode];
101475 }
101476 
101477 /*
101478 ** Process a pragma statement.
101479 **
101480 ** Pragmas are of this form:
101481 **
101482 **      PRAGMA [database.]id [= value]
101483 **
101484 ** The identifier might also be a string.  The value is a string, and
101485 ** identifier, or a number.  If minusFlag is true, then the value is
101486 ** a number that was preceded by a minus sign.
101487 **
101488 ** If the left side is "database.id" then pId1 is the database name
101489 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
101490 ** id and pId2 is any empty string.
101491 */
101492 SQLITE_PRIVATE void sqlite3Pragma(
101493   Parse *pParse,
101494   Token *pId1,        /* First part of [database.]id field */
101495   Token *pId2,        /* Second part of [database.]id field, or NULL */
101496   Token *pValue,      /* Token for <value>, or NULL */
101497   int minusFlag       /* True if a '-' sign preceded <value> */
101498 ){
101499   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
101500   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
101501   const char *zDb = 0;   /* The database name */
101502   Token *pId;            /* Pointer to <id> token */
101503   char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
101504   int iDb;               /* Database index for <database> */
101505   int lwr, upr, mid;           /* Binary search bounds */
101506   int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
101507   sqlite3 *db = pParse->db;    /* The database connection */
101508   Db *pDb;                     /* The specific database being pragmaed */
101509   Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
101510 
101511   if( v==0 ) return;
101512   sqlite3VdbeRunOnlyOnce(v);
101513   pParse->nMem = 2;
101514 
101515   /* Interpret the [database.] part of the pragma statement. iDb is the
101516   ** index of the database this pragma is being applied to in db.aDb[]. */
101517   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
101518   if( iDb<0 ) return;
101519   pDb = &db->aDb[iDb];
101520 
101521   /* If the temp database has been explicitly named as part of the
101522   ** pragma, make sure it is open.
101523   */
101524   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
101525     return;
101526   }
101527 
101528   zLeft = sqlite3NameFromToken(db, pId);
101529   if( !zLeft ) return;
101530   if( minusFlag ){
101531     zRight = sqlite3MPrintf(db, "-%T", pValue);
101532   }else{
101533     zRight = sqlite3NameFromToken(db, pValue);
101534   }
101535 
101536   assert( pId2 );
101537   zDb = pId2->n>0 ? pDb->zName : 0;
101538   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
101539     goto pragma_out;
101540   }
101541 
101542   /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
101543   ** connection.  If it returns SQLITE_OK, then assume that the VFS
101544   ** handled the pragma and generate a no-op prepared statement.
101545   */
101546   aFcntl[0] = 0;
101547   aFcntl[1] = zLeft;
101548   aFcntl[2] = zRight;
101549   aFcntl[3] = 0;
101550   db->busyHandler.nBusy = 0;
101551   rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
101552   if( rc==SQLITE_OK ){
101553     if( aFcntl[0] ){
101554       int mem = ++pParse->nMem;
101555       sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
101556       sqlite3VdbeSetNumCols(v, 1);
101557       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
101558       sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
101559       sqlite3_free(aFcntl[0]);
101560     }
101561     goto pragma_out;
101562   }
101563   if( rc!=SQLITE_NOTFOUND ){
101564     if( aFcntl[0] ){
101565       sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
101566       sqlite3_free(aFcntl[0]);
101567     }
101568     pParse->nErr++;
101569     pParse->rc = rc;
101570     goto pragma_out;
101571   }
101572 
101573   /* Locate the pragma in the lookup table */
101574   lwr = 0;
101575   upr = ArraySize(aPragmaNames)-1;
101576   while( lwr<=upr ){
101577     mid = (lwr+upr)/2;
101578     rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
101579     if( rc==0 ) break;
101580     if( rc<0 ){
101581       upr = mid - 1;
101582     }else{
101583       lwr = mid + 1;
101584     }
101585   }
101586   if( lwr>upr ) goto pragma_out;
101587 
101588   /* Make sure the database schema is loaded if the pragma requires that */
101589   if( (aPragmaNames[mid].mPragFlag & PragFlag_NeedSchema)!=0 ){
101590     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
101591   }
101592 
101593   /* Jump to the appropriate pragma handler */
101594   switch( aPragmaNames[mid].ePragTyp ){
101595 
101596 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
101597   /*
101598   **  PRAGMA [database.]default_cache_size
101599   **  PRAGMA [database.]default_cache_size=N
101600   **
101601   ** The first form reports the current persistent setting for the
101602   ** page cache size.  The value returned is the maximum number of
101603   ** pages in the page cache.  The second form sets both the current
101604   ** page cache size value and the persistent page cache size value
101605   ** stored in the database file.
101606   **
101607   ** Older versions of SQLite would set the default cache size to a
101608   ** negative number to indicate synchronous=OFF.  These days, synchronous
101609   ** is always on by default regardless of the sign of the default cache
101610   ** size.  But continue to take the absolute value of the default cache
101611   ** size of historical compatibility.
101612   */
101613   case PragTyp_DEFAULT_CACHE_SIZE: {
101614     static const int iLn = VDBE_OFFSET_LINENO(2);
101615     static const VdbeOpList getCacheSize[] = {
101616       { OP_Transaction, 0, 0,        0},                         /* 0 */
101617       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
101618       { OP_IfPos,       1, 8,        0},
101619       { OP_Integer,     0, 2,        0},
101620       { OP_Subtract,    1, 2,        1},
101621       { OP_IfPos,       1, 8,        0},
101622       { OP_Integer,     0, 1,        0},                         /* 6 */
101623       { OP_Noop,        0, 0,        0},
101624       { OP_ResultRow,   1, 1,        0},
101625     };
101626     int addr;
101627     sqlite3VdbeUsesBtree(v, iDb);
101628     if( !zRight ){
101629       sqlite3VdbeSetNumCols(v, 1);
101630       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
101631       pParse->nMem += 2;
101632       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize,iLn);
101633       sqlite3VdbeChangeP1(v, addr, iDb);
101634       sqlite3VdbeChangeP1(v, addr+1, iDb);
101635       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
101636     }else{
101637       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
101638       sqlite3BeginWriteOperation(pParse, 0, iDb);
101639       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
101640       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
101641       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101642       pDb->pSchema->cache_size = size;
101643       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
101644     }
101645     break;
101646   }
101647 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
101648 
101649 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
101650   /*
101651   **  PRAGMA [database.]page_size
101652   **  PRAGMA [database.]page_size=N
101653   **
101654   ** The first form reports the current setting for the
101655   ** database page size in bytes.  The second form sets the
101656   ** database page size value.  The value can only be set if
101657   ** the database has not yet been created.
101658   */
101659   case PragTyp_PAGE_SIZE: {
101660     Btree *pBt = pDb->pBt;
101661     assert( pBt!=0 );
101662     if( !zRight ){
101663       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
101664       returnSingleInt(pParse, "page_size", size);
101665     }else{
101666       /* Malloc may fail when setting the page-size, as there is an internal
101667       ** buffer that the pager module resizes using sqlite3_realloc().
101668       */
101669       db->nextPagesize = sqlite3Atoi(zRight);
101670       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
101671         db->mallocFailed = 1;
101672       }
101673     }
101674     break;
101675   }
101676 
101677   /*
101678   **  PRAGMA [database.]secure_delete
101679   **  PRAGMA [database.]secure_delete=ON/OFF
101680   **
101681   ** The first form reports the current setting for the
101682   ** secure_delete flag.  The second form changes the secure_delete
101683   ** flag setting and reports thenew value.
101684   */
101685   case PragTyp_SECURE_DELETE: {
101686     Btree *pBt = pDb->pBt;
101687     int b = -1;
101688     assert( pBt!=0 );
101689     if( zRight ){
101690       b = sqlite3GetBoolean(zRight, 0);
101691     }
101692     if( pId2->n==0 && b>=0 ){
101693       int ii;
101694       for(ii=0; ii<db->nDb; ii++){
101695         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
101696       }
101697     }
101698     b = sqlite3BtreeSecureDelete(pBt, b);
101699     returnSingleInt(pParse, "secure_delete", b);
101700     break;
101701   }
101702 
101703   /*
101704   **  PRAGMA [database.]max_page_count
101705   **  PRAGMA [database.]max_page_count=N
101706   **
101707   ** The first form reports the current setting for the
101708   ** maximum number of pages in the database file.  The
101709   ** second form attempts to change this setting.  Both
101710   ** forms return the current setting.
101711   **
101712   ** The absolute value of N is used.  This is undocumented and might
101713   ** change.  The only purpose is to provide an easy way to test
101714   ** the sqlite3AbsInt32() function.
101715   **
101716   **  PRAGMA [database.]page_count
101717   **
101718   ** Return the number of pages in the specified database.
101719   */
101720   case PragTyp_PAGE_COUNT: {
101721     int iReg;
101722     sqlite3CodeVerifySchema(pParse, iDb);
101723     iReg = ++pParse->nMem;
101724     if( sqlite3Tolower(zLeft[0])=='p' ){
101725       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
101726     }else{
101727       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
101728                         sqlite3AbsInt32(sqlite3Atoi(zRight)));
101729     }
101730     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
101731     sqlite3VdbeSetNumCols(v, 1);
101732     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
101733     break;
101734   }
101735 
101736   /*
101737   **  PRAGMA [database.]locking_mode
101738   **  PRAGMA [database.]locking_mode = (normal|exclusive)
101739   */
101740   case PragTyp_LOCKING_MODE: {
101741     const char *zRet = "normal";
101742     int eMode = getLockingMode(zRight);
101743 
101744     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
101745       /* Simple "PRAGMA locking_mode;" statement. This is a query for
101746       ** the current default locking mode (which may be different to
101747       ** the locking-mode of the main database).
101748       */
101749       eMode = db->dfltLockMode;
101750     }else{
101751       Pager *pPager;
101752       if( pId2->n==0 ){
101753         /* This indicates that no database name was specified as part
101754         ** of the PRAGMA command. In this case the locking-mode must be
101755         ** set on all attached databases, as well as the main db file.
101756         **
101757         ** Also, the sqlite3.dfltLockMode variable is set so that
101758         ** any subsequently attached databases also use the specified
101759         ** locking mode.
101760         */
101761         int ii;
101762         assert(pDb==&db->aDb[0]);
101763         for(ii=2; ii<db->nDb; ii++){
101764           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
101765           sqlite3PagerLockingMode(pPager, eMode);
101766         }
101767         db->dfltLockMode = (u8)eMode;
101768       }
101769       pPager = sqlite3BtreePager(pDb->pBt);
101770       eMode = sqlite3PagerLockingMode(pPager, eMode);
101771     }
101772 
101773     assert( eMode==PAGER_LOCKINGMODE_NORMAL
101774             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
101775     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
101776       zRet = "exclusive";
101777     }
101778     sqlite3VdbeSetNumCols(v, 1);
101779     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
101780     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
101781     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
101782     break;
101783   }
101784 
101785   /*
101786   **  PRAGMA [database.]journal_mode
101787   **  PRAGMA [database.]journal_mode =
101788   **                      (delete|persist|off|truncate|memory|wal|off)
101789   */
101790   case PragTyp_JOURNAL_MODE: {
101791     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
101792     int ii;           /* Loop counter */
101793 
101794     sqlite3VdbeSetNumCols(v, 1);
101795     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
101796 
101797     if( zRight==0 ){
101798       /* If there is no "=MODE" part of the pragma, do a query for the
101799       ** current mode */
101800       eMode = PAGER_JOURNALMODE_QUERY;
101801     }else{
101802       const char *zMode;
101803       int n = sqlite3Strlen30(zRight);
101804       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
101805         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
101806       }
101807       if( !zMode ){
101808         /* If the "=MODE" part does not match any known journal mode,
101809         ** then do a query */
101810         eMode = PAGER_JOURNALMODE_QUERY;
101811       }
101812     }
101813     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
101814       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
101815       iDb = 0;
101816       pId2->n = 1;
101817     }
101818     for(ii=db->nDb-1; ii>=0; ii--){
101819       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
101820         sqlite3VdbeUsesBtree(v, ii);
101821         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
101822       }
101823     }
101824     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
101825     break;
101826   }
101827 
101828   /*
101829   **  PRAGMA [database.]journal_size_limit
101830   **  PRAGMA [database.]journal_size_limit=N
101831   **
101832   ** Get or set the size limit on rollback journal files.
101833   */
101834   case PragTyp_JOURNAL_SIZE_LIMIT: {
101835     Pager *pPager = sqlite3BtreePager(pDb->pBt);
101836     i64 iLimit = -2;
101837     if( zRight ){
101838       sqlite3DecOrHexToI64(zRight, &iLimit);
101839       if( iLimit<-1 ) iLimit = -1;
101840     }
101841     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
101842     returnSingleInt(pParse, "journal_size_limit", iLimit);
101843     break;
101844   }
101845 
101846 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
101847 
101848   /*
101849   **  PRAGMA [database.]auto_vacuum
101850   **  PRAGMA [database.]auto_vacuum=N
101851   **
101852   ** Get or set the value of the database 'auto-vacuum' parameter.
101853   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
101854   */
101855 #ifndef SQLITE_OMIT_AUTOVACUUM
101856   case PragTyp_AUTO_VACUUM: {
101857     Btree *pBt = pDb->pBt;
101858     assert( pBt!=0 );
101859     if( !zRight ){
101860       returnSingleInt(pParse, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
101861     }else{
101862       int eAuto = getAutoVacuum(zRight);
101863       assert( eAuto>=0 && eAuto<=2 );
101864       db->nextAutovac = (u8)eAuto;
101865       /* Call SetAutoVacuum() to set initialize the internal auto and
101866       ** incr-vacuum flags. This is required in case this connection
101867       ** creates the database file. It is important that it is created
101868       ** as an auto-vacuum capable db.
101869       */
101870       rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
101871       if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
101872         /* When setting the auto_vacuum mode to either "full" or
101873         ** "incremental", write the value of meta[6] in the database
101874         ** file. Before writing to meta[6], check that meta[3] indicates
101875         ** that this really is an auto-vacuum capable database.
101876         */
101877         static const int iLn = VDBE_OFFSET_LINENO(2);
101878         static const VdbeOpList setMeta6[] = {
101879           { OP_Transaction,    0,         1,                 0},    /* 0 */
101880           { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
101881           { OP_If,             1,         0,                 0},    /* 2 */
101882           { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
101883           { OP_Integer,        0,         1,                 0},    /* 4 */
101884           { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
101885         };
101886         int iAddr;
101887         iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
101888         sqlite3VdbeChangeP1(v, iAddr, iDb);
101889         sqlite3VdbeChangeP1(v, iAddr+1, iDb);
101890         sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
101891         sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
101892         sqlite3VdbeChangeP1(v, iAddr+5, iDb);
101893         sqlite3VdbeUsesBtree(v, iDb);
101894       }
101895     }
101896     break;
101897   }
101898 #endif
101899 
101900   /*
101901   **  PRAGMA [database.]incremental_vacuum(N)
101902   **
101903   ** Do N steps of incremental vacuuming on a database.
101904   */
101905 #ifndef SQLITE_OMIT_AUTOVACUUM
101906   case PragTyp_INCREMENTAL_VACUUM: {
101907     int iLimit, addr;
101908     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
101909       iLimit = 0x7fffffff;
101910     }
101911     sqlite3BeginWriteOperation(pParse, 0, iDb);
101912     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
101913     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
101914     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
101915     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
101916     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
101917     sqlite3VdbeJumpHere(v, addr);
101918     break;
101919   }
101920 #endif
101921 
101922 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
101923   /*
101924   **  PRAGMA [database.]cache_size
101925   **  PRAGMA [database.]cache_size=N
101926   **
101927   ** The first form reports the current local setting for the
101928   ** page cache size. The second form sets the local
101929   ** page cache size value.  If N is positive then that is the
101930   ** number of pages in the cache.  If N is negative, then the
101931   ** number of pages is adjusted so that the cache uses -N kibibytes
101932   ** of memory.
101933   */
101934   case PragTyp_CACHE_SIZE: {
101935     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101936     if( !zRight ){
101937       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
101938     }else{
101939       int size = sqlite3Atoi(zRight);
101940       pDb->pSchema->cache_size = size;
101941       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
101942     }
101943     break;
101944   }
101945 
101946   /*
101947   **  PRAGMA [database.]mmap_size(N)
101948   **
101949   ** Used to set mapping size limit. The mapping size limit is
101950   ** used to limit the aggregate size of all memory mapped regions of the
101951   ** database file. If this parameter is set to zero, then memory mapping
101952   ** is not used at all.  If N is negative, then the default memory map
101953   ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
101954   ** The parameter N is measured in bytes.
101955   **
101956   ** This value is advisory.  The underlying VFS is free to memory map
101957   ** as little or as much as it wants.  Except, if N is set to 0 then the
101958   ** upper layers will never invoke the xFetch interfaces to the VFS.
101959   */
101960   case PragTyp_MMAP_SIZE: {
101961     sqlite3_int64 sz;
101962 #if SQLITE_MAX_MMAP_SIZE>0
101963     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101964     if( zRight ){
101965       int ii;
101966       sqlite3DecOrHexToI64(zRight, &sz);
101967       if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
101968       if( pId2->n==0 ) db->szMmap = sz;
101969       for(ii=db->nDb-1; ii>=0; ii--){
101970         if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
101971           sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
101972         }
101973       }
101974     }
101975     sz = -1;
101976     rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
101977 #else
101978     sz = 0;
101979     rc = SQLITE_OK;
101980 #endif
101981     if( rc==SQLITE_OK ){
101982       returnSingleInt(pParse, "mmap_size", sz);
101983     }else if( rc!=SQLITE_NOTFOUND ){
101984       pParse->nErr++;
101985       pParse->rc = rc;
101986     }
101987     break;
101988   }
101989 
101990   /*
101991   **   PRAGMA temp_store
101992   **   PRAGMA temp_store = "default"|"memory"|"file"
101993   **
101994   ** Return or set the local value of the temp_store flag.  Changing
101995   ** the local value does not make changes to the disk file and the default
101996   ** value will be restored the next time the database is opened.
101997   **
101998   ** Note that it is possible for the library compile-time options to
101999   ** override this setting
102000   */
102001   case PragTyp_TEMP_STORE: {
102002     if( !zRight ){
102003       returnSingleInt(pParse, "temp_store", db->temp_store);
102004     }else{
102005       changeTempStorage(pParse, zRight);
102006     }
102007     break;
102008   }
102009 
102010   /*
102011   **   PRAGMA temp_store_directory
102012   **   PRAGMA temp_store_directory = ""|"directory_name"
102013   **
102014   ** Return or set the local value of the temp_store_directory flag.  Changing
102015   ** the value sets a specific directory to be used for temporary files.
102016   ** Setting to a null string reverts to the default temporary directory search.
102017   ** If temporary directory is changed, then invalidateTempStorage.
102018   **
102019   */
102020   case PragTyp_TEMP_STORE_DIRECTORY: {
102021     if( !zRight ){
102022       if( sqlite3_temp_directory ){
102023         sqlite3VdbeSetNumCols(v, 1);
102024         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
102025             "temp_store_directory", SQLITE_STATIC);
102026         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
102027         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
102028       }
102029     }else{
102030 #ifndef SQLITE_OMIT_WSD
102031       if( zRight[0] ){
102032         int res;
102033         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
102034         if( rc!=SQLITE_OK || res==0 ){
102035           sqlite3ErrorMsg(pParse, "not a writable directory");
102036           goto pragma_out;
102037         }
102038       }
102039       if( SQLITE_TEMP_STORE==0
102040        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
102041        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
102042       ){
102043         invalidateTempStorage(pParse);
102044       }
102045       sqlite3_free(sqlite3_temp_directory);
102046       if( zRight[0] ){
102047         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
102048       }else{
102049         sqlite3_temp_directory = 0;
102050       }
102051 #endif /* SQLITE_OMIT_WSD */
102052     }
102053     break;
102054   }
102055 
102056 #if SQLITE_OS_WIN
102057   /*
102058   **   PRAGMA data_store_directory
102059   **   PRAGMA data_store_directory = ""|"directory_name"
102060   **
102061   ** Return or set the local value of the data_store_directory flag.  Changing
102062   ** the value sets a specific directory to be used for database files that
102063   ** were specified with a relative pathname.  Setting to a null string reverts
102064   ** to the default database directory, which for database files specified with
102065   ** a relative path will probably be based on the current directory for the
102066   ** process.  Database file specified with an absolute path are not impacted
102067   ** by this setting, regardless of its value.
102068   **
102069   */
102070   case PragTyp_DATA_STORE_DIRECTORY: {
102071     if( !zRight ){
102072       if( sqlite3_data_directory ){
102073         sqlite3VdbeSetNumCols(v, 1);
102074         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
102075             "data_store_directory", SQLITE_STATIC);
102076         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
102077         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
102078       }
102079     }else{
102080 #ifndef SQLITE_OMIT_WSD
102081       if( zRight[0] ){
102082         int res;
102083         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
102084         if( rc!=SQLITE_OK || res==0 ){
102085           sqlite3ErrorMsg(pParse, "not a writable directory");
102086           goto pragma_out;
102087         }
102088       }
102089       sqlite3_free(sqlite3_data_directory);
102090       if( zRight[0] ){
102091         sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
102092       }else{
102093         sqlite3_data_directory = 0;
102094       }
102095 #endif /* SQLITE_OMIT_WSD */
102096     }
102097     break;
102098   }
102099 #endif
102100 
102101 #if SQLITE_ENABLE_LOCKING_STYLE
102102   /*
102103   **   PRAGMA [database.]lock_proxy_file
102104   **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
102105   **
102106   ** Return or set the value of the lock_proxy_file flag.  Changing
102107   ** the value sets a specific file to be used for database access locks.
102108   **
102109   */
102110   case PragTyp_LOCK_PROXY_FILE: {
102111     if( !zRight ){
102112       Pager *pPager = sqlite3BtreePager(pDb->pBt);
102113       char *proxy_file_path = NULL;
102114       sqlite3_file *pFile = sqlite3PagerFile(pPager);
102115       sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
102116                            &proxy_file_path);
102117 
102118       if( proxy_file_path ){
102119         sqlite3VdbeSetNumCols(v, 1);
102120         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
102121                               "lock_proxy_file", SQLITE_STATIC);
102122         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
102123         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
102124       }
102125     }else{
102126       Pager *pPager = sqlite3BtreePager(pDb->pBt);
102127       sqlite3_file *pFile = sqlite3PagerFile(pPager);
102128       int res;
102129       if( zRight[0] ){
102130         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
102131                                      zRight);
102132       } else {
102133         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
102134                                      NULL);
102135       }
102136       if( res!=SQLITE_OK ){
102137         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
102138         goto pragma_out;
102139       }
102140     }
102141     break;
102142   }
102143 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
102144 
102145   /*
102146   **   PRAGMA [database.]synchronous
102147   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
102148   **
102149   ** Return or set the local value of the synchronous flag.  Changing
102150   ** the local value does not make changes to the disk file and the
102151   ** default value will be restored the next time the database is
102152   ** opened.
102153   */
102154   case PragTyp_SYNCHRONOUS: {
102155     if( !zRight ){
102156       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
102157     }else{
102158       if( !db->autoCommit ){
102159         sqlite3ErrorMsg(pParse,
102160             "Safety level may not be changed inside a transaction");
102161       }else{
102162         pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
102163         setAllPagerFlags(db);
102164       }
102165     }
102166     break;
102167   }
102168 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
102169 
102170 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
102171   case PragTyp_FLAG: {
102172     if( zRight==0 ){
102173       returnSingleInt(pParse, aPragmaNames[mid].zName,
102174                      (db->flags & aPragmaNames[mid].iArg)!=0 );
102175     }else{
102176       int mask = aPragmaNames[mid].iArg;    /* Mask of bits to set or clear. */
102177       if( db->autoCommit==0 ){
102178         /* Foreign key support may not be enabled or disabled while not
102179         ** in auto-commit mode.  */
102180         mask &= ~(SQLITE_ForeignKeys);
102181       }
102182 #if SQLITE_USER_AUTHENTICATION
102183       if( db->auth.authLevel==UAUTH_User ){
102184         /* Do not allow non-admin users to modify the schema arbitrarily */
102185         mask &= ~(SQLITE_WriteSchema);
102186       }
102187 #endif
102188 
102189       if( sqlite3GetBoolean(zRight, 0) ){
102190         db->flags |= mask;
102191       }else{
102192         db->flags &= ~mask;
102193         if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
102194       }
102195 
102196       /* Many of the flag-pragmas modify the code generated by the SQL
102197       ** compiler (eg. count_changes). So add an opcode to expire all
102198       ** compiled SQL statements after modifying a pragma value.
102199       */
102200       sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
102201       setAllPagerFlags(db);
102202     }
102203     break;
102204   }
102205 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
102206 
102207 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
102208   /*
102209   **   PRAGMA table_info(<table>)
102210   **
102211   ** Return a single row for each column of the named table. The columns of
102212   ** the returned data set are:
102213   **
102214   ** cid:        Column id (numbered from left to right, starting at 0)
102215   ** name:       Column name
102216   ** type:       Column declaration type.
102217   ** notnull:    True if 'NOT NULL' is part of column declaration
102218   ** dflt_value: The default value for the column, if any.
102219   */
102220   case PragTyp_TABLE_INFO: if( zRight ){
102221     Table *pTab;
102222     pTab = sqlite3FindTable(db, zRight, zDb);
102223     if( pTab ){
102224       int i, k;
102225       int nHidden = 0;
102226       Column *pCol;
102227       Index *pPk = sqlite3PrimaryKeyIndex(pTab);
102228       sqlite3VdbeSetNumCols(v, 6);
102229       pParse->nMem = 6;
102230       sqlite3CodeVerifySchema(pParse, iDb);
102231       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
102232       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
102233       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
102234       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
102235       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
102236       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
102237       sqlite3ViewGetColumnNames(pParse, pTab);
102238       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
102239         if( IsHiddenColumn(pCol) ){
102240           nHidden++;
102241           continue;
102242         }
102243         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
102244         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
102245         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
102246            pCol->zType ? pCol->zType : "", 0);
102247         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
102248         if( pCol->zDflt ){
102249           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
102250         }else{
102251           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
102252         }
102253         if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
102254           k = 0;
102255         }else if( pPk==0 ){
102256           k = 1;
102257         }else{
102258           for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){}
102259         }
102260         sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
102261         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
102262       }
102263     }
102264   }
102265   break;
102266 
102267   case PragTyp_STATS: {
102268     Index *pIdx;
102269     HashElem *i;
102270     v = sqlite3GetVdbe(pParse);
102271     sqlite3VdbeSetNumCols(v, 4);
102272     pParse->nMem = 4;
102273     sqlite3CodeVerifySchema(pParse, iDb);
102274     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
102275     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "index", SQLITE_STATIC);
102276     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "width", SQLITE_STATIC);
102277     sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "height", SQLITE_STATIC);
102278     for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
102279       Table *pTab = sqliteHashData(i);
102280       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, pTab->zName, 0);
102281       sqlite3VdbeAddOp2(v, OP_Null, 0, 2);
102282       sqlite3VdbeAddOp2(v, OP_Integer,
102283                            (int)sqlite3LogEstToInt(pTab->szTabRow), 3);
102284       sqlite3VdbeAddOp2(v, OP_Integer,
102285           (int)sqlite3LogEstToInt(pTab->nRowLogEst), 4);
102286       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
102287       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102288         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
102289         sqlite3VdbeAddOp2(v, OP_Integer,
102290                              (int)sqlite3LogEstToInt(pIdx->szIdxRow), 3);
102291         sqlite3VdbeAddOp2(v, OP_Integer,
102292             (int)sqlite3LogEstToInt(pIdx->aiRowLogEst[0]), 4);
102293         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
102294       }
102295     }
102296   }
102297   break;
102298 
102299   case PragTyp_INDEX_INFO: if( zRight ){
102300     Index *pIdx;
102301     Table *pTab;
102302     pIdx = sqlite3FindIndex(db, zRight, zDb);
102303     if( pIdx ){
102304       int i;
102305       pTab = pIdx->pTable;
102306       sqlite3VdbeSetNumCols(v, 3);
102307       pParse->nMem = 3;
102308       sqlite3CodeVerifySchema(pParse, iDb);
102309       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
102310       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
102311       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
102312       for(i=0; i<pIdx->nKeyCol; i++){
102313         i16 cnum = pIdx->aiColumn[i];
102314         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
102315         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
102316         assert( pTab->nCol>cnum );
102317         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
102318         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
102319       }
102320     }
102321   }
102322   break;
102323 
102324   case PragTyp_INDEX_LIST: if( zRight ){
102325     Index *pIdx;
102326     Table *pTab;
102327     int i;
102328     pTab = sqlite3FindTable(db, zRight, zDb);
102329     if( pTab ){
102330       v = sqlite3GetVdbe(pParse);
102331       sqlite3VdbeSetNumCols(v, 3);
102332       pParse->nMem = 3;
102333       sqlite3CodeVerifySchema(pParse, iDb);
102334       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
102335       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
102336       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
102337       for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
102338         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
102339         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
102340         sqlite3VdbeAddOp2(v, OP_Integer, IsUniqueIndex(pIdx), 3);
102341         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
102342       }
102343     }
102344   }
102345   break;
102346 
102347   case PragTyp_DATABASE_LIST: {
102348     int i;
102349     sqlite3VdbeSetNumCols(v, 3);
102350     pParse->nMem = 3;
102351     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
102352     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
102353     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
102354     for(i=0; i<db->nDb; i++){
102355       if( db->aDb[i].pBt==0 ) continue;
102356       assert( db->aDb[i].zName!=0 );
102357       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
102358       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
102359       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
102360            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
102361       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
102362     }
102363   }
102364   break;
102365 
102366   case PragTyp_COLLATION_LIST: {
102367     int i = 0;
102368     HashElem *p;
102369     sqlite3VdbeSetNumCols(v, 2);
102370     pParse->nMem = 2;
102371     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
102372     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
102373     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
102374       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
102375       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
102376       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
102377       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
102378     }
102379   }
102380   break;
102381 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
102382 
102383 #ifndef SQLITE_OMIT_FOREIGN_KEY
102384   case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
102385     FKey *pFK;
102386     Table *pTab;
102387     pTab = sqlite3FindTable(db, zRight, zDb);
102388     if( pTab ){
102389       v = sqlite3GetVdbe(pParse);
102390       pFK = pTab->pFKey;
102391       if( pFK ){
102392         int i = 0;
102393         sqlite3VdbeSetNumCols(v, 8);
102394         pParse->nMem = 8;
102395         sqlite3CodeVerifySchema(pParse, iDb);
102396         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
102397         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
102398         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
102399         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
102400         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
102401         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
102402         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
102403         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
102404         while(pFK){
102405           int j;
102406           for(j=0; j<pFK->nCol; j++){
102407             char *zCol = pFK->aCol[j].zCol;
102408             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
102409             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
102410             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
102411             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
102412             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
102413             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
102414                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
102415             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
102416             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
102417             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
102418             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
102419             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
102420           }
102421           ++i;
102422           pFK = pFK->pNextFrom;
102423         }
102424       }
102425     }
102426   }
102427   break;
102428 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
102429 
102430 #ifndef SQLITE_OMIT_FOREIGN_KEY
102431 #ifndef SQLITE_OMIT_TRIGGER
102432   case PragTyp_FOREIGN_KEY_CHECK: {
102433     FKey *pFK;             /* A foreign key constraint */
102434     Table *pTab;           /* Child table contain "REFERENCES" keyword */
102435     Table *pParent;        /* Parent table that child points to */
102436     Index *pIdx;           /* Index in the parent table */
102437     int i;                 /* Loop counter:  Foreign key number for pTab */
102438     int j;                 /* Loop counter:  Field of the foreign key */
102439     HashElem *k;           /* Loop counter:  Next table in schema */
102440     int x;                 /* result variable */
102441     int regResult;         /* 3 registers to hold a result row */
102442     int regKey;            /* Register to hold key for checking the FK */
102443     int regRow;            /* Registers to hold a row from pTab */
102444     int addrTop;           /* Top of a loop checking foreign keys */
102445     int addrOk;            /* Jump here if the key is OK */
102446     int *aiCols;           /* child to parent column mapping */
102447 
102448     regResult = pParse->nMem+1;
102449     pParse->nMem += 4;
102450     regKey = ++pParse->nMem;
102451     regRow = ++pParse->nMem;
102452     v = sqlite3GetVdbe(pParse);
102453     sqlite3VdbeSetNumCols(v, 4);
102454     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
102455     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
102456     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
102457     sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
102458     sqlite3CodeVerifySchema(pParse, iDb);
102459     k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
102460     while( k ){
102461       if( zRight ){
102462         pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
102463         k = 0;
102464       }else{
102465         pTab = (Table*)sqliteHashData(k);
102466         k = sqliteHashNext(k);
102467       }
102468       if( pTab==0 || pTab->pFKey==0 ) continue;
102469       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
102470       if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
102471       sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
102472       sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
102473                         P4_TRANSIENT);
102474       for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
102475         pParent = sqlite3FindTable(db, pFK->zTo, zDb);
102476         if( pParent==0 ) continue;
102477         pIdx = 0;
102478         sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
102479         x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
102480         if( x==0 ){
102481           if( pIdx==0 ){
102482             sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
102483           }else{
102484             sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
102485             sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
102486           }
102487         }else{
102488           k = 0;
102489           break;
102490         }
102491       }
102492       assert( pParse->nErr>0 || pFK==0 );
102493       if( pFK ) break;
102494       if( pParse->nTab<i ) pParse->nTab = i;
102495       addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
102496       for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
102497         pParent = sqlite3FindTable(db, pFK->zTo, zDb);
102498         pIdx = 0;
102499         aiCols = 0;
102500         if( pParent ){
102501           x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
102502           assert( x==0 );
102503         }
102504         addrOk = sqlite3VdbeMakeLabel(v);
102505         if( pParent && pIdx==0 ){
102506           int iKey = pFK->aCol[0].iFrom;
102507           assert( iKey>=0 && iKey<pTab->nCol );
102508           if( iKey!=pTab->iPKey ){
102509             sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
102510             sqlite3ColumnDefault(v, pTab, iKey, regRow);
102511             sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
102512             sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
102513                sqlite3VdbeCurrentAddr(v)+3); VdbeCoverage(v);
102514           }else{
102515             sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
102516           }
102517           sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow); VdbeCoverage(v);
102518           sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
102519           sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
102520         }else{
102521           for(j=0; j<pFK->nCol; j++){
102522             sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
102523                             aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
102524             sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
102525           }
102526           if( pParent ){
102527             sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
102528                               sqlite3IndexAffinityStr(v,pIdx), pFK->nCol);
102529             sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
102530             VdbeCoverage(v);
102531           }
102532         }
102533         sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
102534         sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0,
102535                           pFK->zTo, P4_TRANSIENT);
102536         sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
102537         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
102538         sqlite3VdbeResolveLabel(v, addrOk);
102539         sqlite3DbFree(db, aiCols);
102540       }
102541       sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
102542       sqlite3VdbeJumpHere(v, addrTop);
102543     }
102544   }
102545   break;
102546 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
102547 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
102548 
102549 #ifndef NDEBUG
102550   case PragTyp_PARSER_TRACE: {
102551     if( zRight ){
102552       if( sqlite3GetBoolean(zRight, 0) ){
102553         sqlite3ParserTrace(stderr, "parser: ");
102554       }else{
102555         sqlite3ParserTrace(0, 0);
102556       }
102557     }
102558   }
102559   break;
102560 #endif
102561 
102562   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
102563   ** used will be case sensitive or not depending on the RHS.
102564   */
102565   case PragTyp_CASE_SENSITIVE_LIKE: {
102566     if( zRight ){
102567       sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
102568     }
102569   }
102570   break;
102571 
102572 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
102573 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
102574 #endif
102575 
102576 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
102577   /* Pragma "quick_check" is reduced version of
102578   ** integrity_check designed to detect most database corruption
102579   ** without most of the overhead of a full integrity-check.
102580   */
102581   case PragTyp_INTEGRITY_CHECK: {
102582     int i, j, addr, mxErr;
102583 
102584     /* Code that appears at the end of the integrity check.  If no error
102585     ** messages have been generated, output OK.  Otherwise output the
102586     ** error message
102587     */
102588     static const int iLn = VDBE_OFFSET_LINENO(2);
102589     static const VdbeOpList endCode[] = {
102590       { OP_IfNeg,       1, 0,        0},    /* 0 */
102591       { OP_String8,     0, 3,        0},    /* 1 */
102592       { OP_ResultRow,   3, 1,        0},
102593     };
102594 
102595     int isQuick = (sqlite3Tolower(zLeft[0])=='q');
102596 
102597     /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
102598     ** then iDb is set to the index of the database identified by <db>.
102599     ** In this case, the integrity of database iDb only is verified by
102600     ** the VDBE created below.
102601     **
102602     ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
102603     ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
102604     ** to -1 here, to indicate that the VDBE should verify the integrity
102605     ** of all attached databases.  */
102606     assert( iDb>=0 );
102607     assert( iDb==0 || pId2->z );
102608     if( pId2->z==0 ) iDb = -1;
102609 
102610     /* Initialize the VDBE program */
102611     pParse->nMem = 6;
102612     sqlite3VdbeSetNumCols(v, 1);
102613     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
102614 
102615     /* Set the maximum error count */
102616     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
102617     if( zRight ){
102618       sqlite3GetInt32(zRight, &mxErr);
102619       if( mxErr<=0 ){
102620         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
102621       }
102622     }
102623     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
102624 
102625     /* Do an integrity check on each database file */
102626     for(i=0; i<db->nDb; i++){
102627       HashElem *x;
102628       Hash *pTbls;
102629       int cnt = 0;
102630 
102631       if( OMIT_TEMPDB && i==1 ) continue;
102632       if( iDb>=0 && i!=iDb ) continue;
102633 
102634       sqlite3CodeVerifySchema(pParse, i);
102635       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
102636       VdbeCoverage(v);
102637       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
102638       sqlite3VdbeJumpHere(v, addr);
102639 
102640       /* Do an integrity check of the B-Tree
102641       **
102642       ** Begin by filling registers 2, 3, ... with the root pages numbers
102643       ** for all tables and indices in the database.
102644       */
102645       assert( sqlite3SchemaMutexHeld(db, i, 0) );
102646       pTbls = &db->aDb[i].pSchema->tblHash;
102647       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
102648         Table *pTab = sqliteHashData(x);
102649         Index *pIdx;
102650         if( HasRowid(pTab) ){
102651           sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
102652           VdbeComment((v, "%s", pTab->zName));
102653           cnt++;
102654         }
102655         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102656           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
102657           VdbeComment((v, "%s", pIdx->zName));
102658           cnt++;
102659         }
102660       }
102661 
102662       /* Make sure sufficient number of registers have been allocated */
102663       pParse->nMem = MAX( pParse->nMem, cnt+8 );
102664 
102665       /* Do the b-tree integrity checks */
102666       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
102667       sqlite3VdbeChangeP5(v, (u8)i);
102668       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
102669       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
102670          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
102671          P4_DYNAMIC);
102672       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
102673       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
102674       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
102675       sqlite3VdbeJumpHere(v, addr);
102676 
102677       /* Make sure all the indices are constructed correctly.
102678       */
102679       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
102680         Table *pTab = sqliteHashData(x);
102681         Index *pIdx, *pPk;
102682         Index *pPrior = 0;
102683         int loopTop;
102684         int iDataCur, iIdxCur;
102685         int r1 = -1;
102686 
102687         if( pTab->pIndex==0 ) continue;
102688         pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
102689         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
102690         VdbeCoverage(v);
102691         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
102692         sqlite3VdbeJumpHere(v, addr);
102693         sqlite3ExprCacheClear(pParse);
102694         sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead,
102695                                    1, 0, &iDataCur, &iIdxCur);
102696         sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
102697         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
102698           sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
102699         }
102700         pParse->nMem = MAX(pParse->nMem, 8+j);
102701         sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
102702         loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
102703         /* Verify that all NOT NULL columns really are NOT NULL */
102704         for(j=0; j<pTab->nCol; j++){
102705           char *zErr;
102706           int jmp2, jmp3;
102707           if( j==pTab->iPKey ) continue;
102708           if( pTab->aCol[j].notNull==0 ) continue;
102709           sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
102710           sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
102711           jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
102712           sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
102713           zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
102714                               pTab->aCol[j].zName);
102715           sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
102716           sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
102717           jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
102718           sqlite3VdbeAddOp0(v, OP_Halt);
102719           sqlite3VdbeJumpHere(v, jmp2);
102720           sqlite3VdbeJumpHere(v, jmp3);
102721         }
102722         /* Validate index entries for the current row */
102723         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
102724           int jmp2, jmp3, jmp4, jmp5;
102725           int ckUniq = sqlite3VdbeMakeLabel(v);
102726           if( pPk==pIdx ) continue;
102727           r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
102728                                        pPrior, r1);
102729           pPrior = pIdx;
102730           sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);  /* increment entry count */
102731           /* Verify that an index entry exists for the current table row */
102732           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
102733                                       pIdx->nColumn); VdbeCoverage(v);
102734           sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
102735           sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, "row ", P4_STATIC);
102736           sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
102737           sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
102738                             " missing from index ", P4_STATIC);
102739           sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
102740           jmp5 = sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
102741                                    pIdx->zName, P4_TRANSIENT);
102742           sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
102743           sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
102744           jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
102745           sqlite3VdbeAddOp0(v, OP_Halt);
102746           sqlite3VdbeJumpHere(v, jmp2);
102747           /* For UNIQUE indexes, verify that only one entry exists with the
102748           ** current key.  The entry is unique if (1) any column is NULL
102749           ** or (2) the next entry has a different key */
102750           if( IsUniqueIndex(pIdx) ){
102751             int uniqOk = sqlite3VdbeMakeLabel(v);
102752             int jmp6;
102753             int kk;
102754             for(kk=0; kk<pIdx->nKeyCol; kk++){
102755               int iCol = pIdx->aiColumn[kk];
102756               assert( iCol>=0 && iCol<pTab->nCol );
102757               if( pTab->aCol[iCol].notNull ) continue;
102758               sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
102759               VdbeCoverage(v);
102760             }
102761             jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
102762             sqlite3VdbeAddOp2(v, OP_Goto, 0, uniqOk);
102763             sqlite3VdbeJumpHere(v, jmp6);
102764             sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
102765                                  pIdx->nKeyCol); VdbeCoverage(v);
102766             sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
102767             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
102768                               "non-unique entry in index ", P4_STATIC);
102769             sqlite3VdbeAddOp2(v, OP_Goto, 0, jmp5);
102770             sqlite3VdbeResolveLabel(v, uniqOk);
102771           }
102772           sqlite3VdbeJumpHere(v, jmp4);
102773           sqlite3ResolvePartIdxLabel(pParse, jmp3);
102774         }
102775         sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
102776         sqlite3VdbeJumpHere(v, loopTop-1);
102777 #ifndef SQLITE_OMIT_BTREECOUNT
102778         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0,
102779                      "wrong # of entries in index ", P4_STATIC);
102780         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
102781           if( pPk==pIdx ) continue;
102782           addr = sqlite3VdbeCurrentAddr(v);
102783           sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
102784           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
102785           sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
102786           sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
102787           sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
102788           sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
102789           sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT);
102790           sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
102791           sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
102792         }
102793 #endif /* SQLITE_OMIT_BTREECOUNT */
102794       }
102795     }
102796     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
102797     sqlite3VdbeChangeP3(v, addr, -mxErr);
102798     sqlite3VdbeJumpHere(v, addr);
102799     sqlite3VdbeChangeP4(v, addr+1, "ok", P4_STATIC);
102800   }
102801   break;
102802 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
102803 
102804 #ifndef SQLITE_OMIT_UTF16
102805   /*
102806   **   PRAGMA encoding
102807   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
102808   **
102809   ** In its first form, this pragma returns the encoding of the main
102810   ** database. If the database is not initialized, it is initialized now.
102811   **
102812   ** The second form of this pragma is a no-op if the main database file
102813   ** has not already been initialized. In this case it sets the default
102814   ** encoding that will be used for the main database file if a new file
102815   ** is created. If an existing main database file is opened, then the
102816   ** default text encoding for the existing database is used.
102817   **
102818   ** In all cases new databases created using the ATTACH command are
102819   ** created to use the same default text encoding as the main database. If
102820   ** the main database has not been initialized and/or created when ATTACH
102821   ** is executed, this is done before the ATTACH operation.
102822   **
102823   ** In the second form this pragma sets the text encoding to be used in
102824   ** new database files created using this database handle. It is only
102825   ** useful if invoked immediately after the main database i
102826   */
102827   case PragTyp_ENCODING: {
102828     static const struct EncName {
102829       char *zName;
102830       u8 enc;
102831     } encnames[] = {
102832       { "UTF8",     SQLITE_UTF8        },
102833       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
102834       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
102835       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
102836       { "UTF16le",  SQLITE_UTF16LE     },
102837       { "UTF16be",  SQLITE_UTF16BE     },
102838       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
102839       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
102840       { 0, 0 }
102841     };
102842     const struct EncName *pEnc;
102843     if( !zRight ){    /* "PRAGMA encoding" */
102844       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
102845       sqlite3VdbeSetNumCols(v, 1);
102846       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
102847       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
102848       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
102849       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
102850       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
102851       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
102852       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
102853     }else{                        /* "PRAGMA encoding = XXX" */
102854       /* Only change the value of sqlite.enc if the database handle is not
102855       ** initialized. If the main database exists, the new sqlite.enc value
102856       ** will be overwritten when the schema is next loaded. If it does not
102857       ** already exists, it will be created to use the new encoding value.
102858       */
102859       if(
102860         !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
102861         DbHasProperty(db, 0, DB_Empty)
102862       ){
102863         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
102864           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
102865             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
102866             break;
102867           }
102868         }
102869         if( !pEnc->zName ){
102870           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
102871         }
102872       }
102873     }
102874   }
102875   break;
102876 #endif /* SQLITE_OMIT_UTF16 */
102877 
102878 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
102879   /*
102880   **   PRAGMA [database.]schema_version
102881   **   PRAGMA [database.]schema_version = <integer>
102882   **
102883   **   PRAGMA [database.]user_version
102884   **   PRAGMA [database.]user_version = <integer>
102885   **
102886   **   PRAGMA [database.]freelist_count = <integer>
102887   **
102888   **   PRAGMA [database.]application_id
102889   **   PRAGMA [database.]application_id = <integer>
102890   **
102891   ** The pragma's schema_version and user_version are used to set or get
102892   ** the value of the schema-version and user-version, respectively. Both
102893   ** the schema-version and the user-version are 32-bit signed integers
102894   ** stored in the database header.
102895   **
102896   ** The schema-cookie is usually only manipulated internally by SQLite. It
102897   ** is incremented by SQLite whenever the database schema is modified (by
102898   ** creating or dropping a table or index). The schema version is used by
102899   ** SQLite each time a query is executed to ensure that the internal cache
102900   ** of the schema used when compiling the SQL query matches the schema of
102901   ** the database against which the compiled query is actually executed.
102902   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
102903   ** the schema-version is potentially dangerous and may lead to program
102904   ** crashes or database corruption. Use with caution!
102905   **
102906   ** The user-version is not used internally by SQLite. It may be used by
102907   ** applications for any purpose.
102908   */
102909   case PragTyp_HEADER_VALUE: {
102910     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
102911     sqlite3VdbeUsesBtree(v, iDb);
102912     switch( zLeft[0] ){
102913       case 'a': case 'A':
102914         iCookie = BTREE_APPLICATION_ID;
102915         break;
102916       case 'f': case 'F':
102917         iCookie = BTREE_FREE_PAGE_COUNT;
102918         break;
102919       case 's': case 'S':
102920         iCookie = BTREE_SCHEMA_VERSION;
102921         break;
102922       default:
102923         iCookie = BTREE_USER_VERSION;
102924         break;
102925     }
102926 
102927     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
102928       /* Write the specified cookie value */
102929       static const VdbeOpList setCookie[] = {
102930         { OP_Transaction,    0,  1,  0},    /* 0 */
102931         { OP_Integer,        0,  1,  0},    /* 1 */
102932         { OP_SetCookie,      0,  0,  1},    /* 2 */
102933       };
102934       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
102935       sqlite3VdbeChangeP1(v, addr, iDb);
102936       sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
102937       sqlite3VdbeChangeP1(v, addr+2, iDb);
102938       sqlite3VdbeChangeP2(v, addr+2, iCookie);
102939     }else{
102940       /* Read the specified cookie value */
102941       static const VdbeOpList readCookie[] = {
102942         { OP_Transaction,     0,  0,  0},    /* 0 */
102943         { OP_ReadCookie,      0,  1,  0},    /* 1 */
102944         { OP_ResultRow,       1,  1,  0}
102945       };
102946       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie, 0);
102947       sqlite3VdbeChangeP1(v, addr, iDb);
102948       sqlite3VdbeChangeP1(v, addr+1, iDb);
102949       sqlite3VdbeChangeP3(v, addr+1, iCookie);
102950       sqlite3VdbeSetNumCols(v, 1);
102951       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
102952     }
102953   }
102954   break;
102955 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
102956 
102957 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
102958   /*
102959   **   PRAGMA compile_options
102960   **
102961   ** Return the names of all compile-time options used in this build,
102962   ** one option per row.
102963   */
102964   case PragTyp_COMPILE_OPTIONS: {
102965     int i = 0;
102966     const char *zOpt;
102967     sqlite3VdbeSetNumCols(v, 1);
102968     pParse->nMem = 1;
102969     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
102970     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
102971       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
102972       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
102973     }
102974   }
102975   break;
102976 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
102977 
102978 #ifndef SQLITE_OMIT_WAL
102979   /*
102980   **   PRAGMA [database.]wal_checkpoint = passive|full|restart
102981   **
102982   ** Checkpoint the database.
102983   */
102984   case PragTyp_WAL_CHECKPOINT: {
102985     int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
102986     int eMode = SQLITE_CHECKPOINT_PASSIVE;
102987     if( zRight ){
102988       if( sqlite3StrICmp(zRight, "full")==0 ){
102989         eMode = SQLITE_CHECKPOINT_FULL;
102990       }else if( sqlite3StrICmp(zRight, "restart")==0 ){
102991         eMode = SQLITE_CHECKPOINT_RESTART;
102992       }
102993     }
102994     sqlite3VdbeSetNumCols(v, 3);
102995     pParse->nMem = 3;
102996     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
102997     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
102998     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
102999 
103000     sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
103001     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
103002   }
103003   break;
103004 
103005   /*
103006   **   PRAGMA wal_autocheckpoint
103007   **   PRAGMA wal_autocheckpoint = N
103008   **
103009   ** Configure a database connection to automatically checkpoint a database
103010   ** after accumulating N frames in the log. Or query for the current value
103011   ** of N.
103012   */
103013   case PragTyp_WAL_AUTOCHECKPOINT: {
103014     if( zRight ){
103015       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
103016     }
103017     returnSingleInt(pParse, "wal_autocheckpoint",
103018        db->xWalCallback==sqlite3WalDefaultHook ?
103019            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
103020   }
103021   break;
103022 #endif
103023 
103024   /*
103025   **  PRAGMA shrink_memory
103026   **
103027   ** This pragma attempts to free as much memory as possible from the
103028   ** current database connection.
103029   */
103030   case PragTyp_SHRINK_MEMORY: {
103031     sqlite3_db_release_memory(db);
103032     break;
103033   }
103034 
103035   /*
103036   **   PRAGMA busy_timeout
103037   **   PRAGMA busy_timeout = N
103038   **
103039   ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
103040   ** if one is set.  If no busy handler or a different busy handler is set
103041   ** then 0 is returned.  Setting the busy_timeout to 0 or negative
103042   ** disables the timeout.
103043   */
103044   /*case PragTyp_BUSY_TIMEOUT*/ default: {
103045     assert( aPragmaNames[mid].ePragTyp==PragTyp_BUSY_TIMEOUT );
103046     if( zRight ){
103047       sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
103048     }
103049     returnSingleInt(pParse, "timeout",  db->busyTimeout);
103050     break;
103051   }
103052 
103053   /*
103054   **   PRAGMA soft_heap_limit
103055   **   PRAGMA soft_heap_limit = N
103056   **
103057   ** Call sqlite3_soft_heap_limit64(N).  Return the result.  If N is omitted,
103058   ** use -1.
103059   */
103060   case PragTyp_SOFT_HEAP_LIMIT: {
103061     sqlite3_int64 N;
103062     if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
103063       sqlite3_soft_heap_limit64(N);
103064     }
103065     returnSingleInt(pParse, "soft_heap_limit",  sqlite3_soft_heap_limit64(-1));
103066     break;
103067   }
103068 
103069   /*
103070   **   PRAGMA threads
103071   **   PRAGMA threads = N
103072   **
103073   ** Configure the maximum number of worker threads.  Return the new
103074   ** maximum, which might be less than requested.
103075   */
103076   case PragTyp_THREADS: {
103077     sqlite3_int64 N;
103078     if( zRight
103079      && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
103080      && N>=0
103081     ){
103082       sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
103083     }
103084     returnSingleInt(pParse, "threads",
103085                     sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
103086     break;
103087   }
103088 
103089 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
103090   /*
103091   ** Report the current state of file logs for all databases
103092   */
103093   case PragTyp_LOCK_STATUS: {
103094     static const char *const azLockName[] = {
103095       "unlocked", "shared", "reserved", "pending", "exclusive"
103096     };
103097     int i;
103098     sqlite3VdbeSetNumCols(v, 2);
103099     pParse->nMem = 2;
103100     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
103101     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
103102     for(i=0; i<db->nDb; i++){
103103       Btree *pBt;
103104       const char *zState = "unknown";
103105       int j;
103106       if( db->aDb[i].zName==0 ) continue;
103107       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
103108       pBt = db->aDb[i].pBt;
103109       if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
103110         zState = "closed";
103111       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
103112                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
103113          zState = azLockName[j];
103114       }
103115       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
103116       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
103117     }
103118     break;
103119   }
103120 #endif
103121 
103122 #ifdef SQLITE_HAS_CODEC
103123   case PragTyp_KEY: {
103124     if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
103125     break;
103126   }
103127   case PragTyp_REKEY: {
103128     if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
103129     break;
103130   }
103131   case PragTyp_HEXKEY: {
103132     if( zRight ){
103133       u8 iByte;
103134       int i;
103135       char zKey[40];
103136       for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
103137         iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
103138         if( (i&1)!=0 ) zKey[i/2] = iByte;
103139       }
103140       if( (zLeft[3] & 0xf)==0xb ){
103141         sqlite3_key_v2(db, zDb, zKey, i/2);
103142       }else{
103143         sqlite3_rekey_v2(db, zDb, zKey, i/2);
103144       }
103145     }
103146     break;
103147   }
103148 #endif
103149 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
103150   case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
103151 #ifdef SQLITE_HAS_CODEC
103152     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
103153       sqlite3_activate_see(&zRight[4]);
103154     }
103155 #endif
103156 #ifdef SQLITE_ENABLE_CEROD
103157     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
103158       sqlite3_activate_cerod(&zRight[6]);
103159     }
103160 #endif
103161   }
103162   break;
103163 #endif
103164 
103165   } /* End of the PRAGMA switch */
103166 
103167 pragma_out:
103168   sqlite3DbFree(db, zLeft);
103169   sqlite3DbFree(db, zRight);
103170 }
103171 
103172 #endif /* SQLITE_OMIT_PRAGMA */
103173 
103174 /************** End of pragma.c **********************************************/
103175 /************** Begin file prepare.c *****************************************/
103176 /*
103177 ** 2005 May 25
103178 **
103179 ** The author disclaims copyright to this source code.  In place of
103180 ** a legal notice, here is a blessing:
103181 **
103182 **    May you do good and not evil.
103183 **    May you find forgiveness for yourself and forgive others.
103184 **    May you share freely, never taking more than you give.
103185 **
103186 *************************************************************************
103187 ** This file contains the implementation of the sqlite3_prepare()
103188 ** interface, and routines that contribute to loading the database schema
103189 ** from disk.
103190 */
103191 
103192 /*
103193 ** Fill the InitData structure with an error message that indicates
103194 ** that the database is corrupt.
103195 */
103196 static void corruptSchema(
103197   InitData *pData,     /* Initialization context */
103198   const char *zObj,    /* Object being parsed at the point of error */
103199   const char *zExtra   /* Error information */
103200 ){
103201   sqlite3 *db = pData->db;
103202   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
103203     if( zObj==0 ) zObj = "?";
103204     sqlite3SetString(pData->pzErrMsg, db,
103205       "malformed database schema (%s)", zObj);
103206     if( zExtra ){
103207       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
103208                                  "%s - %s", *pData->pzErrMsg, zExtra);
103209     }
103210   }
103211   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
103212 }
103213 
103214 /*
103215 ** This is the callback routine for the code that initializes the
103216 ** database.  See sqlite3Init() below for additional information.
103217 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
103218 **
103219 ** Each callback contains the following information:
103220 **
103221 **     argv[0] = name of thing being created
103222 **     argv[1] = root page number for table or index. 0 for trigger or view.
103223 **     argv[2] = SQL text for the CREATE statement.
103224 **
103225 */
103226 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
103227   InitData *pData = (InitData*)pInit;
103228   sqlite3 *db = pData->db;
103229   int iDb = pData->iDb;
103230 
103231   assert( argc==3 );
103232   UNUSED_PARAMETER2(NotUsed, argc);
103233   assert( sqlite3_mutex_held(db->mutex) );
103234   DbClearProperty(db, iDb, DB_Empty);
103235   if( db->mallocFailed ){
103236     corruptSchema(pData, argv[0], 0);
103237     return 1;
103238   }
103239 
103240   assert( iDb>=0 && iDb<db->nDb );
103241   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
103242   if( argv[1]==0 ){
103243     corruptSchema(pData, argv[0], 0);
103244   }else if( argv[2] && argv[2][0] ){
103245     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
103246     ** But because db->init.busy is set to 1, no VDBE code is generated
103247     ** or executed.  All the parser does is build the internal data
103248     ** structures that describe the table, index, or view.
103249     */
103250     int rc;
103251     sqlite3_stmt *pStmt;
103252     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
103253 
103254     assert( db->init.busy );
103255     db->init.iDb = iDb;
103256     db->init.newTnum = sqlite3Atoi(argv[1]);
103257     db->init.orphanTrigger = 0;
103258     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
103259     rc = db->errCode;
103260     assert( (rc&0xFF)==(rcp&0xFF) );
103261     db->init.iDb = 0;
103262     if( SQLITE_OK!=rc ){
103263       if( db->init.orphanTrigger ){
103264         assert( iDb==1 );
103265       }else{
103266         pData->rc = rc;
103267         if( rc==SQLITE_NOMEM ){
103268           db->mallocFailed = 1;
103269         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
103270           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
103271         }
103272       }
103273     }
103274     sqlite3_finalize(pStmt);
103275   }else if( argv[0]==0 ){
103276     corruptSchema(pData, 0, 0);
103277   }else{
103278     /* If the SQL column is blank it means this is an index that
103279     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
103280     ** constraint for a CREATE TABLE.  The index should have already
103281     ** been created when we processed the CREATE TABLE.  All we have
103282     ** to do here is record the root page number for that index.
103283     */
103284     Index *pIndex;
103285     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
103286     if( pIndex==0 ){
103287       /* This can occur if there exists an index on a TEMP table which
103288       ** has the same name as another index on a permanent index.  Since
103289       ** the permanent table is hidden by the TEMP table, we can also
103290       ** safely ignore the index on the permanent table.
103291       */
103292       /* Do Nothing */;
103293     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
103294       corruptSchema(pData, argv[0], "invalid rootpage");
103295     }
103296   }
103297   return 0;
103298 }
103299 
103300 /*
103301 ** Attempt to read the database schema and initialize internal
103302 ** data structures for a single database file.  The index of the
103303 ** database file is given by iDb.  iDb==0 is used for the main
103304 ** database.  iDb==1 should never be used.  iDb>=2 is used for
103305 ** auxiliary databases.  Return one of the SQLITE_ error codes to
103306 ** indicate success or failure.
103307 */
103308 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
103309   int rc;
103310   int i;
103311 #ifndef SQLITE_OMIT_DEPRECATED
103312   int size;
103313 #endif
103314   Table *pTab;
103315   Db *pDb;
103316   char const *azArg[4];
103317   int meta[5];
103318   InitData initData;
103319   char const *zMasterSchema;
103320   char const *zMasterName;
103321   int openedTransaction = 0;
103322 
103323   /*
103324   ** The master database table has a structure like this
103325   */
103326   static const char master_schema[] =
103327      "CREATE TABLE sqlite_master(\n"
103328      "  type text,\n"
103329      "  name text,\n"
103330      "  tbl_name text,\n"
103331      "  rootpage integer,\n"
103332      "  sql text\n"
103333      ")"
103334   ;
103335 #ifndef SQLITE_OMIT_TEMPDB
103336   static const char temp_master_schema[] =
103337      "CREATE TEMP TABLE sqlite_temp_master(\n"
103338      "  type text,\n"
103339      "  name text,\n"
103340      "  tbl_name text,\n"
103341      "  rootpage integer,\n"
103342      "  sql text\n"
103343      ")"
103344   ;
103345 #else
103346   #define temp_master_schema 0
103347 #endif
103348 
103349   assert( iDb>=0 && iDb<db->nDb );
103350   assert( db->aDb[iDb].pSchema );
103351   assert( sqlite3_mutex_held(db->mutex) );
103352   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
103353 
103354   /* zMasterSchema and zInitScript are set to point at the master schema
103355   ** and initialisation script appropriate for the database being
103356   ** initialized. zMasterName is the name of the master table.
103357   */
103358   if( !OMIT_TEMPDB && iDb==1 ){
103359     zMasterSchema = temp_master_schema;
103360   }else{
103361     zMasterSchema = master_schema;
103362   }
103363   zMasterName = SCHEMA_TABLE(iDb);
103364 
103365   /* Construct the schema tables.  */
103366   azArg[0] = zMasterName;
103367   azArg[1] = "1";
103368   azArg[2] = zMasterSchema;
103369   azArg[3] = 0;
103370   initData.db = db;
103371   initData.iDb = iDb;
103372   initData.rc = SQLITE_OK;
103373   initData.pzErrMsg = pzErrMsg;
103374   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
103375   if( initData.rc ){
103376     rc = initData.rc;
103377     goto error_out;
103378   }
103379   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
103380   if( ALWAYS(pTab) ){
103381     pTab->tabFlags |= TF_Readonly;
103382   }
103383 
103384   /* Create a cursor to hold the database open
103385   */
103386   pDb = &db->aDb[iDb];
103387   if( pDb->pBt==0 ){
103388     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
103389       DbSetProperty(db, 1, DB_SchemaLoaded);
103390     }
103391     return SQLITE_OK;
103392   }
103393 
103394   /* If there is not already a read-only (or read-write) transaction opened
103395   ** on the b-tree database, open one now. If a transaction is opened, it
103396   ** will be closed before this function returns.  */
103397   sqlite3BtreeEnter(pDb->pBt);
103398   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
103399     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
103400     if( rc!=SQLITE_OK ){
103401       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
103402       goto initone_error_out;
103403     }
103404     openedTransaction = 1;
103405   }
103406 
103407   /* Get the database meta information.
103408   **
103409   ** Meta values are as follows:
103410   **    meta[0]   Schema cookie.  Changes with each schema change.
103411   **    meta[1]   File format of schema layer.
103412   **    meta[2]   Size of the page cache.
103413   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
103414   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
103415   **    meta[5]   User version
103416   **    meta[6]   Incremental vacuum mode
103417   **    meta[7]   unused
103418   **    meta[8]   unused
103419   **    meta[9]   unused
103420   **
103421   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
103422   ** the possible values of meta[4].
103423   */
103424   for(i=0; i<ArraySize(meta); i++){
103425     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
103426   }
103427   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
103428 
103429   /* If opening a non-empty database, check the text encoding. For the
103430   ** main database, set sqlite3.enc to the encoding of the main database.
103431   ** For an attached db, it is an error if the encoding is not the same
103432   ** as sqlite3.enc.
103433   */
103434   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
103435     if( iDb==0 ){
103436 #ifndef SQLITE_OMIT_UTF16
103437       u8 encoding;
103438       /* If opening the main database, set ENC(db). */
103439       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
103440       if( encoding==0 ) encoding = SQLITE_UTF8;
103441       ENC(db) = encoding;
103442 #else
103443       ENC(db) = SQLITE_UTF8;
103444 #endif
103445     }else{
103446       /* If opening an attached database, the encoding much match ENC(db) */
103447       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
103448         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
103449             " text encoding as main database");
103450         rc = SQLITE_ERROR;
103451         goto initone_error_out;
103452       }
103453     }
103454   }else{
103455     DbSetProperty(db, iDb, DB_Empty);
103456   }
103457   pDb->pSchema->enc = ENC(db);
103458 
103459   if( pDb->pSchema->cache_size==0 ){
103460 #ifndef SQLITE_OMIT_DEPRECATED
103461     size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
103462     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
103463     pDb->pSchema->cache_size = size;
103464 #else
103465     pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
103466 #endif
103467     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
103468   }
103469 
103470   /*
103471   ** file_format==1    Version 3.0.0.
103472   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
103473   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
103474   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
103475   */
103476   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
103477   if( pDb->pSchema->file_format==0 ){
103478     pDb->pSchema->file_format = 1;
103479   }
103480   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
103481     sqlite3SetString(pzErrMsg, db, "unsupported file format");
103482     rc = SQLITE_ERROR;
103483     goto initone_error_out;
103484   }
103485 
103486   /* Ticket #2804:  When we open a database in the newer file format,
103487   ** clear the legacy_file_format pragma flag so that a VACUUM will
103488   ** not downgrade the database and thus invalidate any descending
103489   ** indices that the user might have created.
103490   */
103491   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
103492     db->flags &= ~SQLITE_LegacyFileFmt;
103493   }
103494 
103495   /* Read the schema information out of the schema tables
103496   */
103497   assert( db->init.busy );
103498   {
103499     char *zSql;
103500     zSql = sqlite3MPrintf(db,
103501         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
103502         db->aDb[iDb].zName, zMasterName);
103503 #ifndef SQLITE_OMIT_AUTHORIZATION
103504     {
103505       sqlite3_xauth xAuth;
103506       xAuth = db->xAuth;
103507       db->xAuth = 0;
103508 #endif
103509       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
103510 #ifndef SQLITE_OMIT_AUTHORIZATION
103511       db->xAuth = xAuth;
103512     }
103513 #endif
103514     if( rc==SQLITE_OK ) rc = initData.rc;
103515     sqlite3DbFree(db, zSql);
103516 #ifndef SQLITE_OMIT_ANALYZE
103517     if( rc==SQLITE_OK ){
103518       sqlite3AnalysisLoad(db, iDb);
103519     }
103520 #endif
103521   }
103522   if( db->mallocFailed ){
103523     rc = SQLITE_NOMEM;
103524     sqlite3ResetAllSchemasOfConnection(db);
103525   }
103526   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
103527     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
103528     ** the schema loaded, even if errors occurred. In this situation the
103529     ** current sqlite3_prepare() operation will fail, but the following one
103530     ** will attempt to compile the supplied statement against whatever subset
103531     ** of the schema was loaded before the error occurred. The primary
103532     ** purpose of this is to allow access to the sqlite_master table
103533     ** even when its contents have been corrupted.
103534     */
103535     DbSetProperty(db, iDb, DB_SchemaLoaded);
103536     rc = SQLITE_OK;
103537   }
103538 
103539   /* Jump here for an error that occurs after successfully allocating
103540   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
103541   ** before that point, jump to error_out.
103542   */
103543 initone_error_out:
103544   if( openedTransaction ){
103545     sqlite3BtreeCommit(pDb->pBt);
103546   }
103547   sqlite3BtreeLeave(pDb->pBt);
103548 
103549 error_out:
103550   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
103551     db->mallocFailed = 1;
103552   }
103553   return rc;
103554 }
103555 
103556 /*
103557 ** Initialize all database files - the main database file, the file
103558 ** used to store temporary tables, and any additional database files
103559 ** created using ATTACH statements.  Return a success code.  If an
103560 ** error occurs, write an error message into *pzErrMsg.
103561 **
103562 ** After a database is initialized, the DB_SchemaLoaded bit is set
103563 ** bit is set in the flags field of the Db structure. If the database
103564 ** file was of zero-length, then the DB_Empty flag is also set.
103565 */
103566 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
103567   int i, rc;
103568   int commit_internal = !(db->flags&SQLITE_InternChanges);
103569 
103570   assert( sqlite3_mutex_held(db->mutex) );
103571   assert( db->init.busy==0 );
103572   rc = SQLITE_OK;
103573   db->init.busy = 1;
103574   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
103575     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
103576     rc = sqlite3InitOne(db, i, pzErrMsg);
103577     if( rc ){
103578       sqlite3ResetOneSchema(db, i);
103579     }
103580   }
103581 
103582   /* Once all the other databases have been initialized, load the schema
103583   ** for the TEMP database. This is loaded last, as the TEMP database
103584   ** schema may contain references to objects in other databases.
103585   */
103586 #ifndef SQLITE_OMIT_TEMPDB
103587   assert( db->nDb>1 );
103588   if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
103589     rc = sqlite3InitOne(db, 1, pzErrMsg);
103590     if( rc ){
103591       sqlite3ResetOneSchema(db, 1);
103592     }
103593   }
103594 #endif
103595 
103596   db->init.busy = 0;
103597   if( rc==SQLITE_OK && commit_internal ){
103598     sqlite3CommitInternalChanges(db);
103599   }
103600 
103601   return rc;
103602 }
103603 
103604 /*
103605 ** This routine is a no-op if the database schema is already initialized.
103606 ** Otherwise, the schema is loaded. An error code is returned.
103607 */
103608 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
103609   int rc = SQLITE_OK;
103610   sqlite3 *db = pParse->db;
103611   assert( sqlite3_mutex_held(db->mutex) );
103612   if( !db->init.busy ){
103613     rc = sqlite3Init(db, &pParse->zErrMsg);
103614   }
103615   if( rc!=SQLITE_OK ){
103616     pParse->rc = rc;
103617     pParse->nErr++;
103618   }
103619   return rc;
103620 }
103621 
103622 
103623 /*
103624 ** Check schema cookies in all databases.  If any cookie is out
103625 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
103626 ** make no changes to pParse->rc.
103627 */
103628 static void schemaIsValid(Parse *pParse){
103629   sqlite3 *db = pParse->db;
103630   int iDb;
103631   int rc;
103632   int cookie;
103633 
103634   assert( pParse->checkSchema );
103635   assert( sqlite3_mutex_held(db->mutex) );
103636   for(iDb=0; iDb<db->nDb; iDb++){
103637     int openedTransaction = 0;         /* True if a transaction is opened */
103638     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
103639     if( pBt==0 ) continue;
103640 
103641     /* If there is not already a read-only (or read-write) transaction opened
103642     ** on the b-tree database, open one now. If a transaction is opened, it
103643     ** will be closed immediately after reading the meta-value. */
103644     if( !sqlite3BtreeIsInReadTrans(pBt) ){
103645       rc = sqlite3BtreeBeginTrans(pBt, 0);
103646       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
103647         db->mallocFailed = 1;
103648       }
103649       if( rc!=SQLITE_OK ) return;
103650       openedTransaction = 1;
103651     }
103652 
103653     /* Read the schema cookie from the database. If it does not match the
103654     ** value stored as part of the in-memory schema representation,
103655     ** set Parse.rc to SQLITE_SCHEMA. */
103656     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
103657     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
103658     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
103659       sqlite3ResetOneSchema(db, iDb);
103660       pParse->rc = SQLITE_SCHEMA;
103661     }
103662 
103663     /* Close the transaction, if one was opened. */
103664     if( openedTransaction ){
103665       sqlite3BtreeCommit(pBt);
103666     }
103667   }
103668 }
103669 
103670 /*
103671 ** Convert a schema pointer into the iDb index that indicates
103672 ** which database file in db->aDb[] the schema refers to.
103673 **
103674 ** If the same database is attached more than once, the first
103675 ** attached database is returned.
103676 */
103677 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
103678   int i = -1000000;
103679 
103680   /* If pSchema is NULL, then return -1000000. This happens when code in
103681   ** expr.c is trying to resolve a reference to a transient table (i.e. one
103682   ** created by a sub-select). In this case the return value of this
103683   ** function should never be used.
103684   **
103685   ** We return -1000000 instead of the more usual -1 simply because using
103686   ** -1000000 as the incorrect index into db->aDb[] is much
103687   ** more likely to cause a segfault than -1 (of course there are assert()
103688   ** statements too, but it never hurts to play the odds).
103689   */
103690   assert( sqlite3_mutex_held(db->mutex) );
103691   if( pSchema ){
103692     for(i=0; ALWAYS(i<db->nDb); i++){
103693       if( db->aDb[i].pSchema==pSchema ){
103694         break;
103695       }
103696     }
103697     assert( i>=0 && i<db->nDb );
103698   }
103699   return i;
103700 }
103701 
103702 /*
103703 ** Free all memory allocations in the pParse object
103704 */
103705 SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
103706   if( pParse ){
103707     sqlite3 *db = pParse->db;
103708     sqlite3DbFree(db, pParse->aLabel);
103709     sqlite3ExprListDelete(db, pParse->pConstExpr);
103710   }
103711 }
103712 
103713 /*
103714 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
103715 */
103716 static int sqlite3Prepare(
103717   sqlite3 *db,              /* Database handle. */
103718   const char *zSql,         /* UTF-8 encoded SQL statement. */
103719   int nBytes,               /* Length of zSql in bytes. */
103720   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
103721   Vdbe *pReprepare,         /* VM being reprepared */
103722   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
103723   const char **pzTail       /* OUT: End of parsed string */
103724 ){
103725   Parse *pParse;            /* Parsing context */
103726   char *zErrMsg = 0;        /* Error message */
103727   int rc = SQLITE_OK;       /* Result code */
103728   int i;                    /* Loop counter */
103729 
103730   /* Allocate the parsing context */
103731   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
103732   if( pParse==0 ){
103733     rc = SQLITE_NOMEM;
103734     goto end_prepare;
103735   }
103736   pParse->pReprepare = pReprepare;
103737   assert( ppStmt && *ppStmt==0 );
103738   assert( !db->mallocFailed );
103739   assert( sqlite3_mutex_held(db->mutex) );
103740 
103741   /* Check to verify that it is possible to get a read lock on all
103742   ** database schemas.  The inability to get a read lock indicates that
103743   ** some other database connection is holding a write-lock, which in
103744   ** turn means that the other connection has made uncommitted changes
103745   ** to the schema.
103746   **
103747   ** Were we to proceed and prepare the statement against the uncommitted
103748   ** schema changes and if those schema changes are subsequently rolled
103749   ** back and different changes are made in their place, then when this
103750   ** prepared statement goes to run the schema cookie would fail to detect
103751   ** the schema change.  Disaster would follow.
103752   **
103753   ** This thread is currently holding mutexes on all Btrees (because
103754   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
103755   ** is not possible for another thread to start a new schema change
103756   ** while this routine is running.  Hence, we do not need to hold
103757   ** locks on the schema, we just need to make sure nobody else is
103758   ** holding them.
103759   **
103760   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
103761   ** but it does *not* override schema lock detection, so this all still
103762   ** works even if READ_UNCOMMITTED is set.
103763   */
103764   for(i=0; i<db->nDb; i++) {
103765     Btree *pBt = db->aDb[i].pBt;
103766     if( pBt ){
103767       assert( sqlite3BtreeHoldsMutex(pBt) );
103768       rc = sqlite3BtreeSchemaLocked(pBt);
103769       if( rc ){
103770         const char *zDb = db->aDb[i].zName;
103771         sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
103772         testcase( db->flags & SQLITE_ReadUncommitted );
103773         goto end_prepare;
103774       }
103775     }
103776   }
103777 
103778   sqlite3VtabUnlockList(db);
103779 
103780   pParse->db = db;
103781   pParse->nQueryLoop = 0;  /* Logarithmic, so 0 really means 1 */
103782   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
103783     char *zSqlCopy;
103784     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
103785     testcase( nBytes==mxLen );
103786     testcase( nBytes==mxLen+1 );
103787     if( nBytes>mxLen ){
103788       sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
103789       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
103790       goto end_prepare;
103791     }
103792     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
103793     if( zSqlCopy ){
103794       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
103795       sqlite3DbFree(db, zSqlCopy);
103796       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
103797     }else{
103798       pParse->zTail = &zSql[nBytes];
103799     }
103800   }else{
103801     sqlite3RunParser(pParse, zSql, &zErrMsg);
103802   }
103803   assert( 0==pParse->nQueryLoop );
103804 
103805   if( db->mallocFailed ){
103806     pParse->rc = SQLITE_NOMEM;
103807   }
103808   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
103809   if( pParse->checkSchema ){
103810     schemaIsValid(pParse);
103811   }
103812   if( db->mallocFailed ){
103813     pParse->rc = SQLITE_NOMEM;
103814   }
103815   if( pzTail ){
103816     *pzTail = pParse->zTail;
103817   }
103818   rc = pParse->rc;
103819 
103820 #ifndef SQLITE_OMIT_EXPLAIN
103821   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
103822     static const char * const azColName[] = {
103823        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
103824        "selectid", "order", "from", "detail"
103825     };
103826     int iFirst, mx;
103827     if( pParse->explain==2 ){
103828       sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
103829       iFirst = 8;
103830       mx = 12;
103831     }else{
103832       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
103833       iFirst = 0;
103834       mx = 8;
103835     }
103836     for(i=iFirst; i<mx; i++){
103837       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
103838                             azColName[i], SQLITE_STATIC);
103839     }
103840   }
103841 #endif
103842 
103843   if( db->init.busy==0 ){
103844     Vdbe *pVdbe = pParse->pVdbe;
103845     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
103846   }
103847   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
103848     sqlite3VdbeFinalize(pParse->pVdbe);
103849     assert(!(*ppStmt));
103850   }else{
103851     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
103852   }
103853 
103854   if( zErrMsg ){
103855     sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
103856     sqlite3DbFree(db, zErrMsg);
103857   }else{
103858     sqlite3Error(db, rc);
103859   }
103860 
103861   /* Delete any TriggerPrg structures allocated while parsing this statement. */
103862   while( pParse->pTriggerPrg ){
103863     TriggerPrg *pT = pParse->pTriggerPrg;
103864     pParse->pTriggerPrg = pT->pNext;
103865     sqlite3DbFree(db, pT);
103866   }
103867 
103868 end_prepare:
103869 
103870   sqlite3ParserReset(pParse);
103871   sqlite3StackFree(db, pParse);
103872   rc = sqlite3ApiExit(db, rc);
103873   assert( (rc&db->errMask)==rc );
103874   return rc;
103875 }
103876 static int sqlite3LockAndPrepare(
103877   sqlite3 *db,              /* Database handle. */
103878   const char *zSql,         /* UTF-8 encoded SQL statement. */
103879   int nBytes,               /* Length of zSql in bytes. */
103880   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
103881   Vdbe *pOld,               /* VM being reprepared */
103882   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
103883   const char **pzTail       /* OUT: End of parsed string */
103884 ){
103885   int rc;
103886   assert( ppStmt!=0 );
103887   *ppStmt = 0;
103888   if( !sqlite3SafetyCheckOk(db) ){
103889     return SQLITE_MISUSE_BKPT;
103890   }
103891   sqlite3_mutex_enter(db->mutex);
103892   sqlite3BtreeEnterAll(db);
103893   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
103894   if( rc==SQLITE_SCHEMA ){
103895     sqlite3_finalize(*ppStmt);
103896     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
103897   }
103898   sqlite3BtreeLeaveAll(db);
103899   sqlite3_mutex_leave(db->mutex);
103900   assert( rc==SQLITE_OK || *ppStmt==0 );
103901   return rc;
103902 }
103903 
103904 /*
103905 ** Rerun the compilation of a statement after a schema change.
103906 **
103907 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
103908 ** if the statement cannot be recompiled because another connection has
103909 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
103910 ** occurs, return SQLITE_SCHEMA.
103911 */
103912 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
103913   int rc;
103914   sqlite3_stmt *pNew;
103915   const char *zSql;
103916   sqlite3 *db;
103917 
103918   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
103919   zSql = sqlite3_sql((sqlite3_stmt *)p);
103920   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
103921   db = sqlite3VdbeDb(p);
103922   assert( sqlite3_mutex_held(db->mutex) );
103923   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
103924   if( rc ){
103925     if( rc==SQLITE_NOMEM ){
103926       db->mallocFailed = 1;
103927     }
103928     assert( pNew==0 );
103929     return rc;
103930   }else{
103931     assert( pNew!=0 );
103932   }
103933   sqlite3VdbeSwap((Vdbe*)pNew, p);
103934   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
103935   sqlite3VdbeResetStepResult((Vdbe*)pNew);
103936   sqlite3VdbeFinalize((Vdbe*)pNew);
103937   return SQLITE_OK;
103938 }
103939 
103940 
103941 /*
103942 ** Two versions of the official API.  Legacy and new use.  In the legacy
103943 ** version, the original SQL text is not saved in the prepared statement
103944 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
103945 ** sqlite3_step().  In the new version, the original SQL text is retained
103946 ** and the statement is automatically recompiled if an schema change
103947 ** occurs.
103948 */
103949 SQLITE_API int sqlite3_prepare(
103950   sqlite3 *db,              /* Database handle. */
103951   const char *zSql,         /* UTF-8 encoded SQL statement. */
103952   int nBytes,               /* Length of zSql in bytes. */
103953   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
103954   const char **pzTail       /* OUT: End of parsed string */
103955 ){
103956   int rc;
103957   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
103958   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
103959   return rc;
103960 }
103961 SQLITE_API int sqlite3_prepare_v2(
103962   sqlite3 *db,              /* Database handle. */
103963   const char *zSql,         /* UTF-8 encoded SQL statement. */
103964   int nBytes,               /* Length of zSql in bytes. */
103965   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
103966   const char **pzTail       /* OUT: End of parsed string */
103967 ){
103968   int rc;
103969   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
103970   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
103971   return rc;
103972 }
103973 
103974 
103975 #ifndef SQLITE_OMIT_UTF16
103976 /*
103977 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
103978 */
103979 static int sqlite3Prepare16(
103980   sqlite3 *db,              /* Database handle. */
103981   const void *zSql,         /* UTF-16 encoded SQL statement. */
103982   int nBytes,               /* Length of zSql in bytes. */
103983   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
103984   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
103985   const void **pzTail       /* OUT: End of parsed string */
103986 ){
103987   /* This function currently works by first transforming the UTF-16
103988   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
103989   ** tricky bit is figuring out the pointer to return in *pzTail.
103990   */
103991   char *zSql8;
103992   const char *zTail8 = 0;
103993   int rc = SQLITE_OK;
103994 
103995   assert( ppStmt );
103996   *ppStmt = 0;
103997   if( !sqlite3SafetyCheckOk(db) ){
103998     return SQLITE_MISUSE_BKPT;
103999   }
104000   if( nBytes>=0 ){
104001     int sz;
104002     const char *z = (const char*)zSql;
104003     for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
104004     nBytes = sz;
104005   }
104006   sqlite3_mutex_enter(db->mutex);
104007   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
104008   if( zSql8 ){
104009     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
104010   }
104011 
104012   if( zTail8 && pzTail ){
104013     /* If sqlite3_prepare returns a tail pointer, we calculate the
104014     ** equivalent pointer into the UTF-16 string by counting the unicode
104015     ** characters between zSql8 and zTail8, and then returning a pointer
104016     ** the same number of characters into the UTF-16 string.
104017     */
104018     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
104019     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
104020   }
104021   sqlite3DbFree(db, zSql8);
104022   rc = sqlite3ApiExit(db, rc);
104023   sqlite3_mutex_leave(db->mutex);
104024   return rc;
104025 }
104026 
104027 /*
104028 ** Two versions of the official API.  Legacy and new use.  In the legacy
104029 ** version, the original SQL text is not saved in the prepared statement
104030 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
104031 ** sqlite3_step().  In the new version, the original SQL text is retained
104032 ** and the statement is automatically recompiled if an schema change
104033 ** occurs.
104034 */
104035 SQLITE_API int sqlite3_prepare16(
104036   sqlite3 *db,              /* Database handle. */
104037   const void *zSql,         /* UTF-16 encoded SQL statement. */
104038   int nBytes,               /* Length of zSql in bytes. */
104039   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
104040   const void **pzTail       /* OUT: End of parsed string */
104041 ){
104042   int rc;
104043   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
104044   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
104045   return rc;
104046 }
104047 SQLITE_API int sqlite3_prepare16_v2(
104048   sqlite3 *db,              /* Database handle. */
104049   const void *zSql,         /* UTF-16 encoded SQL statement. */
104050   int nBytes,               /* Length of zSql in bytes. */
104051   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
104052   const void **pzTail       /* OUT: End of parsed string */
104053 ){
104054   int rc;
104055   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
104056   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
104057   return rc;
104058 }
104059 
104060 #endif /* SQLITE_OMIT_UTF16 */
104061 
104062 /************** End of prepare.c *********************************************/
104063 /************** Begin file select.c ******************************************/
104064 /*
104065 ** 2001 September 15
104066 **
104067 ** The author disclaims copyright to this source code.  In place of
104068 ** a legal notice, here is a blessing:
104069 **
104070 **    May you do good and not evil.
104071 **    May you find forgiveness for yourself and forgive others.
104072 **    May you share freely, never taking more than you give.
104073 **
104074 *************************************************************************
104075 ** This file contains C code routines that are called by the parser
104076 ** to handle SELECT statements in SQLite.
104077 */
104078 
104079 /*
104080 ** Trace output macros
104081 */
104082 #if SELECTTRACE_ENABLED
104083 /***/ int sqlite3SelectTrace = 0;
104084 # define SELECTTRACE(K,P,S,X)  \
104085   if(sqlite3SelectTrace&(K))   \
104086     sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",(S)->zSelName,(S)),\
104087     sqlite3DebugPrintf X
104088 #else
104089 # define SELECTTRACE(K,P,S,X)
104090 #endif
104091 
104092 
104093 /*
104094 ** An instance of the following object is used to record information about
104095 ** how to process the DISTINCT keyword, to simplify passing that information
104096 ** into the selectInnerLoop() routine.
104097 */
104098 typedef struct DistinctCtx DistinctCtx;
104099 struct DistinctCtx {
104100   u8 isTnct;      /* True if the DISTINCT keyword is present */
104101   u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
104102   int tabTnct;    /* Ephemeral table used for DISTINCT processing */
104103   int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
104104 };
104105 
104106 /*
104107 ** An instance of the following object is used to record information about
104108 ** the ORDER BY (or GROUP BY) clause of query is being coded.
104109 */
104110 typedef struct SortCtx SortCtx;
104111 struct SortCtx {
104112   ExprList *pOrderBy;   /* The ORDER BY (or GROUP BY clause) */
104113   int nOBSat;           /* Number of ORDER BY terms satisfied by indices */
104114   int iECursor;         /* Cursor number for the sorter */
104115   int regReturn;        /* Register holding block-output return address */
104116   int labelBkOut;       /* Start label for the block-output subroutine */
104117   int addrSortIndex;    /* Address of the OP_SorterOpen or OP_OpenEphemeral */
104118   u8 sortFlags;         /* Zero or more SORTFLAG_* bits */
104119 };
104120 #define SORTFLAG_UseSorter  0x01   /* Use SorterOpen instead of OpenEphemeral */
104121 
104122 /*
104123 ** Delete all the content of a Select structure but do not deallocate
104124 ** the select structure itself.
104125 */
104126 static void clearSelect(sqlite3 *db, Select *p){
104127   sqlite3ExprListDelete(db, p->pEList);
104128   sqlite3SrcListDelete(db, p->pSrc);
104129   sqlite3ExprDelete(db, p->pWhere);
104130   sqlite3ExprListDelete(db, p->pGroupBy);
104131   sqlite3ExprDelete(db, p->pHaving);
104132   sqlite3ExprListDelete(db, p->pOrderBy);
104133   sqlite3SelectDelete(db, p->pPrior);
104134   sqlite3ExprDelete(db, p->pLimit);
104135   sqlite3ExprDelete(db, p->pOffset);
104136   sqlite3WithDelete(db, p->pWith);
104137 }
104138 
104139 /*
104140 ** Initialize a SelectDest structure.
104141 */
104142 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
104143   pDest->eDest = (u8)eDest;
104144   pDest->iSDParm = iParm;
104145   pDest->affSdst = 0;
104146   pDest->iSdst = 0;
104147   pDest->nSdst = 0;
104148 }
104149 
104150 
104151 /*
104152 ** Allocate a new Select structure and return a pointer to that
104153 ** structure.
104154 */
104155 SQLITE_PRIVATE Select *sqlite3SelectNew(
104156   Parse *pParse,        /* Parsing context */
104157   ExprList *pEList,     /* which columns to include in the result */
104158   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
104159   Expr *pWhere,         /* the WHERE clause */
104160   ExprList *pGroupBy,   /* the GROUP BY clause */
104161   Expr *pHaving,        /* the HAVING clause */
104162   ExprList *pOrderBy,   /* the ORDER BY clause */
104163   u16 selFlags,         /* Flag parameters, such as SF_Distinct */
104164   Expr *pLimit,         /* LIMIT value.  NULL means not used */
104165   Expr *pOffset         /* OFFSET value.  NULL means no offset */
104166 ){
104167   Select *pNew;
104168   Select standin;
104169   sqlite3 *db = pParse->db;
104170   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
104171   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
104172   if( pNew==0 ){
104173     assert( db->mallocFailed );
104174     pNew = &standin;
104175     memset(pNew, 0, sizeof(*pNew));
104176   }
104177   if( pEList==0 ){
104178     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
104179   }
104180   pNew->pEList = pEList;
104181   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
104182   pNew->pSrc = pSrc;
104183   pNew->pWhere = pWhere;
104184   pNew->pGroupBy = pGroupBy;
104185   pNew->pHaving = pHaving;
104186   pNew->pOrderBy = pOrderBy;
104187   pNew->selFlags = selFlags;
104188   pNew->op = TK_SELECT;
104189   pNew->pLimit = pLimit;
104190   pNew->pOffset = pOffset;
104191   assert( pOffset==0 || pLimit!=0 );
104192   pNew->addrOpenEphm[0] = -1;
104193   pNew->addrOpenEphm[1] = -1;
104194   if( db->mallocFailed ) {
104195     clearSelect(db, pNew);
104196     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
104197     pNew = 0;
104198   }else{
104199     assert( pNew->pSrc!=0 || pParse->nErr>0 );
104200   }
104201   assert( pNew!=&standin );
104202   return pNew;
104203 }
104204 
104205 #if SELECTTRACE_ENABLED
104206 /*
104207 ** Set the name of a Select object
104208 */
104209 SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
104210   if( p && zName ){
104211     sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
104212   }
104213 }
104214 #endif
104215 
104216 
104217 /*
104218 ** Delete the given Select structure and all of its substructures.
104219 */
104220 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
104221   if( p ){
104222     clearSelect(db, p);
104223     sqlite3DbFree(db, p);
104224   }
104225 }
104226 
104227 /*
104228 ** Return a pointer to the right-most SELECT statement in a compound.
104229 */
104230 static Select *findRightmost(Select *p){
104231   while( p->pNext ) p = p->pNext;
104232   return p;
104233 }
104234 
104235 /*
104236 ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
104237 ** type of join.  Return an integer constant that expresses that type
104238 ** in terms of the following bit values:
104239 **
104240 **     JT_INNER
104241 **     JT_CROSS
104242 **     JT_OUTER
104243 **     JT_NATURAL
104244 **     JT_LEFT
104245 **     JT_RIGHT
104246 **
104247 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
104248 **
104249 ** If an illegal or unsupported join type is seen, then still return
104250 ** a join type, but put an error in the pParse structure.
104251 */
104252 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
104253   int jointype = 0;
104254   Token *apAll[3];
104255   Token *p;
104256                              /*   0123456789 123456789 123456789 123 */
104257   static const char zKeyText[] = "naturaleftouterightfullinnercross";
104258   static const struct {
104259     u8 i;        /* Beginning of keyword text in zKeyText[] */
104260     u8 nChar;    /* Length of the keyword in characters */
104261     u8 code;     /* Join type mask */
104262   } aKeyword[] = {
104263     /* natural */ { 0,  7, JT_NATURAL                },
104264     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
104265     /* outer   */ { 10, 5, JT_OUTER                  },
104266     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
104267     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
104268     /* inner   */ { 23, 5, JT_INNER                  },
104269     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
104270   };
104271   int i, j;
104272   apAll[0] = pA;
104273   apAll[1] = pB;
104274   apAll[2] = pC;
104275   for(i=0; i<3 && apAll[i]; i++){
104276     p = apAll[i];
104277     for(j=0; j<ArraySize(aKeyword); j++){
104278       if( p->n==aKeyword[j].nChar
104279           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
104280         jointype |= aKeyword[j].code;
104281         break;
104282       }
104283     }
104284     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
104285     if( j>=ArraySize(aKeyword) ){
104286       jointype |= JT_ERROR;
104287       break;
104288     }
104289   }
104290   if(
104291      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
104292      (jointype & JT_ERROR)!=0
104293   ){
104294     const char *zSp = " ";
104295     assert( pB!=0 );
104296     if( pC==0 ){ zSp++; }
104297     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
104298        "%T %T%s%T", pA, pB, zSp, pC);
104299     jointype = JT_INNER;
104300   }else if( (jointype & JT_OUTER)!=0
104301          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
104302     sqlite3ErrorMsg(pParse,
104303       "RIGHT and FULL OUTER JOINs are not currently supported");
104304     jointype = JT_INNER;
104305   }
104306   return jointype;
104307 }
104308 
104309 /*
104310 ** Return the index of a column in a table.  Return -1 if the column
104311 ** is not contained in the table.
104312 */
104313 static int columnIndex(Table *pTab, const char *zCol){
104314   int i;
104315   for(i=0; i<pTab->nCol; i++){
104316     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
104317   }
104318   return -1;
104319 }
104320 
104321 /*
104322 ** Search the first N tables in pSrc, from left to right, looking for a
104323 ** table that has a column named zCol.
104324 **
104325 ** When found, set *piTab and *piCol to the table index and column index
104326 ** of the matching column and return TRUE.
104327 **
104328 ** If not found, return FALSE.
104329 */
104330 static int tableAndColumnIndex(
104331   SrcList *pSrc,       /* Array of tables to search */
104332   int N,               /* Number of tables in pSrc->a[] to search */
104333   const char *zCol,    /* Name of the column we are looking for */
104334   int *piTab,          /* Write index of pSrc->a[] here */
104335   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
104336 ){
104337   int i;               /* For looping over tables in pSrc */
104338   int iCol;            /* Index of column matching zCol */
104339 
104340   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
104341   for(i=0; i<N; i++){
104342     iCol = columnIndex(pSrc->a[i].pTab, zCol);
104343     if( iCol>=0 ){
104344       if( piTab ){
104345         *piTab = i;
104346         *piCol = iCol;
104347       }
104348       return 1;
104349     }
104350   }
104351   return 0;
104352 }
104353 
104354 /*
104355 ** This function is used to add terms implied by JOIN syntax to the
104356 ** WHERE clause expression of a SELECT statement. The new term, which
104357 ** is ANDed with the existing WHERE clause, is of the form:
104358 **
104359 **    (tab1.col1 = tab2.col2)
104360 **
104361 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
104362 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
104363 ** column iColRight of tab2.
104364 */
104365 static void addWhereTerm(
104366   Parse *pParse,                  /* Parsing context */
104367   SrcList *pSrc,                  /* List of tables in FROM clause */
104368   int iLeft,                      /* Index of first table to join in pSrc */
104369   int iColLeft,                   /* Index of column in first table */
104370   int iRight,                     /* Index of second table in pSrc */
104371   int iColRight,                  /* Index of column in second table */
104372   int isOuterJoin,                /* True if this is an OUTER join */
104373   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
104374 ){
104375   sqlite3 *db = pParse->db;
104376   Expr *pE1;
104377   Expr *pE2;
104378   Expr *pEq;
104379 
104380   assert( iLeft<iRight );
104381   assert( pSrc->nSrc>iRight );
104382   assert( pSrc->a[iLeft].pTab );
104383   assert( pSrc->a[iRight].pTab );
104384 
104385   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
104386   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
104387 
104388   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
104389   if( pEq && isOuterJoin ){
104390     ExprSetProperty(pEq, EP_FromJoin);
104391     assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
104392     ExprSetVVAProperty(pEq, EP_NoReduce);
104393     pEq->iRightJoinTable = (i16)pE2->iTable;
104394   }
104395   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
104396 }
104397 
104398 /*
104399 ** Set the EP_FromJoin property on all terms of the given expression.
104400 ** And set the Expr.iRightJoinTable to iTable for every term in the
104401 ** expression.
104402 **
104403 ** The EP_FromJoin property is used on terms of an expression to tell
104404 ** the LEFT OUTER JOIN processing logic that this term is part of the
104405 ** join restriction specified in the ON or USING clause and not a part
104406 ** of the more general WHERE clause.  These terms are moved over to the
104407 ** WHERE clause during join processing but we need to remember that they
104408 ** originated in the ON or USING clause.
104409 **
104410 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
104411 ** expression depends on table iRightJoinTable even if that table is not
104412 ** explicitly mentioned in the expression.  That information is needed
104413 ** for cases like this:
104414 **
104415 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
104416 **
104417 ** The where clause needs to defer the handling of the t1.x=5
104418 ** term until after the t2 loop of the join.  In that way, a
104419 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
104420 ** defer the handling of t1.x=5, it will be processed immediately
104421 ** after the t1 loop and rows with t1.x!=5 will never appear in
104422 ** the output, which is incorrect.
104423 */
104424 static void setJoinExpr(Expr *p, int iTable){
104425   while( p ){
104426     ExprSetProperty(p, EP_FromJoin);
104427     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
104428     ExprSetVVAProperty(p, EP_NoReduce);
104429     p->iRightJoinTable = (i16)iTable;
104430     setJoinExpr(p->pLeft, iTable);
104431     p = p->pRight;
104432   }
104433 }
104434 
104435 /*
104436 ** This routine processes the join information for a SELECT statement.
104437 ** ON and USING clauses are converted into extra terms of the WHERE clause.
104438 ** NATURAL joins also create extra WHERE clause terms.
104439 **
104440 ** The terms of a FROM clause are contained in the Select.pSrc structure.
104441 ** The left most table is the first entry in Select.pSrc.  The right-most
104442 ** table is the last entry.  The join operator is held in the entry to
104443 ** the left.  Thus entry 0 contains the join operator for the join between
104444 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
104445 ** also attached to the left entry.
104446 **
104447 ** This routine returns the number of errors encountered.
104448 */
104449 static int sqliteProcessJoin(Parse *pParse, Select *p){
104450   SrcList *pSrc;                  /* All tables in the FROM clause */
104451   int i, j;                       /* Loop counters */
104452   struct SrcList_item *pLeft;     /* Left table being joined */
104453   struct SrcList_item *pRight;    /* Right table being joined */
104454 
104455   pSrc = p->pSrc;
104456   pLeft = &pSrc->a[0];
104457   pRight = &pLeft[1];
104458   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
104459     Table *pLeftTab = pLeft->pTab;
104460     Table *pRightTab = pRight->pTab;
104461     int isOuter;
104462 
104463     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
104464     isOuter = (pRight->jointype & JT_OUTER)!=0;
104465 
104466     /* When the NATURAL keyword is present, add WHERE clause terms for
104467     ** every column that the two tables have in common.
104468     */
104469     if( pRight->jointype & JT_NATURAL ){
104470       if( pRight->pOn || pRight->pUsing ){
104471         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
104472            "an ON or USING clause", 0);
104473         return 1;
104474       }
104475       for(j=0; j<pRightTab->nCol; j++){
104476         char *zName;   /* Name of column in the right table */
104477         int iLeft;     /* Matching left table */
104478         int iLeftCol;  /* Matching column in the left table */
104479 
104480         zName = pRightTab->aCol[j].zName;
104481         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
104482           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
104483                        isOuter, &p->pWhere);
104484         }
104485       }
104486     }
104487 
104488     /* Disallow both ON and USING clauses in the same join
104489     */
104490     if( pRight->pOn && pRight->pUsing ){
104491       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
104492         "clauses in the same join");
104493       return 1;
104494     }
104495 
104496     /* Add the ON clause to the end of the WHERE clause, connected by
104497     ** an AND operator.
104498     */
104499     if( pRight->pOn ){
104500       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
104501       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
104502       pRight->pOn = 0;
104503     }
104504 
104505     /* Create extra terms on the WHERE clause for each column named
104506     ** in the USING clause.  Example: If the two tables to be joined are
104507     ** A and B and the USING clause names X, Y, and Z, then add this
104508     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
104509     ** Report an error if any column mentioned in the USING clause is
104510     ** not contained in both tables to be joined.
104511     */
104512     if( pRight->pUsing ){
104513       IdList *pList = pRight->pUsing;
104514       for(j=0; j<pList->nId; j++){
104515         char *zName;     /* Name of the term in the USING clause */
104516         int iLeft;       /* Table on the left with matching column name */
104517         int iLeftCol;    /* Column number of matching column on the left */
104518         int iRightCol;   /* Column number of matching column on the right */
104519 
104520         zName = pList->a[j].zName;
104521         iRightCol = columnIndex(pRightTab, zName);
104522         if( iRightCol<0
104523          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
104524         ){
104525           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
104526             "not present in both tables", zName);
104527           return 1;
104528         }
104529         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
104530                      isOuter, &p->pWhere);
104531       }
104532     }
104533   }
104534   return 0;
104535 }
104536 
104537 /* Forward reference */
104538 static KeyInfo *keyInfoFromExprList(
104539   Parse *pParse,       /* Parsing context */
104540   ExprList *pList,     /* Form the KeyInfo object from this ExprList */
104541   int iStart,          /* Begin with this column of pList */
104542   int nExtra           /* Add this many extra columns to the end */
104543 );
104544 
104545 /*
104546 ** Generate code that will push the record in registers regData
104547 ** through regData+nData-1 onto the sorter.
104548 */
104549 static void pushOntoSorter(
104550   Parse *pParse,         /* Parser context */
104551   SortCtx *pSort,        /* Information about the ORDER BY clause */
104552   Select *pSelect,       /* The whole SELECT statement */
104553   int regData,           /* First register holding data to be sorted */
104554   int nData,             /* Number of elements in the data array */
104555   int nPrefixReg         /* No. of reg prior to regData available for use */
104556 ){
104557   Vdbe *v = pParse->pVdbe;                         /* Stmt under construction */
104558   int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
104559   int nExpr = pSort->pOrderBy->nExpr;              /* No. of ORDER BY terms */
104560   int nBase = nExpr + bSeq + nData;                /* Fields in sorter record */
104561   int regBase;                                     /* Regs for sorter record */
104562   int regRecord = ++pParse->nMem;                  /* Assembled sorter record */
104563   int nOBSat = pSort->nOBSat;                      /* ORDER BY terms to skip */
104564   int op;                            /* Opcode to add sorter record to sorter */
104565 
104566   assert( bSeq==0 || bSeq==1 );
104567   if( nPrefixReg ){
104568     assert( nPrefixReg==nExpr+bSeq );
104569     regBase = regData - nExpr - bSeq;
104570   }else{
104571     regBase = pParse->nMem + 1;
104572     pParse->nMem += nBase;
104573   }
104574   sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, SQLITE_ECEL_DUP);
104575   if( bSeq ){
104576     sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
104577   }
104578   if( nPrefixReg==0 ){
104579     sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
104580   }
104581 
104582   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
104583   if( nOBSat>0 ){
104584     int regPrevKey;   /* The first nOBSat columns of the previous row */
104585     int addrFirst;    /* Address of the OP_IfNot opcode */
104586     int addrJmp;      /* Address of the OP_Jump opcode */
104587     VdbeOp *pOp;      /* Opcode that opens the sorter */
104588     int nKey;         /* Number of sorting key columns, including OP_Sequence */
104589     KeyInfo *pKI;     /* Original KeyInfo on the sorter table */
104590 
104591     regPrevKey = pParse->nMem+1;
104592     pParse->nMem += pSort->nOBSat;
104593     nKey = nExpr - pSort->nOBSat + bSeq;
104594     if( bSeq ){
104595       addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
104596     }else{
104597       addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
104598     }
104599     VdbeCoverage(v);
104600     sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
104601     pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
104602     if( pParse->db->mallocFailed ) return;
104603     pOp->p2 = nKey + nData;
104604     pKI = pOp->p4.pKeyInfo;
104605     memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
104606     sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
104607     pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat, 1);
104608     addrJmp = sqlite3VdbeCurrentAddr(v);
104609     sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
104610     pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
104611     pSort->regReturn = ++pParse->nMem;
104612     sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
104613     sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
104614     sqlite3VdbeJumpHere(v, addrFirst);
104615     sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
104616     sqlite3VdbeJumpHere(v, addrJmp);
104617   }
104618   if( pSort->sortFlags & SORTFLAG_UseSorter ){
104619     op = OP_SorterInsert;
104620   }else{
104621     op = OP_IdxInsert;
104622   }
104623   sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
104624   if( pSelect->iLimit ){
104625     int addr1, addr2;
104626     int iLimit;
104627     if( pSelect->iOffset ){
104628       iLimit = pSelect->iOffset+1;
104629     }else{
104630       iLimit = pSelect->iLimit;
104631     }
104632     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit); VdbeCoverage(v);
104633     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
104634     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
104635     sqlite3VdbeJumpHere(v, addr1);
104636     sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
104637     sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
104638     sqlite3VdbeJumpHere(v, addr2);
104639   }
104640 }
104641 
104642 /*
104643 ** Add code to implement the OFFSET
104644 */
104645 static void codeOffset(
104646   Vdbe *v,          /* Generate code into this VM */
104647   int iOffset,      /* Register holding the offset counter */
104648   int iContinue     /* Jump here to skip the current record */
104649 ){
104650   if( iOffset>0 ){
104651     int addr;
104652     addr = sqlite3VdbeAddOp3(v, OP_IfNeg, iOffset, 0, -1); VdbeCoverage(v);
104653     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
104654     VdbeComment((v, "skip OFFSET records"));
104655     sqlite3VdbeJumpHere(v, addr);
104656   }
104657 }
104658 
104659 /*
104660 ** Add code that will check to make sure the N registers starting at iMem
104661 ** form a distinct entry.  iTab is a sorting index that holds previously
104662 ** seen combinations of the N values.  A new entry is made in iTab
104663 ** if the current N values are new.
104664 **
104665 ** A jump to addrRepeat is made and the N+1 values are popped from the
104666 ** stack if the top N elements are not distinct.
104667 */
104668 static void codeDistinct(
104669   Parse *pParse,     /* Parsing and code generating context */
104670   int iTab,          /* A sorting index used to test for distinctness */
104671   int addrRepeat,    /* Jump to here if not distinct */
104672   int N,             /* Number of elements */
104673   int iMem           /* First element */
104674 ){
104675   Vdbe *v;
104676   int r1;
104677 
104678   v = pParse->pVdbe;
104679   r1 = sqlite3GetTempReg(pParse);
104680   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
104681   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
104682   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
104683   sqlite3ReleaseTempReg(pParse, r1);
104684 }
104685 
104686 #ifndef SQLITE_OMIT_SUBQUERY
104687 /*
104688 ** Generate an error message when a SELECT is used within a subexpression
104689 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
104690 ** column.  We do this in a subroutine because the error used to occur
104691 ** in multiple places.  (The error only occurs in one place now, but we
104692 ** retain the subroutine to minimize code disruption.)
104693 */
104694 static int checkForMultiColumnSelectError(
104695   Parse *pParse,       /* Parse context. */
104696   SelectDest *pDest,   /* Destination of SELECT results */
104697   int nExpr            /* Number of result columns returned by SELECT */
104698 ){
104699   int eDest = pDest->eDest;
104700   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
104701     sqlite3ErrorMsg(pParse, "only a single result allowed for "
104702        "a SELECT that is part of an expression");
104703     return 1;
104704   }else{
104705     return 0;
104706   }
104707 }
104708 #endif
104709 
104710 /*
104711 ** This routine generates the code for the inside of the inner loop
104712 ** of a SELECT.
104713 **
104714 ** If srcTab is negative, then the pEList expressions
104715 ** are evaluated in order to get the data for this row.  If srcTab is
104716 ** zero or more, then data is pulled from srcTab and pEList is used only
104717 ** to get number columns and the datatype for each column.
104718 */
104719 static void selectInnerLoop(
104720   Parse *pParse,          /* The parser context */
104721   Select *p,              /* The complete select statement being coded */
104722   ExprList *pEList,       /* List of values being extracted */
104723   int srcTab,             /* Pull data from this table */
104724   SortCtx *pSort,         /* If not NULL, info on how to process ORDER BY */
104725   DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
104726   SelectDest *pDest,      /* How to dispose of the results */
104727   int iContinue,          /* Jump here to continue with next row */
104728   int iBreak              /* Jump here to break out of the inner loop */
104729 ){
104730   Vdbe *v = pParse->pVdbe;
104731   int i;
104732   int hasDistinct;        /* True if the DISTINCT keyword is present */
104733   int regResult;              /* Start of memory holding result set */
104734   int eDest = pDest->eDest;   /* How to dispose of results */
104735   int iParm = pDest->iSDParm; /* First argument to disposal method */
104736   int nResultCol;             /* Number of result columns */
104737   int nPrefixReg = 0;         /* Number of extra registers before regResult */
104738 
104739   assert( v );
104740   assert( pEList!=0 );
104741   hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
104742   if( pSort && pSort->pOrderBy==0 ) pSort = 0;
104743   if( pSort==0 && !hasDistinct ){
104744     assert( iContinue!=0 );
104745     codeOffset(v, p->iOffset, iContinue);
104746   }
104747 
104748   /* Pull the requested columns.
104749   */
104750   nResultCol = pEList->nExpr;
104751 
104752   if( pDest->iSdst==0 ){
104753     if( pSort ){
104754       nPrefixReg = pSort->pOrderBy->nExpr;
104755       if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
104756       pParse->nMem += nPrefixReg;
104757     }
104758     pDest->iSdst = pParse->nMem+1;
104759     pParse->nMem += nResultCol;
104760   }else if( pDest->iSdst+nResultCol > pParse->nMem ){
104761     /* This is an error condition that can result, for example, when a SELECT
104762     ** on the right-hand side of an INSERT contains more result columns than
104763     ** there are columns in the table on the left.  The error will be caught
104764     ** and reported later.  But we need to make sure enough memory is allocated
104765     ** to avoid other spurious errors in the meantime. */
104766     pParse->nMem += nResultCol;
104767   }
104768   pDest->nSdst = nResultCol;
104769   regResult = pDest->iSdst;
104770   if( srcTab>=0 ){
104771     for(i=0; i<nResultCol; i++){
104772       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
104773       VdbeComment((v, "%s", pEList->a[i].zName));
104774     }
104775   }else if( eDest!=SRT_Exists ){
104776     /* If the destination is an EXISTS(...) expression, the actual
104777     ** values returned by the SELECT are not required.
104778     */
104779     sqlite3ExprCodeExprList(pParse, pEList, regResult,
104780                   (eDest==SRT_Output||eDest==SRT_Coroutine)?SQLITE_ECEL_DUP:0);
104781   }
104782 
104783   /* If the DISTINCT keyword was present on the SELECT statement
104784   ** and this row has been seen before, then do not make this row
104785   ** part of the result.
104786   */
104787   if( hasDistinct ){
104788     switch( pDistinct->eTnctType ){
104789       case WHERE_DISTINCT_ORDERED: {
104790         VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
104791         int iJump;              /* Jump destination */
104792         int regPrev;            /* Previous row content */
104793 
104794         /* Allocate space for the previous row */
104795         regPrev = pParse->nMem+1;
104796         pParse->nMem += nResultCol;
104797 
104798         /* Change the OP_OpenEphemeral coded earlier to an OP_Null
104799         ** sets the MEM_Cleared bit on the first register of the
104800         ** previous value.  This will cause the OP_Ne below to always
104801         ** fail on the first iteration of the loop even if the first
104802         ** row is all NULLs.
104803         */
104804         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
104805         pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
104806         pOp->opcode = OP_Null;
104807         pOp->p1 = 1;
104808         pOp->p2 = regPrev;
104809 
104810         iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
104811         for(i=0; i<nResultCol; i++){
104812           CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
104813           if( i<nResultCol-1 ){
104814             sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
104815             VdbeCoverage(v);
104816           }else{
104817             sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
104818             VdbeCoverage(v);
104819            }
104820           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
104821           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
104822         }
104823         assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
104824         sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
104825         break;
104826       }
104827 
104828       case WHERE_DISTINCT_UNIQUE: {
104829         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
104830         break;
104831       }
104832 
104833       default: {
104834         assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
104835         codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, regResult);
104836         break;
104837       }
104838     }
104839     if( pSort==0 ){
104840       codeOffset(v, p->iOffset, iContinue);
104841     }
104842   }
104843 
104844   switch( eDest ){
104845     /* In this mode, write each query result to the key of the temporary
104846     ** table iParm.
104847     */
104848 #ifndef SQLITE_OMIT_COMPOUND_SELECT
104849     case SRT_Union: {
104850       int r1;
104851       r1 = sqlite3GetTempReg(pParse);
104852       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
104853       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
104854       sqlite3ReleaseTempReg(pParse, r1);
104855       break;
104856     }
104857 
104858     /* Construct a record from the query result, but instead of
104859     ** saving that record, use it as a key to delete elements from
104860     ** the temporary table iParm.
104861     */
104862     case SRT_Except: {
104863       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
104864       break;
104865     }
104866 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
104867 
104868     /* Store the result as data using a unique key.
104869     */
104870     case SRT_Fifo:
104871     case SRT_DistFifo:
104872     case SRT_Table:
104873     case SRT_EphemTab: {
104874       int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
104875       testcase( eDest==SRT_Table );
104876       testcase( eDest==SRT_EphemTab );
104877       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
104878 #ifndef SQLITE_OMIT_CTE
104879       if( eDest==SRT_DistFifo ){
104880         /* If the destination is DistFifo, then cursor (iParm+1) is open
104881         ** on an ephemeral index. If the current row is already present
104882         ** in the index, do not write it to the output. If not, add the
104883         ** current row to the index and proceed with writing it to the
104884         ** output table as well.  */
104885         int addr = sqlite3VdbeCurrentAddr(v) + 4;
104886         sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); VdbeCoverage(v);
104887         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
104888         assert( pSort==0 );
104889       }
104890 #endif
104891       if( pSort ){
104892         pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, 1, nPrefixReg);
104893       }else{
104894         int r2 = sqlite3GetTempReg(pParse);
104895         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
104896         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
104897         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
104898         sqlite3ReleaseTempReg(pParse, r2);
104899       }
104900       sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
104901       break;
104902     }
104903 
104904 #ifndef SQLITE_OMIT_SUBQUERY
104905     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
104906     ** then there should be a single item on the stack.  Write this
104907     ** item into the set table with bogus data.
104908     */
104909     case SRT_Set: {
104910       assert( nResultCol==1 );
104911       pDest->affSdst =
104912                   sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
104913       if( pSort ){
104914         /* At first glance you would think we could optimize out the
104915         ** ORDER BY in this case since the order of entries in the set
104916         ** does not matter.  But there might be a LIMIT clause, in which
104917         ** case the order does matter */
104918         pushOntoSorter(pParse, pSort, p, regResult, 1, nPrefixReg);
104919       }else{
104920         int r1 = sqlite3GetTempReg(pParse);
104921         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
104922         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
104923         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
104924         sqlite3ReleaseTempReg(pParse, r1);
104925       }
104926       break;
104927     }
104928 
104929     /* If any row exist in the result set, record that fact and abort.
104930     */
104931     case SRT_Exists: {
104932       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
104933       /* The LIMIT clause will terminate the loop for us */
104934       break;
104935     }
104936 
104937     /* If this is a scalar select that is part of an expression, then
104938     ** store the results in the appropriate memory cell and break out
104939     ** of the scan loop.
104940     */
104941     case SRT_Mem: {
104942       assert( nResultCol==1 );
104943       if( pSort ){
104944         pushOntoSorter(pParse, pSort, p, regResult, 1, nPrefixReg);
104945       }else{
104946         assert( regResult==iParm );
104947         /* The LIMIT clause will jump out of the loop for us */
104948       }
104949       break;
104950     }
104951 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
104952 
104953     case SRT_Coroutine:       /* Send data to a co-routine */
104954     case SRT_Output: {        /* Return the results */
104955       testcase( eDest==SRT_Coroutine );
104956       testcase( eDest==SRT_Output );
104957       if( pSort ){
104958         pushOntoSorter(pParse, pSort, p, regResult, nResultCol, nPrefixReg);
104959       }else if( eDest==SRT_Coroutine ){
104960         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
104961       }else{
104962         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
104963         sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
104964       }
104965       break;
104966     }
104967 
104968 #ifndef SQLITE_OMIT_CTE
104969     /* Write the results into a priority queue that is order according to
104970     ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
104971     ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
104972     ** pSO->nExpr columns, then make sure all keys are unique by adding a
104973     ** final OP_Sequence column.  The last column is the record as a blob.
104974     */
104975     case SRT_DistQueue:
104976     case SRT_Queue: {
104977       int nKey;
104978       int r1, r2, r3;
104979       int addrTest = 0;
104980       ExprList *pSO;
104981       pSO = pDest->pOrderBy;
104982       assert( pSO );
104983       nKey = pSO->nExpr;
104984       r1 = sqlite3GetTempReg(pParse);
104985       r2 = sqlite3GetTempRange(pParse, nKey+2);
104986       r3 = r2+nKey+1;
104987       if( eDest==SRT_DistQueue ){
104988         /* If the destination is DistQueue, then cursor (iParm+1) is open
104989         ** on a second ephemeral index that holds all values every previously
104990         ** added to the queue. */
104991         addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
104992                                         regResult, nResultCol);
104993         VdbeCoverage(v);
104994       }
104995       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
104996       if( eDest==SRT_DistQueue ){
104997         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
104998         sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
104999       }
105000       for(i=0; i<nKey; i++){
105001         sqlite3VdbeAddOp2(v, OP_SCopy,
105002                           regResult + pSO->a[i].u.x.iOrderByCol - 1,
105003                           r2+i);
105004       }
105005       sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
105006       sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
105007       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
105008       if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
105009       sqlite3ReleaseTempReg(pParse, r1);
105010       sqlite3ReleaseTempRange(pParse, r2, nKey+2);
105011       break;
105012     }
105013 #endif /* SQLITE_OMIT_CTE */
105014 
105015 
105016 
105017 #if !defined(SQLITE_OMIT_TRIGGER)
105018     /* Discard the results.  This is used for SELECT statements inside
105019     ** the body of a TRIGGER.  The purpose of such selects is to call
105020     ** user-defined functions that have side effects.  We do not care
105021     ** about the actual results of the select.
105022     */
105023     default: {
105024       assert( eDest==SRT_Discard );
105025       break;
105026     }
105027 #endif
105028   }
105029 
105030   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
105031   ** there is a sorter, in which case the sorter has already limited
105032   ** the output for us.
105033   */
105034   if( pSort==0 && p->iLimit ){
105035     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v);
105036   }
105037 }
105038 
105039 /*
105040 ** Allocate a KeyInfo object sufficient for an index of N key columns and
105041 ** X extra columns.
105042 */
105043 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
105044   KeyInfo *p = sqlite3DbMallocZero(0,
105045                    sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1));
105046   if( p ){
105047     p->aSortOrder = (u8*)&p->aColl[N+X];
105048     p->nField = (u16)N;
105049     p->nXField = (u16)X;
105050     p->enc = ENC(db);
105051     p->db = db;
105052     p->nRef = 1;
105053   }else{
105054     db->mallocFailed = 1;
105055   }
105056   return p;
105057 }
105058 
105059 /*
105060 ** Deallocate a KeyInfo object
105061 */
105062 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
105063   if( p ){
105064     assert( p->nRef>0 );
105065     p->nRef--;
105066     if( p->nRef==0 ) sqlite3DbFree(0, p);
105067   }
105068 }
105069 
105070 /*
105071 ** Make a new pointer to a KeyInfo object
105072 */
105073 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
105074   if( p ){
105075     assert( p->nRef>0 );
105076     p->nRef++;
105077   }
105078   return p;
105079 }
105080 
105081 #ifdef SQLITE_DEBUG
105082 /*
105083 ** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
105084 ** can only be changed if this is just a single reference to the object.
105085 **
105086 ** This routine is used only inside of assert() statements.
105087 */
105088 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
105089 #endif /* SQLITE_DEBUG */
105090 
105091 /*
105092 ** Given an expression list, generate a KeyInfo structure that records
105093 ** the collating sequence for each expression in that expression list.
105094 **
105095 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
105096 ** KeyInfo structure is appropriate for initializing a virtual index to
105097 ** implement that clause.  If the ExprList is the result set of a SELECT
105098 ** then the KeyInfo structure is appropriate for initializing a virtual
105099 ** index to implement a DISTINCT test.
105100 **
105101 ** Space to hold the KeyInfo structure is obtained from malloc.  The calling
105102 ** function is responsible for seeing that this structure is eventually
105103 ** freed.
105104 */
105105 static KeyInfo *keyInfoFromExprList(
105106   Parse *pParse,       /* Parsing context */
105107   ExprList *pList,     /* Form the KeyInfo object from this ExprList */
105108   int iStart,          /* Begin with this column of pList */
105109   int nExtra           /* Add this many extra columns to the end */
105110 ){
105111   int nExpr;
105112   KeyInfo *pInfo;
105113   struct ExprList_item *pItem;
105114   sqlite3 *db = pParse->db;
105115   int i;
105116 
105117   nExpr = pList->nExpr;
105118   pInfo = sqlite3KeyInfoAlloc(db, nExpr+nExtra-iStart, 1);
105119   if( pInfo ){
105120     assert( sqlite3KeyInfoIsWriteable(pInfo) );
105121     for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
105122       CollSeq *pColl;
105123       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
105124       if( !pColl ) pColl = db->pDfltColl;
105125       pInfo->aColl[i-iStart] = pColl;
105126       pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
105127     }
105128   }
105129   return pInfo;
105130 }
105131 
105132 #ifndef SQLITE_OMIT_COMPOUND_SELECT
105133 /*
105134 ** Name of the connection operator, used for error messages.
105135 */
105136 static const char *selectOpName(int id){
105137   char *z;
105138   switch( id ){
105139     case TK_ALL:       z = "UNION ALL";   break;
105140     case TK_INTERSECT: z = "INTERSECT";   break;
105141     case TK_EXCEPT:    z = "EXCEPT";      break;
105142     default:           z = "UNION";       break;
105143   }
105144   return z;
105145 }
105146 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
105147 
105148 #ifndef SQLITE_OMIT_EXPLAIN
105149 /*
105150 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
105151 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
105152 ** where the caption is of the form:
105153 **
105154 **   "USE TEMP B-TREE FOR xxx"
105155 **
105156 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
105157 ** is determined by the zUsage argument.
105158 */
105159 static void explainTempTable(Parse *pParse, const char *zUsage){
105160   if( pParse->explain==2 ){
105161     Vdbe *v = pParse->pVdbe;
105162     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
105163     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
105164   }
105165 }
105166 
105167 /*
105168 ** Assign expression b to lvalue a. A second, no-op, version of this macro
105169 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
105170 ** in sqlite3Select() to assign values to structure member variables that
105171 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
105172 ** code with #ifndef directives.
105173 */
105174 # define explainSetInteger(a, b) a = b
105175 
105176 #else
105177 /* No-op versions of the explainXXX() functions and macros. */
105178 # define explainTempTable(y,z)
105179 # define explainSetInteger(y,z)
105180 #endif
105181 
105182 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
105183 /*
105184 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
105185 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
105186 ** where the caption is of one of the two forms:
105187 **
105188 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
105189 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
105190 **
105191 ** where iSub1 and iSub2 are the integers passed as the corresponding
105192 ** function parameters, and op is the text representation of the parameter
105193 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
105194 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
105195 ** false, or the second form if it is true.
105196 */
105197 static void explainComposite(
105198   Parse *pParse,                  /* Parse context */
105199   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
105200   int iSub1,                      /* Subquery id 1 */
105201   int iSub2,                      /* Subquery id 2 */
105202   int bUseTmp                     /* True if a temp table was used */
105203 ){
105204   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
105205   if( pParse->explain==2 ){
105206     Vdbe *v = pParse->pVdbe;
105207     char *zMsg = sqlite3MPrintf(
105208         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
105209         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
105210     );
105211     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
105212   }
105213 }
105214 #else
105215 /* No-op versions of the explainXXX() functions and macros. */
105216 # define explainComposite(v,w,x,y,z)
105217 #endif
105218 
105219 /*
105220 ** If the inner loop was generated using a non-null pOrderBy argument,
105221 ** then the results were placed in a sorter.  After the loop is terminated
105222 ** we need to run the sorter and output the results.  The following
105223 ** routine generates the code needed to do that.
105224 */
105225 static void generateSortTail(
105226   Parse *pParse,    /* Parsing context */
105227   Select *p,        /* The SELECT statement */
105228   SortCtx *pSort,   /* Information on the ORDER BY clause */
105229   int nColumn,      /* Number of columns of data */
105230   SelectDest *pDest /* Write the sorted results here */
105231 ){
105232   Vdbe *v = pParse->pVdbe;                     /* The prepared statement */
105233   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
105234   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
105235   int addr;
105236   int addrOnce = 0;
105237   int iTab;
105238   ExprList *pOrderBy = pSort->pOrderBy;
105239   int eDest = pDest->eDest;
105240   int iParm = pDest->iSDParm;
105241   int regRow;
105242   int regRowid;
105243   int nKey;
105244   int iSortTab;                   /* Sorter cursor to read from */
105245   int nSortData;                  /* Trailing values to read from sorter */
105246   int i;
105247   int bSeq;                       /* True if sorter record includes seq. no. */
105248 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
105249   struct ExprList_item *aOutEx = p->pEList->a;
105250 #endif
105251 
105252   if( pSort->labelBkOut ){
105253     sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
105254     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBreak);
105255     sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
105256   }
105257   iTab = pSort->iECursor;
105258   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
105259     regRowid = 0;
105260     regRow = pDest->iSdst;
105261     nSortData = nColumn;
105262   }else{
105263     regRowid = sqlite3GetTempReg(pParse);
105264     regRow = sqlite3GetTempReg(pParse);
105265     nSortData = 1;
105266   }
105267   nKey = pOrderBy->nExpr - pSort->nOBSat;
105268   if( pSort->sortFlags & SORTFLAG_UseSorter ){
105269     int regSortOut = ++pParse->nMem;
105270     iSortTab = pParse->nTab++;
105271     if( pSort->labelBkOut ){
105272       addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
105273     }
105274     sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
105275     if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
105276     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
105277     VdbeCoverage(v);
105278     codeOffset(v, p->iOffset, addrContinue);
105279     sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
105280     bSeq = 0;
105281   }else{
105282     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
105283     codeOffset(v, p->iOffset, addrContinue);
105284     iSortTab = iTab;
105285     bSeq = 1;
105286   }
105287   for(i=0; i<nSortData; i++){
105288     sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
105289     VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
105290   }
105291   switch( eDest ){
105292     case SRT_Table:
105293     case SRT_EphemTab: {
105294       testcase( eDest==SRT_Table );
105295       testcase( eDest==SRT_EphemTab );
105296       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
105297       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
105298       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
105299       break;
105300     }
105301 #ifndef SQLITE_OMIT_SUBQUERY
105302     case SRT_Set: {
105303       assert( nColumn==1 );
105304       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
105305                         &pDest->affSdst, 1);
105306       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
105307       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
105308       break;
105309     }
105310     case SRT_Mem: {
105311       assert( nColumn==1 );
105312       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
105313       /* The LIMIT clause will terminate the loop for us */
105314       break;
105315     }
105316 #endif
105317     default: {
105318       assert( eDest==SRT_Output || eDest==SRT_Coroutine );
105319       testcase( eDest==SRT_Output );
105320       testcase( eDest==SRT_Coroutine );
105321       if( eDest==SRT_Output ){
105322         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
105323         sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
105324       }else{
105325         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
105326       }
105327       break;
105328     }
105329   }
105330   if( regRowid ){
105331     sqlite3ReleaseTempReg(pParse, regRow);
105332     sqlite3ReleaseTempReg(pParse, regRowid);
105333   }
105334   /* The bottom of the loop
105335   */
105336   sqlite3VdbeResolveLabel(v, addrContinue);
105337   if( pSort->sortFlags & SORTFLAG_UseSorter ){
105338     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
105339   }else{
105340     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
105341   }
105342   if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
105343   sqlite3VdbeResolveLabel(v, addrBreak);
105344 }
105345 
105346 /*
105347 ** Return a pointer to a string containing the 'declaration type' of the
105348 ** expression pExpr. The string may be treated as static by the caller.
105349 **
105350 ** Also try to estimate the size of the returned value and return that
105351 ** result in *pEstWidth.
105352 **
105353 ** The declaration type is the exact datatype definition extracted from the
105354 ** original CREATE TABLE statement if the expression is a column. The
105355 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
105356 ** is considered a column can be complex in the presence of subqueries. The
105357 ** result-set expression in all of the following SELECT statements is
105358 ** considered a column by this function.
105359 **
105360 **   SELECT col FROM tbl;
105361 **   SELECT (SELECT col FROM tbl;
105362 **   SELECT (SELECT col FROM tbl);
105363 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
105364 **
105365 ** The declaration type for any expression other than a column is NULL.
105366 **
105367 ** This routine has either 3 or 6 parameters depending on whether or not
105368 ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
105369 */
105370 #ifdef SQLITE_ENABLE_COLUMN_METADATA
105371 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
105372 static const char *columnTypeImpl(
105373   NameContext *pNC,
105374   Expr *pExpr,
105375   const char **pzOrigDb,
105376   const char **pzOrigTab,
105377   const char **pzOrigCol,
105378   u8 *pEstWidth
105379 ){
105380   char const *zOrigDb = 0;
105381   char const *zOrigTab = 0;
105382   char const *zOrigCol = 0;
105383 #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
105384 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
105385 static const char *columnTypeImpl(
105386   NameContext *pNC,
105387   Expr *pExpr,
105388   u8 *pEstWidth
105389 ){
105390 #endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */
105391   char const *zType = 0;
105392   int j;
105393   u8 estWidth = 1;
105394 
105395   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
105396   switch( pExpr->op ){
105397     case TK_AGG_COLUMN:
105398     case TK_COLUMN: {
105399       /* The expression is a column. Locate the table the column is being
105400       ** extracted from in NameContext.pSrcList. This table may be real
105401       ** database table or a subquery.
105402       */
105403       Table *pTab = 0;            /* Table structure column is extracted from */
105404       Select *pS = 0;             /* Select the column is extracted from */
105405       int iCol = pExpr->iColumn;  /* Index of column in pTab */
105406       testcase( pExpr->op==TK_AGG_COLUMN );
105407       testcase( pExpr->op==TK_COLUMN );
105408       while( pNC && !pTab ){
105409         SrcList *pTabList = pNC->pSrcList;
105410         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
105411         if( j<pTabList->nSrc ){
105412           pTab = pTabList->a[j].pTab;
105413           pS = pTabList->a[j].pSelect;
105414         }else{
105415           pNC = pNC->pNext;
105416         }
105417       }
105418 
105419       if( pTab==0 ){
105420         /* At one time, code such as "SELECT new.x" within a trigger would
105421         ** cause this condition to run.  Since then, we have restructured how
105422         ** trigger code is generated and so this condition is no longer
105423         ** possible. However, it can still be true for statements like
105424         ** the following:
105425         **
105426         **   CREATE TABLE t1(col INTEGER);
105427         **   SELECT (SELECT t1.col) FROM FROM t1;
105428         **
105429         ** when columnType() is called on the expression "t1.col" in the
105430         ** sub-select. In this case, set the column type to NULL, even
105431         ** though it should really be "INTEGER".
105432         **
105433         ** This is not a problem, as the column type of "t1.col" is never
105434         ** used. When columnType() is called on the expression
105435         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
105436         ** branch below.  */
105437         break;
105438       }
105439 
105440       assert( pTab && pExpr->pTab==pTab );
105441       if( pS ){
105442         /* The "table" is actually a sub-select or a view in the FROM clause
105443         ** of the SELECT statement. Return the declaration type and origin
105444         ** data for the result-set column of the sub-select.
105445         */
105446         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
105447           /* If iCol is less than zero, then the expression requests the
105448           ** rowid of the sub-select or view. This expression is legal (see
105449           ** test case misc2.2.2) - it always evaluates to NULL.
105450           */
105451           NameContext sNC;
105452           Expr *p = pS->pEList->a[iCol].pExpr;
105453           sNC.pSrcList = pS->pSrc;
105454           sNC.pNext = pNC;
105455           sNC.pParse = pNC->pParse;
105456           zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
105457         }
105458       }else if( pTab->pSchema ){
105459         /* A real table */
105460         assert( !pS );
105461         if( iCol<0 ) iCol = pTab->iPKey;
105462         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
105463 #ifdef SQLITE_ENABLE_COLUMN_METADATA
105464         if( iCol<0 ){
105465           zType = "INTEGER";
105466           zOrigCol = "rowid";
105467         }else{
105468           zType = pTab->aCol[iCol].zType;
105469           zOrigCol = pTab->aCol[iCol].zName;
105470           estWidth = pTab->aCol[iCol].szEst;
105471         }
105472         zOrigTab = pTab->zName;
105473         if( pNC->pParse ){
105474           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
105475           zOrigDb = pNC->pParse->db->aDb[iDb].zName;
105476         }
105477 #else
105478         if( iCol<0 ){
105479           zType = "INTEGER";
105480         }else{
105481           zType = pTab->aCol[iCol].zType;
105482           estWidth = pTab->aCol[iCol].szEst;
105483         }
105484 #endif
105485       }
105486       break;
105487     }
105488 #ifndef SQLITE_OMIT_SUBQUERY
105489     case TK_SELECT: {
105490       /* The expression is a sub-select. Return the declaration type and
105491       ** origin info for the single column in the result set of the SELECT
105492       ** statement.
105493       */
105494       NameContext sNC;
105495       Select *pS = pExpr->x.pSelect;
105496       Expr *p = pS->pEList->a[0].pExpr;
105497       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
105498       sNC.pSrcList = pS->pSrc;
105499       sNC.pNext = pNC;
105500       sNC.pParse = pNC->pParse;
105501       zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
105502       break;
105503     }
105504 #endif
105505   }
105506 
105507 #ifdef SQLITE_ENABLE_COLUMN_METADATA
105508   if( pzOrigDb ){
105509     assert( pzOrigTab && pzOrigCol );
105510     *pzOrigDb = zOrigDb;
105511     *pzOrigTab = zOrigTab;
105512     *pzOrigCol = zOrigCol;
105513   }
105514 #endif
105515   if( pEstWidth ) *pEstWidth = estWidth;
105516   return zType;
105517 }
105518 
105519 /*
105520 ** Generate code that will tell the VDBE the declaration types of columns
105521 ** in the result set.
105522 */
105523 static void generateColumnTypes(
105524   Parse *pParse,      /* Parser context */
105525   SrcList *pTabList,  /* List of tables */
105526   ExprList *pEList    /* Expressions defining the result set */
105527 ){
105528 #ifndef SQLITE_OMIT_DECLTYPE
105529   Vdbe *v = pParse->pVdbe;
105530   int i;
105531   NameContext sNC;
105532   sNC.pSrcList = pTabList;
105533   sNC.pParse = pParse;
105534   for(i=0; i<pEList->nExpr; i++){
105535     Expr *p = pEList->a[i].pExpr;
105536     const char *zType;
105537 #ifdef SQLITE_ENABLE_COLUMN_METADATA
105538     const char *zOrigDb = 0;
105539     const char *zOrigTab = 0;
105540     const char *zOrigCol = 0;
105541     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
105542 
105543     /* The vdbe must make its own copy of the column-type and other
105544     ** column specific strings, in case the schema is reset before this
105545     ** virtual machine is deleted.
105546     */
105547     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
105548     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
105549     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
105550 #else
105551     zType = columnType(&sNC, p, 0, 0, 0, 0);
105552 #endif
105553     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
105554   }
105555 #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
105556 }
105557 
105558 /*
105559 ** Generate code that will tell the VDBE the names of columns
105560 ** in the result set.  This information is used to provide the
105561 ** azCol[] values in the callback.
105562 */
105563 static void generateColumnNames(
105564   Parse *pParse,      /* Parser context */
105565   SrcList *pTabList,  /* List of tables */
105566   ExprList *pEList    /* Expressions defining the result set */
105567 ){
105568   Vdbe *v = pParse->pVdbe;
105569   int i, j;
105570   sqlite3 *db = pParse->db;
105571   int fullNames, shortNames;
105572 
105573 #ifndef SQLITE_OMIT_EXPLAIN
105574   /* If this is an EXPLAIN, skip this step */
105575   if( pParse->explain ){
105576     return;
105577   }
105578 #endif
105579 
105580   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
105581   pParse->colNamesSet = 1;
105582   fullNames = (db->flags & SQLITE_FullColNames)!=0;
105583   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
105584   sqlite3VdbeSetNumCols(v, pEList->nExpr);
105585   for(i=0; i<pEList->nExpr; i++){
105586     Expr *p;
105587     p = pEList->a[i].pExpr;
105588     if( NEVER(p==0) ) continue;
105589     if( pEList->a[i].zName ){
105590       char *zName = pEList->a[i].zName;
105591       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
105592     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
105593       Table *pTab;
105594       char *zCol;
105595       int iCol = p->iColumn;
105596       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
105597         if( pTabList->a[j].iCursor==p->iTable ) break;
105598       }
105599       assert( j<pTabList->nSrc );
105600       pTab = pTabList->a[j].pTab;
105601       if( iCol<0 ) iCol = pTab->iPKey;
105602       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
105603       if( iCol<0 ){
105604         zCol = "rowid";
105605       }else{
105606         zCol = pTab->aCol[iCol].zName;
105607       }
105608       if( !shortNames && !fullNames ){
105609         sqlite3VdbeSetColName(v, i, COLNAME_NAME,
105610             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
105611       }else if( fullNames ){
105612         char *zName = 0;
105613         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
105614         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
105615       }else{
105616         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
105617       }
105618     }else{
105619       const char *z = pEList->a[i].zSpan;
105620       z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
105621       sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
105622     }
105623   }
105624   generateColumnTypes(pParse, pTabList, pEList);
105625 }
105626 
105627 /*
105628 ** Given an expression list (which is really the list of expressions
105629 ** that form the result set of a SELECT statement) compute appropriate
105630 ** column names for a table that would hold the expression list.
105631 **
105632 ** All column names will be unique.
105633 **
105634 ** Only the column names are computed.  Column.zType, Column.zColl,
105635 ** and other fields of Column are zeroed.
105636 **
105637 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
105638 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
105639 */
105640 static int selectColumnsFromExprList(
105641   Parse *pParse,          /* Parsing context */
105642   ExprList *pEList,       /* Expr list from which to derive column names */
105643   i16 *pnCol,             /* Write the number of columns here */
105644   Column **paCol          /* Write the new column list here */
105645 ){
105646   sqlite3 *db = pParse->db;   /* Database connection */
105647   int i, j;                   /* Loop counters */
105648   int cnt;                    /* Index added to make the name unique */
105649   Column *aCol, *pCol;        /* For looping over result columns */
105650   int nCol;                   /* Number of columns in the result set */
105651   Expr *p;                    /* Expression for a single result column */
105652   char *zName;                /* Column name */
105653   int nName;                  /* Size of name in zName[] */
105654 
105655   if( pEList ){
105656     nCol = pEList->nExpr;
105657     aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
105658     testcase( aCol==0 );
105659   }else{
105660     nCol = 0;
105661     aCol = 0;
105662   }
105663   *pnCol = nCol;
105664   *paCol = aCol;
105665 
105666   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
105667     /* Get an appropriate name for the column
105668     */
105669     p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
105670     if( (zName = pEList->a[i].zName)!=0 ){
105671       /* If the column contains an "AS <name>" phrase, use <name> as the name */
105672       zName = sqlite3DbStrDup(db, zName);
105673     }else{
105674       Expr *pColExpr = p;  /* The expression that is the result column name */
105675       Table *pTab;         /* Table associated with this expression */
105676       while( pColExpr->op==TK_DOT ){
105677         pColExpr = pColExpr->pRight;
105678         assert( pColExpr!=0 );
105679       }
105680       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
105681         /* For columns use the column name name */
105682         int iCol = pColExpr->iColumn;
105683         pTab = pColExpr->pTab;
105684         if( iCol<0 ) iCol = pTab->iPKey;
105685         zName = sqlite3MPrintf(db, "%s",
105686                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
105687       }else if( pColExpr->op==TK_ID ){
105688         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
105689         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
105690       }else{
105691         /* Use the original text of the column expression as its name */
105692         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
105693       }
105694     }
105695     if( db->mallocFailed ){
105696       sqlite3DbFree(db, zName);
105697       break;
105698     }
105699 
105700     /* Make sure the column name is unique.  If the name is not unique,
105701     ** append an integer to the name so that it becomes unique.
105702     */
105703     nName = sqlite3Strlen30(zName);
105704     for(j=cnt=0; j<i; j++){
105705       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
105706         char *zNewName;
105707         int k;
105708         for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
105709         if( k>=0 && zName[k]==':' ) nName = k;
105710         zName[nName] = 0;
105711         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
105712         sqlite3DbFree(db, zName);
105713         zName = zNewName;
105714         j = -1;
105715         if( zName==0 ) break;
105716       }
105717     }
105718     pCol->zName = zName;
105719   }
105720   if( db->mallocFailed ){
105721     for(j=0; j<i; j++){
105722       sqlite3DbFree(db, aCol[j].zName);
105723     }
105724     sqlite3DbFree(db, aCol);
105725     *paCol = 0;
105726     *pnCol = 0;
105727     return SQLITE_NOMEM;
105728   }
105729   return SQLITE_OK;
105730 }
105731 
105732 /*
105733 ** Add type and collation information to a column list based on
105734 ** a SELECT statement.
105735 **
105736 ** The column list presumably came from selectColumnNamesFromExprList().
105737 ** The column list has only names, not types or collations.  This
105738 ** routine goes through and adds the types and collations.
105739 **
105740 ** This routine requires that all identifiers in the SELECT
105741 ** statement be resolved.
105742 */
105743 static void selectAddColumnTypeAndCollation(
105744   Parse *pParse,        /* Parsing contexts */
105745   Table *pTab,          /* Add column type information to this table */
105746   Select *pSelect       /* SELECT used to determine types and collations */
105747 ){
105748   sqlite3 *db = pParse->db;
105749   NameContext sNC;
105750   Column *pCol;
105751   CollSeq *pColl;
105752   int i;
105753   Expr *p;
105754   struct ExprList_item *a;
105755   u64 szAll = 0;
105756 
105757   assert( pSelect!=0 );
105758   assert( (pSelect->selFlags & SF_Resolved)!=0 );
105759   assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
105760   if( db->mallocFailed ) return;
105761   memset(&sNC, 0, sizeof(sNC));
105762   sNC.pSrcList = pSelect->pSrc;
105763   a = pSelect->pEList->a;
105764   for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
105765     p = a[i].pExpr;
105766     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst));
105767     szAll += pCol->szEst;
105768     pCol->affinity = sqlite3ExprAffinity(p);
105769     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
105770     pColl = sqlite3ExprCollSeq(pParse, p);
105771     if( pColl ){
105772       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
105773     }
105774   }
105775   pTab->szTabRow = sqlite3LogEst(szAll*4);
105776 }
105777 
105778 /*
105779 ** Given a SELECT statement, generate a Table structure that describes
105780 ** the result set of that SELECT.
105781 */
105782 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
105783   Table *pTab;
105784   sqlite3 *db = pParse->db;
105785   int savedFlags;
105786 
105787   savedFlags = db->flags;
105788   db->flags &= ~SQLITE_FullColNames;
105789   db->flags |= SQLITE_ShortColNames;
105790   sqlite3SelectPrep(pParse, pSelect, 0);
105791   if( pParse->nErr ) return 0;
105792   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
105793   db->flags = savedFlags;
105794   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
105795   if( pTab==0 ){
105796     return 0;
105797   }
105798   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
105799   ** is disabled */
105800   assert( db->lookaside.bEnabled==0 );
105801   pTab->nRef = 1;
105802   pTab->zName = 0;
105803   pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
105804   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
105805   selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
105806   pTab->iPKey = -1;
105807   if( db->mallocFailed ){
105808     sqlite3DeleteTable(db, pTab);
105809     return 0;
105810   }
105811   return pTab;
105812 }
105813 
105814 /*
105815 ** Get a VDBE for the given parser context.  Create a new one if necessary.
105816 ** If an error occurs, return NULL and leave a message in pParse.
105817 */
105818 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
105819   Vdbe *v = pParse->pVdbe;
105820   if( v==0 ){
105821     v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
105822     if( v ) sqlite3VdbeAddOp0(v, OP_Init);
105823     if( pParse->pToplevel==0
105824      && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
105825     ){
105826       pParse->okConstFactor = 1;
105827     }
105828 
105829   }
105830   return v;
105831 }
105832 
105833 
105834 /*
105835 ** Compute the iLimit and iOffset fields of the SELECT based on the
105836 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
105837 ** that appear in the original SQL statement after the LIMIT and OFFSET
105838 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
105839 ** are the integer memory register numbers for counters used to compute
105840 ** the limit and offset.  If there is no limit and/or offset, then
105841 ** iLimit and iOffset are negative.
105842 **
105843 ** This routine changes the values of iLimit and iOffset only if
105844 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
105845 ** iOffset should have been preset to appropriate default values (zero)
105846 ** prior to calling this routine.
105847 **
105848 ** The iOffset register (if it exists) is initialized to the value
105849 ** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
105850 ** iOffset+1 is initialized to LIMIT+OFFSET.
105851 **
105852 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
105853 ** redefined.  The UNION ALL operator uses this property to force
105854 ** the reuse of the same limit and offset registers across multiple
105855 ** SELECT statements.
105856 */
105857 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
105858   Vdbe *v = 0;
105859   int iLimit = 0;
105860   int iOffset;
105861   int addr1, n;
105862   if( p->iLimit ) return;
105863 
105864   /*
105865   ** "LIMIT -1" always shows all rows.  There is some
105866   ** controversy about what the correct behavior should be.
105867   ** The current implementation interprets "LIMIT 0" to mean
105868   ** no rows.
105869   */
105870   sqlite3ExprCacheClear(pParse);
105871   assert( p->pOffset==0 || p->pLimit!=0 );
105872   if( p->pLimit ){
105873     p->iLimit = iLimit = ++pParse->nMem;
105874     v = sqlite3GetVdbe(pParse);
105875     assert( v!=0 );
105876     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
105877       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
105878       VdbeComment((v, "LIMIT counter"));
105879       if( n==0 ){
105880         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
105881       }else if( n>=0 && p->nSelectRow>(u64)n ){
105882         p->nSelectRow = n;
105883       }
105884     }else{
105885       sqlite3ExprCode(pParse, p->pLimit, iLimit);
105886       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
105887       VdbeComment((v, "LIMIT counter"));
105888       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak); VdbeCoverage(v);
105889     }
105890     if( p->pOffset ){
105891       p->iOffset = iOffset = ++pParse->nMem;
105892       pParse->nMem++;   /* Allocate an extra register for limit+offset */
105893       sqlite3ExprCode(pParse, p->pOffset, iOffset);
105894       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
105895       VdbeComment((v, "OFFSET counter"));
105896       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); VdbeCoverage(v);
105897       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
105898       sqlite3VdbeJumpHere(v, addr1);
105899       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
105900       VdbeComment((v, "LIMIT+OFFSET"));
105901       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); VdbeCoverage(v);
105902       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
105903       sqlite3VdbeJumpHere(v, addr1);
105904     }
105905   }
105906 }
105907 
105908 #ifndef SQLITE_OMIT_COMPOUND_SELECT
105909 /*
105910 ** Return the appropriate collating sequence for the iCol-th column of
105911 ** the result set for the compound-select statement "p".  Return NULL if
105912 ** the column has no default collating sequence.
105913 **
105914 ** The collating sequence for the compound select is taken from the
105915 ** left-most term of the select that has a collating sequence.
105916 */
105917 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
105918   CollSeq *pRet;
105919   if( p->pPrior ){
105920     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
105921   }else{
105922     pRet = 0;
105923   }
105924   assert( iCol>=0 );
105925   if( pRet==0 && iCol<p->pEList->nExpr ){
105926     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
105927   }
105928   return pRet;
105929 }
105930 
105931 /*
105932 ** The select statement passed as the second parameter is a compound SELECT
105933 ** with an ORDER BY clause. This function allocates and returns a KeyInfo
105934 ** structure suitable for implementing the ORDER BY.
105935 **
105936 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
105937 ** function is responsible for ensuring that this structure is eventually
105938 ** freed.
105939 */
105940 static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
105941   ExprList *pOrderBy = p->pOrderBy;
105942   int nOrderBy = p->pOrderBy->nExpr;
105943   sqlite3 *db = pParse->db;
105944   KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
105945   if( pRet ){
105946     int i;
105947     for(i=0; i<nOrderBy; i++){
105948       struct ExprList_item *pItem = &pOrderBy->a[i];
105949       Expr *pTerm = pItem->pExpr;
105950       CollSeq *pColl;
105951 
105952       if( pTerm->flags & EP_Collate ){
105953         pColl = sqlite3ExprCollSeq(pParse, pTerm);
105954       }else{
105955         pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
105956         if( pColl==0 ) pColl = db->pDfltColl;
105957         pOrderBy->a[i].pExpr =
105958           sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
105959       }
105960       assert( sqlite3KeyInfoIsWriteable(pRet) );
105961       pRet->aColl[i] = pColl;
105962       pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
105963     }
105964   }
105965 
105966   return pRet;
105967 }
105968 
105969 #ifndef SQLITE_OMIT_CTE
105970 /*
105971 ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
105972 ** query of the form:
105973 **
105974 **   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
105975 **                         \___________/             \_______________/
105976 **                           p->pPrior                      p
105977 **
105978 **
105979 ** There is exactly one reference to the recursive-table in the FROM clause
105980 ** of recursive-query, marked with the SrcList->a[].isRecursive flag.
105981 **
105982 ** The setup-query runs once to generate an initial set of rows that go
105983 ** into a Queue table.  Rows are extracted from the Queue table one by
105984 ** one.  Each row extracted from Queue is output to pDest.  Then the single
105985 ** extracted row (now in the iCurrent table) becomes the content of the
105986 ** recursive-table for a recursive-query run.  The output of the recursive-query
105987 ** is added back into the Queue table.  Then another row is extracted from Queue
105988 ** and the iteration continues until the Queue table is empty.
105989 **
105990 ** If the compound query operator is UNION then no duplicate rows are ever
105991 ** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
105992 ** that have ever been inserted into Queue and causes duplicates to be
105993 ** discarded.  If the operator is UNION ALL, then duplicates are allowed.
105994 **
105995 ** If the query has an ORDER BY, then entries in the Queue table are kept in
105996 ** ORDER BY order and the first entry is extracted for each cycle.  Without
105997 ** an ORDER BY, the Queue table is just a FIFO.
105998 **
105999 ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
106000 ** have been output to pDest.  A LIMIT of zero means to output no rows and a
106001 ** negative LIMIT means to output all rows.  If there is also an OFFSET clause
106002 ** with a positive value, then the first OFFSET outputs are discarded rather
106003 ** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
106004 ** rows have been skipped.
106005 */
106006 static void generateWithRecursiveQuery(
106007   Parse *pParse,        /* Parsing context */
106008   Select *p,            /* The recursive SELECT to be coded */
106009   SelectDest *pDest     /* What to do with query results */
106010 ){
106011   SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
106012   int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
106013   Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
106014   Select *pSetup = p->pPrior;   /* The setup query */
106015   int addrTop;                  /* Top of the loop */
106016   int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
106017   int iCurrent = 0;             /* The Current table */
106018   int regCurrent;               /* Register holding Current table */
106019   int iQueue;                   /* The Queue table */
106020   int iDistinct = 0;            /* To ensure unique results if UNION */
106021   int eDest = SRT_Fifo;         /* How to write to Queue */
106022   SelectDest destQueue;         /* SelectDest targetting the Queue table */
106023   int i;                        /* Loop counter */
106024   int rc;                       /* Result code */
106025   ExprList *pOrderBy;           /* The ORDER BY clause */
106026   Expr *pLimit, *pOffset;       /* Saved LIMIT and OFFSET */
106027   int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
106028 
106029   /* Obtain authorization to do a recursive query */
106030   if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
106031 
106032   /* Process the LIMIT and OFFSET clauses, if they exist */
106033   addrBreak = sqlite3VdbeMakeLabel(v);
106034   computeLimitRegisters(pParse, p, addrBreak);
106035   pLimit = p->pLimit;
106036   pOffset = p->pOffset;
106037   regLimit = p->iLimit;
106038   regOffset = p->iOffset;
106039   p->pLimit = p->pOffset = 0;
106040   p->iLimit = p->iOffset = 0;
106041   pOrderBy = p->pOrderBy;
106042 
106043   /* Locate the cursor number of the Current table */
106044   for(i=0; ALWAYS(i<pSrc->nSrc); i++){
106045     if( pSrc->a[i].isRecursive ){
106046       iCurrent = pSrc->a[i].iCursor;
106047       break;
106048     }
106049   }
106050 
106051   /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
106052   ** the Distinct table must be exactly one greater than Queue in order
106053   ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
106054   iQueue = pParse->nTab++;
106055   if( p->op==TK_UNION ){
106056     eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
106057     iDistinct = pParse->nTab++;
106058   }else{
106059     eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
106060   }
106061   sqlite3SelectDestInit(&destQueue, eDest, iQueue);
106062 
106063   /* Allocate cursors for Current, Queue, and Distinct. */
106064   regCurrent = ++pParse->nMem;
106065   sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
106066   if( pOrderBy ){
106067     KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
106068     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
106069                       (char*)pKeyInfo, P4_KEYINFO);
106070     destQueue.pOrderBy = pOrderBy;
106071   }else{
106072     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
106073   }
106074   VdbeComment((v, "Queue table"));
106075   if( iDistinct ){
106076     p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
106077     p->selFlags |= SF_UsesEphemeral;
106078   }
106079 
106080   /* Detach the ORDER BY clause from the compound SELECT */
106081   p->pOrderBy = 0;
106082 
106083   /* Store the results of the setup-query in Queue. */
106084   pSetup->pNext = 0;
106085   rc = sqlite3Select(pParse, pSetup, &destQueue);
106086   pSetup->pNext = p;
106087   if( rc ) goto end_of_recursive_query;
106088 
106089   /* Find the next row in the Queue and output that row */
106090   addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
106091 
106092   /* Transfer the next row in Queue over to Current */
106093   sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
106094   if( pOrderBy ){
106095     sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
106096   }else{
106097     sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
106098   }
106099   sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
106100 
106101   /* Output the single row in Current */
106102   addrCont = sqlite3VdbeMakeLabel(v);
106103   codeOffset(v, regOffset, addrCont);
106104   selectInnerLoop(pParse, p, p->pEList, iCurrent,
106105       0, 0, pDest, addrCont, addrBreak);
106106   if( regLimit ){
106107     sqlite3VdbeAddOp3(v, OP_IfZero, regLimit, addrBreak, -1);
106108     VdbeCoverage(v);
106109   }
106110   sqlite3VdbeResolveLabel(v, addrCont);
106111 
106112   /* Execute the recursive SELECT taking the single row in Current as
106113   ** the value for the recursive-table. Store the results in the Queue.
106114   */
106115   p->pPrior = 0;
106116   sqlite3Select(pParse, p, &destQueue);
106117   assert( p->pPrior==0 );
106118   p->pPrior = pSetup;
106119 
106120   /* Keep running the loop until the Queue is empty */
106121   sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
106122   sqlite3VdbeResolveLabel(v, addrBreak);
106123 
106124 end_of_recursive_query:
106125   sqlite3ExprListDelete(pParse->db, p->pOrderBy);
106126   p->pOrderBy = pOrderBy;
106127   p->pLimit = pLimit;
106128   p->pOffset = pOffset;
106129   return;
106130 }
106131 #endif /* SQLITE_OMIT_CTE */
106132 
106133 /* Forward references */
106134 static int multiSelectOrderBy(
106135   Parse *pParse,        /* Parsing context */
106136   Select *p,            /* The right-most of SELECTs to be coded */
106137   SelectDest *pDest     /* What to do with query results */
106138 );
106139 
106140 
106141 /*
106142 ** This routine is called to process a compound query form from
106143 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
106144 ** INTERSECT
106145 **
106146 ** "p" points to the right-most of the two queries.  the query on the
106147 ** left is p->pPrior.  The left query could also be a compound query
106148 ** in which case this routine will be called recursively.
106149 **
106150 ** The results of the total query are to be written into a destination
106151 ** of type eDest with parameter iParm.
106152 **
106153 ** Example 1:  Consider a three-way compound SQL statement.
106154 **
106155 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
106156 **
106157 ** This statement is parsed up as follows:
106158 **
106159 **     SELECT c FROM t3
106160 **      |
106161 **      `----->  SELECT b FROM t2
106162 **                |
106163 **                `------>  SELECT a FROM t1
106164 **
106165 ** The arrows in the diagram above represent the Select.pPrior pointer.
106166 ** So if this routine is called with p equal to the t3 query, then
106167 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
106168 **
106169 ** Notice that because of the way SQLite parses compound SELECTs, the
106170 ** individual selects always group from left to right.
106171 */
106172 static int multiSelect(
106173   Parse *pParse,        /* Parsing context */
106174   Select *p,            /* The right-most of SELECTs to be coded */
106175   SelectDest *pDest     /* What to do with query results */
106176 ){
106177   int rc = SQLITE_OK;   /* Success code from a subroutine */
106178   Select *pPrior;       /* Another SELECT immediately to our left */
106179   Vdbe *v;              /* Generate code to this VDBE */
106180   SelectDest dest;      /* Alternative data destination */
106181   Select *pDelete = 0;  /* Chain of simple selects to delete */
106182   sqlite3 *db;          /* Database connection */
106183 #ifndef SQLITE_OMIT_EXPLAIN
106184   int iSub1 = 0;        /* EQP id of left-hand query */
106185   int iSub2 = 0;        /* EQP id of right-hand query */
106186 #endif
106187 
106188   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
106189   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
106190   */
106191   assert( p && p->pPrior );  /* Calling function guarantees this much */
106192   assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
106193   db = pParse->db;
106194   pPrior = p->pPrior;
106195   dest = *pDest;
106196   if( pPrior->pOrderBy ){
106197     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
106198       selectOpName(p->op));
106199     rc = 1;
106200     goto multi_select_end;
106201   }
106202   if( pPrior->pLimit ){
106203     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
106204       selectOpName(p->op));
106205     rc = 1;
106206     goto multi_select_end;
106207   }
106208 
106209   v = sqlite3GetVdbe(pParse);
106210   assert( v!=0 );  /* The VDBE already created by calling function */
106211 
106212   /* Create the destination temporary table if necessary
106213   */
106214   if( dest.eDest==SRT_EphemTab ){
106215     assert( p->pEList );
106216     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
106217     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
106218     dest.eDest = SRT_Table;
106219   }
106220 
106221   /* Make sure all SELECTs in the statement have the same number of elements
106222   ** in their result sets.
106223   */
106224   assert( p->pEList && pPrior->pEList );
106225   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
106226     if( p->selFlags & SF_Values ){
106227       sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
106228     }else{
106229       sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
106230         " do not have the same number of result columns", selectOpName(p->op));
106231     }
106232     rc = 1;
106233     goto multi_select_end;
106234   }
106235 
106236 #ifndef SQLITE_OMIT_CTE
106237   if( p->selFlags & SF_Recursive ){
106238     generateWithRecursiveQuery(pParse, p, &dest);
106239   }else
106240 #endif
106241 
106242   /* Compound SELECTs that have an ORDER BY clause are handled separately.
106243   */
106244   if( p->pOrderBy ){
106245     return multiSelectOrderBy(pParse, p, pDest);
106246   }else
106247 
106248   /* Generate code for the left and right SELECT statements.
106249   */
106250   switch( p->op ){
106251     case TK_ALL: {
106252       int addr = 0;
106253       int nLimit;
106254       assert( !pPrior->pLimit );
106255       pPrior->iLimit = p->iLimit;
106256       pPrior->iOffset = p->iOffset;
106257       pPrior->pLimit = p->pLimit;
106258       pPrior->pOffset = p->pOffset;
106259       explainSetInteger(iSub1, pParse->iNextSelectId);
106260       rc = sqlite3Select(pParse, pPrior, &dest);
106261       p->pLimit = 0;
106262       p->pOffset = 0;
106263       if( rc ){
106264         goto multi_select_end;
106265       }
106266       p->pPrior = 0;
106267       p->iLimit = pPrior->iLimit;
106268       p->iOffset = pPrior->iOffset;
106269       if( p->iLimit ){
106270         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit); VdbeCoverage(v);
106271         VdbeComment((v, "Jump ahead if LIMIT reached"));
106272       }
106273       explainSetInteger(iSub2, pParse->iNextSelectId);
106274       rc = sqlite3Select(pParse, p, &dest);
106275       testcase( rc!=SQLITE_OK );
106276       pDelete = p->pPrior;
106277       p->pPrior = pPrior;
106278       p->nSelectRow += pPrior->nSelectRow;
106279       if( pPrior->pLimit
106280        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
106281        && nLimit>0 && p->nSelectRow > (u64)nLimit
106282       ){
106283         p->nSelectRow = nLimit;
106284       }
106285       if( addr ){
106286         sqlite3VdbeJumpHere(v, addr);
106287       }
106288       break;
106289     }
106290     case TK_EXCEPT:
106291     case TK_UNION: {
106292       int unionTab;    /* Cursor number of the temporary table holding result */
106293       u8 op = 0;       /* One of the SRT_ operations to apply to self */
106294       int priorOp;     /* The SRT_ operation to apply to prior selects */
106295       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
106296       int addr;
106297       SelectDest uniondest;
106298 
106299       testcase( p->op==TK_EXCEPT );
106300       testcase( p->op==TK_UNION );
106301       priorOp = SRT_Union;
106302       if( dest.eDest==priorOp ){
106303         /* We can reuse a temporary table generated by a SELECT to our
106304         ** right.
106305         */
106306         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
106307         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
106308         unionTab = dest.iSDParm;
106309       }else{
106310         /* We will need to create our own temporary table to hold the
106311         ** intermediate results.
106312         */
106313         unionTab = pParse->nTab++;
106314         assert( p->pOrderBy==0 );
106315         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
106316         assert( p->addrOpenEphm[0] == -1 );
106317         p->addrOpenEphm[0] = addr;
106318         findRightmost(p)->selFlags |= SF_UsesEphemeral;
106319         assert( p->pEList );
106320       }
106321 
106322       /* Code the SELECT statements to our left
106323       */
106324       assert( !pPrior->pOrderBy );
106325       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
106326       explainSetInteger(iSub1, pParse->iNextSelectId);
106327       rc = sqlite3Select(pParse, pPrior, &uniondest);
106328       if( rc ){
106329         goto multi_select_end;
106330       }
106331 
106332       /* Code the current SELECT statement
106333       */
106334       if( p->op==TK_EXCEPT ){
106335         op = SRT_Except;
106336       }else{
106337         assert( p->op==TK_UNION );
106338         op = SRT_Union;
106339       }
106340       p->pPrior = 0;
106341       pLimit = p->pLimit;
106342       p->pLimit = 0;
106343       pOffset = p->pOffset;
106344       p->pOffset = 0;
106345       uniondest.eDest = op;
106346       explainSetInteger(iSub2, pParse->iNextSelectId);
106347       rc = sqlite3Select(pParse, p, &uniondest);
106348       testcase( rc!=SQLITE_OK );
106349       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
106350       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
106351       sqlite3ExprListDelete(db, p->pOrderBy);
106352       pDelete = p->pPrior;
106353       p->pPrior = pPrior;
106354       p->pOrderBy = 0;
106355       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
106356       sqlite3ExprDelete(db, p->pLimit);
106357       p->pLimit = pLimit;
106358       p->pOffset = pOffset;
106359       p->iLimit = 0;
106360       p->iOffset = 0;
106361 
106362       /* Convert the data in the temporary table into whatever form
106363       ** it is that we currently need.
106364       */
106365       assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
106366       if( dest.eDest!=priorOp ){
106367         int iCont, iBreak, iStart;
106368         assert( p->pEList );
106369         if( dest.eDest==SRT_Output ){
106370           Select *pFirst = p;
106371           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
106372           generateColumnNames(pParse, 0, pFirst->pEList);
106373         }
106374         iBreak = sqlite3VdbeMakeLabel(v);
106375         iCont = sqlite3VdbeMakeLabel(v);
106376         computeLimitRegisters(pParse, p, iBreak);
106377         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
106378         iStart = sqlite3VdbeCurrentAddr(v);
106379         selectInnerLoop(pParse, p, p->pEList, unionTab,
106380                         0, 0, &dest, iCont, iBreak);
106381         sqlite3VdbeResolveLabel(v, iCont);
106382         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
106383         sqlite3VdbeResolveLabel(v, iBreak);
106384         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
106385       }
106386       break;
106387     }
106388     default: assert( p->op==TK_INTERSECT ); {
106389       int tab1, tab2;
106390       int iCont, iBreak, iStart;
106391       Expr *pLimit, *pOffset;
106392       int addr;
106393       SelectDest intersectdest;
106394       int r1;
106395 
106396       /* INTERSECT is different from the others since it requires
106397       ** two temporary tables.  Hence it has its own case.  Begin
106398       ** by allocating the tables we will need.
106399       */
106400       tab1 = pParse->nTab++;
106401       tab2 = pParse->nTab++;
106402       assert( p->pOrderBy==0 );
106403 
106404       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
106405       assert( p->addrOpenEphm[0] == -1 );
106406       p->addrOpenEphm[0] = addr;
106407       findRightmost(p)->selFlags |= SF_UsesEphemeral;
106408       assert( p->pEList );
106409 
106410       /* Code the SELECTs to our left into temporary table "tab1".
106411       */
106412       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
106413       explainSetInteger(iSub1, pParse->iNextSelectId);
106414       rc = sqlite3Select(pParse, pPrior, &intersectdest);
106415       if( rc ){
106416         goto multi_select_end;
106417       }
106418 
106419       /* Code the current SELECT into temporary table "tab2"
106420       */
106421       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
106422       assert( p->addrOpenEphm[1] == -1 );
106423       p->addrOpenEphm[1] = addr;
106424       p->pPrior = 0;
106425       pLimit = p->pLimit;
106426       p->pLimit = 0;
106427       pOffset = p->pOffset;
106428       p->pOffset = 0;
106429       intersectdest.iSDParm = tab2;
106430       explainSetInteger(iSub2, pParse->iNextSelectId);
106431       rc = sqlite3Select(pParse, p, &intersectdest);
106432       testcase( rc!=SQLITE_OK );
106433       pDelete = p->pPrior;
106434       p->pPrior = pPrior;
106435       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
106436       sqlite3ExprDelete(db, p->pLimit);
106437       p->pLimit = pLimit;
106438       p->pOffset = pOffset;
106439 
106440       /* Generate code to take the intersection of the two temporary
106441       ** tables.
106442       */
106443       assert( p->pEList );
106444       if( dest.eDest==SRT_Output ){
106445         Select *pFirst = p;
106446         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
106447         generateColumnNames(pParse, 0, pFirst->pEList);
106448       }
106449       iBreak = sqlite3VdbeMakeLabel(v);
106450       iCont = sqlite3VdbeMakeLabel(v);
106451       computeLimitRegisters(pParse, p, iBreak);
106452       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
106453       r1 = sqlite3GetTempReg(pParse);
106454       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
106455       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
106456       sqlite3ReleaseTempReg(pParse, r1);
106457       selectInnerLoop(pParse, p, p->pEList, tab1,
106458                       0, 0, &dest, iCont, iBreak);
106459       sqlite3VdbeResolveLabel(v, iCont);
106460       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
106461       sqlite3VdbeResolveLabel(v, iBreak);
106462       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
106463       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
106464       break;
106465     }
106466   }
106467 
106468   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
106469 
106470   /* Compute collating sequences used by
106471   ** temporary tables needed to implement the compound select.
106472   ** Attach the KeyInfo structure to all temporary tables.
106473   **
106474   ** This section is run by the right-most SELECT statement only.
106475   ** SELECT statements to the left always skip this part.  The right-most
106476   ** SELECT might also skip this part if it has no ORDER BY clause and
106477   ** no temp tables are required.
106478   */
106479   if( p->selFlags & SF_UsesEphemeral ){
106480     int i;                        /* Loop counter */
106481     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
106482     Select *pLoop;                /* For looping through SELECT statements */
106483     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
106484     int nCol;                     /* Number of columns in result set */
106485 
106486     assert( p->pNext==0 );
106487     nCol = p->pEList->nExpr;
106488     pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
106489     if( !pKeyInfo ){
106490       rc = SQLITE_NOMEM;
106491       goto multi_select_end;
106492     }
106493     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
106494       *apColl = multiSelectCollSeq(pParse, p, i);
106495       if( 0==*apColl ){
106496         *apColl = db->pDfltColl;
106497       }
106498     }
106499 
106500     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
106501       for(i=0; i<2; i++){
106502         int addr = pLoop->addrOpenEphm[i];
106503         if( addr<0 ){
106504           /* If [0] is unused then [1] is also unused.  So we can
106505           ** always safely abort as soon as the first unused slot is found */
106506           assert( pLoop->addrOpenEphm[1]<0 );
106507           break;
106508         }
106509         sqlite3VdbeChangeP2(v, addr, nCol);
106510         sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
106511                             P4_KEYINFO);
106512         pLoop->addrOpenEphm[i] = -1;
106513       }
106514     }
106515     sqlite3KeyInfoUnref(pKeyInfo);
106516   }
106517 
106518 multi_select_end:
106519   pDest->iSdst = dest.iSdst;
106520   pDest->nSdst = dest.nSdst;
106521   sqlite3SelectDelete(db, pDelete);
106522   return rc;
106523 }
106524 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
106525 
106526 /*
106527 ** Code an output subroutine for a coroutine implementation of a
106528 ** SELECT statment.
106529 **
106530 ** The data to be output is contained in pIn->iSdst.  There are
106531 ** pIn->nSdst columns to be output.  pDest is where the output should
106532 ** be sent.
106533 **
106534 ** regReturn is the number of the register holding the subroutine
106535 ** return address.
106536 **
106537 ** If regPrev>0 then it is the first register in a vector that
106538 ** records the previous output.  mem[regPrev] is a flag that is false
106539 ** if there has been no previous output.  If regPrev>0 then code is
106540 ** generated to suppress duplicates.  pKeyInfo is used for comparing
106541 ** keys.
106542 **
106543 ** If the LIMIT found in p->iLimit is reached, jump immediately to
106544 ** iBreak.
106545 */
106546 static int generateOutputSubroutine(
106547   Parse *pParse,          /* Parsing context */
106548   Select *p,              /* The SELECT statement */
106549   SelectDest *pIn,        /* Coroutine supplying data */
106550   SelectDest *pDest,      /* Where to send the data */
106551   int regReturn,          /* The return address register */
106552   int regPrev,            /* Previous result register.  No uniqueness if 0 */
106553   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
106554   int iBreak              /* Jump here if we hit the LIMIT */
106555 ){
106556   Vdbe *v = pParse->pVdbe;
106557   int iContinue;
106558   int addr;
106559 
106560   addr = sqlite3VdbeCurrentAddr(v);
106561   iContinue = sqlite3VdbeMakeLabel(v);
106562 
106563   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
106564   */
106565   if( regPrev ){
106566     int j1, j2;
106567     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
106568     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
106569                               (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
106570     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); VdbeCoverage(v);
106571     sqlite3VdbeJumpHere(v, j1);
106572     sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
106573     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
106574   }
106575   if( pParse->db->mallocFailed ) return 0;
106576 
106577   /* Suppress the first OFFSET entries if there is an OFFSET clause
106578   */
106579   codeOffset(v, p->iOffset, iContinue);
106580 
106581   switch( pDest->eDest ){
106582     /* Store the result as data using a unique key.
106583     */
106584     case SRT_Table:
106585     case SRT_EphemTab: {
106586       int r1 = sqlite3GetTempReg(pParse);
106587       int r2 = sqlite3GetTempReg(pParse);
106588       testcase( pDest->eDest==SRT_Table );
106589       testcase( pDest->eDest==SRT_EphemTab );
106590       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
106591       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
106592       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
106593       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
106594       sqlite3ReleaseTempReg(pParse, r2);
106595       sqlite3ReleaseTempReg(pParse, r1);
106596       break;
106597     }
106598 
106599 #ifndef SQLITE_OMIT_SUBQUERY
106600     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
106601     ** then there should be a single item on the stack.  Write this
106602     ** item into the set table with bogus data.
106603     */
106604     case SRT_Set: {
106605       int r1;
106606       assert( pIn->nSdst==1 );
106607       pDest->affSdst =
106608          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
106609       r1 = sqlite3GetTempReg(pParse);
106610       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
106611       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
106612       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
106613       sqlite3ReleaseTempReg(pParse, r1);
106614       break;
106615     }
106616 
106617 #if 0  /* Never occurs on an ORDER BY query */
106618     /* If any row exist in the result set, record that fact and abort.
106619     */
106620     case SRT_Exists: {
106621       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
106622       /* The LIMIT clause will terminate the loop for us */
106623       break;
106624     }
106625 #endif
106626 
106627     /* If this is a scalar select that is part of an expression, then
106628     ** store the results in the appropriate memory cell and break out
106629     ** of the scan loop.
106630     */
106631     case SRT_Mem: {
106632       assert( pIn->nSdst==1 );
106633       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
106634       /* The LIMIT clause will jump out of the loop for us */
106635       break;
106636     }
106637 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
106638 
106639     /* The results are stored in a sequence of registers
106640     ** starting at pDest->iSdst.  Then the co-routine yields.
106641     */
106642     case SRT_Coroutine: {
106643       if( pDest->iSdst==0 ){
106644         pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
106645         pDest->nSdst = pIn->nSdst;
106646       }
106647       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
106648       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
106649       break;
106650     }
106651 
106652     /* If none of the above, then the result destination must be
106653     ** SRT_Output.  This routine is never called with any other
106654     ** destination other than the ones handled above or SRT_Output.
106655     **
106656     ** For SRT_Output, results are stored in a sequence of registers.
106657     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
106658     ** return the next row of result.
106659     */
106660     default: {
106661       assert( pDest->eDest==SRT_Output );
106662       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
106663       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
106664       break;
106665     }
106666   }
106667 
106668   /* Jump to the end of the loop if the LIMIT is reached.
106669   */
106670   if( p->iLimit ){
106671     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v);
106672   }
106673 
106674   /* Generate the subroutine return
106675   */
106676   sqlite3VdbeResolveLabel(v, iContinue);
106677   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
106678 
106679   return addr;
106680 }
106681 
106682 /*
106683 ** Alternative compound select code generator for cases when there
106684 ** is an ORDER BY clause.
106685 **
106686 ** We assume a query of the following form:
106687 **
106688 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
106689 **
106690 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
106691 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
106692 ** co-routines.  Then run the co-routines in parallel and merge the results
106693 ** into the output.  In addition to the two coroutines (called selectA and
106694 ** selectB) there are 7 subroutines:
106695 **
106696 **    outA:    Move the output of the selectA coroutine into the output
106697 **             of the compound query.
106698 **
106699 **    outB:    Move the output of the selectB coroutine into the output
106700 **             of the compound query.  (Only generated for UNION and
106701 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
106702 **             appears only in B.)
106703 **
106704 **    AltB:    Called when there is data from both coroutines and A<B.
106705 **
106706 **    AeqB:    Called when there is data from both coroutines and A==B.
106707 **
106708 **    AgtB:    Called when there is data from both coroutines and A>B.
106709 **
106710 **    EofA:    Called when data is exhausted from selectA.
106711 **
106712 **    EofB:    Called when data is exhausted from selectB.
106713 **
106714 ** The implementation of the latter five subroutines depend on which
106715 ** <operator> is used:
106716 **
106717 **
106718 **             UNION ALL         UNION            EXCEPT          INTERSECT
106719 **          -------------  -----------------  --------------  -----------------
106720 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
106721 **
106722 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
106723 **
106724 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
106725 **
106726 **   EofA:   outB, nextB      outB, nextB          halt             halt
106727 **
106728 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
106729 **
106730 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
106731 ** causes an immediate jump to EofA and an EOF on B following nextB causes
106732 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
106733 ** following nextX causes a jump to the end of the select processing.
106734 **
106735 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
106736 ** within the output subroutine.  The regPrev register set holds the previously
106737 ** output value.  A comparison is made against this value and the output
106738 ** is skipped if the next results would be the same as the previous.
106739 **
106740 ** The implementation plan is to implement the two coroutines and seven
106741 ** subroutines first, then put the control logic at the bottom.  Like this:
106742 **
106743 **          goto Init
106744 **     coA: coroutine for left query (A)
106745 **     coB: coroutine for right query (B)
106746 **    outA: output one row of A
106747 **    outB: output one row of B (UNION and UNION ALL only)
106748 **    EofA: ...
106749 **    EofB: ...
106750 **    AltB: ...
106751 **    AeqB: ...
106752 **    AgtB: ...
106753 **    Init: initialize coroutine registers
106754 **          yield coA
106755 **          if eof(A) goto EofA
106756 **          yield coB
106757 **          if eof(B) goto EofB
106758 **    Cmpr: Compare A, B
106759 **          Jump AltB, AeqB, AgtB
106760 **     End: ...
106761 **
106762 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
106763 ** actually called using Gosub and they do not Return.  EofA and EofB loop
106764 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
106765 ** and AgtB jump to either L2 or to one of EofA or EofB.
106766 */
106767 #ifndef SQLITE_OMIT_COMPOUND_SELECT
106768 static int multiSelectOrderBy(
106769   Parse *pParse,        /* Parsing context */
106770   Select *p,            /* The right-most of SELECTs to be coded */
106771   SelectDest *pDest     /* What to do with query results */
106772 ){
106773   int i, j;             /* Loop counters */
106774   Select *pPrior;       /* Another SELECT immediately to our left */
106775   Vdbe *v;              /* Generate code to this VDBE */
106776   SelectDest destA;     /* Destination for coroutine A */
106777   SelectDest destB;     /* Destination for coroutine B */
106778   int regAddrA;         /* Address register for select-A coroutine */
106779   int regAddrB;         /* Address register for select-B coroutine */
106780   int addrSelectA;      /* Address of the select-A coroutine */
106781   int addrSelectB;      /* Address of the select-B coroutine */
106782   int regOutA;          /* Address register for the output-A subroutine */
106783   int regOutB;          /* Address register for the output-B subroutine */
106784   int addrOutA;         /* Address of the output-A subroutine */
106785   int addrOutB = 0;     /* Address of the output-B subroutine */
106786   int addrEofA;         /* Address of the select-A-exhausted subroutine */
106787   int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */
106788   int addrEofB;         /* Address of the select-B-exhausted subroutine */
106789   int addrAltB;         /* Address of the A<B subroutine */
106790   int addrAeqB;         /* Address of the A==B subroutine */
106791   int addrAgtB;         /* Address of the A>B subroutine */
106792   int regLimitA;        /* Limit register for select-A */
106793   int regLimitB;        /* Limit register for select-A */
106794   int regPrev;          /* A range of registers to hold previous output */
106795   int savedLimit;       /* Saved value of p->iLimit */
106796   int savedOffset;      /* Saved value of p->iOffset */
106797   int labelCmpr;        /* Label for the start of the merge algorithm */
106798   int labelEnd;         /* Label for the end of the overall SELECT stmt */
106799   int j1;               /* Jump instructions that get retargetted */
106800   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
106801   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
106802   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
106803   sqlite3 *db;          /* Database connection */
106804   ExprList *pOrderBy;   /* The ORDER BY clause */
106805   int nOrderBy;         /* Number of terms in the ORDER BY clause */
106806   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
106807 #ifndef SQLITE_OMIT_EXPLAIN
106808   int iSub1;            /* EQP id of left-hand query */
106809   int iSub2;            /* EQP id of right-hand query */
106810 #endif
106811 
106812   assert( p->pOrderBy!=0 );
106813   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
106814   db = pParse->db;
106815   v = pParse->pVdbe;
106816   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
106817   labelEnd = sqlite3VdbeMakeLabel(v);
106818   labelCmpr = sqlite3VdbeMakeLabel(v);
106819 
106820 
106821   /* Patch up the ORDER BY clause
106822   */
106823   op = p->op;
106824   pPrior = p->pPrior;
106825   assert( pPrior->pOrderBy==0 );
106826   pOrderBy = p->pOrderBy;
106827   assert( pOrderBy );
106828   nOrderBy = pOrderBy->nExpr;
106829 
106830   /* For operators other than UNION ALL we have to make sure that
106831   ** the ORDER BY clause covers every term of the result set.  Add
106832   ** terms to the ORDER BY clause as necessary.
106833   */
106834   if( op!=TK_ALL ){
106835     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
106836       struct ExprList_item *pItem;
106837       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
106838         assert( pItem->u.x.iOrderByCol>0 );
106839         if( pItem->u.x.iOrderByCol==i ) break;
106840       }
106841       if( j==nOrderBy ){
106842         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
106843         if( pNew==0 ) return SQLITE_NOMEM;
106844         pNew->flags |= EP_IntValue;
106845         pNew->u.iValue = i;
106846         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
106847         if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
106848       }
106849     }
106850   }
106851 
106852   /* Compute the comparison permutation and keyinfo that is used with
106853   ** the permutation used to determine if the next
106854   ** row of results comes from selectA or selectB.  Also add explicit
106855   ** collations to the ORDER BY clause terms so that when the subqueries
106856   ** to the right and the left are evaluated, they use the correct
106857   ** collation.
106858   */
106859   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
106860   if( aPermute ){
106861     struct ExprList_item *pItem;
106862     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
106863       assert( pItem->u.x.iOrderByCol>0
106864           && pItem->u.x.iOrderByCol<=p->pEList->nExpr );
106865       aPermute[i] = pItem->u.x.iOrderByCol - 1;
106866     }
106867     pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
106868   }else{
106869     pKeyMerge = 0;
106870   }
106871 
106872   /* Reattach the ORDER BY clause to the query.
106873   */
106874   p->pOrderBy = pOrderBy;
106875   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
106876 
106877   /* Allocate a range of temporary registers and the KeyInfo needed
106878   ** for the logic that removes duplicate result rows when the
106879   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
106880   */
106881   if( op==TK_ALL ){
106882     regPrev = 0;
106883   }else{
106884     int nExpr = p->pEList->nExpr;
106885     assert( nOrderBy>=nExpr || db->mallocFailed );
106886     regPrev = pParse->nMem+1;
106887     pParse->nMem += nExpr+1;
106888     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
106889     pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
106890     if( pKeyDup ){
106891       assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
106892       for(i=0; i<nExpr; i++){
106893         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
106894         pKeyDup->aSortOrder[i] = 0;
106895       }
106896     }
106897   }
106898 
106899   /* Separate the left and the right query from one another
106900   */
106901   p->pPrior = 0;
106902   pPrior->pNext = 0;
106903   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
106904   if( pPrior->pPrior==0 ){
106905     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
106906   }
106907 
106908   /* Compute the limit registers */
106909   computeLimitRegisters(pParse, p, labelEnd);
106910   if( p->iLimit && op==TK_ALL ){
106911     regLimitA = ++pParse->nMem;
106912     regLimitB = ++pParse->nMem;
106913     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
106914                                   regLimitA);
106915     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
106916   }else{
106917     regLimitA = regLimitB = 0;
106918   }
106919   sqlite3ExprDelete(db, p->pLimit);
106920   p->pLimit = 0;
106921   sqlite3ExprDelete(db, p->pOffset);
106922   p->pOffset = 0;
106923 
106924   regAddrA = ++pParse->nMem;
106925   regAddrB = ++pParse->nMem;
106926   regOutA = ++pParse->nMem;
106927   regOutB = ++pParse->nMem;
106928   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
106929   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
106930 
106931   /* Generate a coroutine to evaluate the SELECT statement to the
106932   ** left of the compound operator - the "A" select.
106933   */
106934   addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
106935   j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
106936   VdbeComment((v, "left SELECT"));
106937   pPrior->iLimit = regLimitA;
106938   explainSetInteger(iSub1, pParse->iNextSelectId);
106939   sqlite3Select(pParse, pPrior, &destA);
106940   sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrA);
106941   sqlite3VdbeJumpHere(v, j1);
106942 
106943   /* Generate a coroutine to evaluate the SELECT statement on
106944   ** the right - the "B" select
106945   */
106946   addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
106947   j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
106948   VdbeComment((v, "right SELECT"));
106949   savedLimit = p->iLimit;
106950   savedOffset = p->iOffset;
106951   p->iLimit = regLimitB;
106952   p->iOffset = 0;
106953   explainSetInteger(iSub2, pParse->iNextSelectId);
106954   sqlite3Select(pParse, p, &destB);
106955   p->iLimit = savedLimit;
106956   p->iOffset = savedOffset;
106957   sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrB);
106958 
106959   /* Generate a subroutine that outputs the current row of the A
106960   ** select as the next output row of the compound select.
106961   */
106962   VdbeNoopComment((v, "Output routine for A"));
106963   addrOutA = generateOutputSubroutine(pParse,
106964                  p, &destA, pDest, regOutA,
106965                  regPrev, pKeyDup, labelEnd);
106966 
106967   /* Generate a subroutine that outputs the current row of the B
106968   ** select as the next output row of the compound select.
106969   */
106970   if( op==TK_ALL || op==TK_UNION ){
106971     VdbeNoopComment((v, "Output routine for B"));
106972     addrOutB = generateOutputSubroutine(pParse,
106973                  p, &destB, pDest, regOutB,
106974                  regPrev, pKeyDup, labelEnd);
106975   }
106976   sqlite3KeyInfoUnref(pKeyDup);
106977 
106978   /* Generate a subroutine to run when the results from select A
106979   ** are exhausted and only data in select B remains.
106980   */
106981   if( op==TK_EXCEPT || op==TK_INTERSECT ){
106982     addrEofA_noB = addrEofA = labelEnd;
106983   }else{
106984     VdbeNoopComment((v, "eof-A subroutine"));
106985     addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
106986     addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
106987                                      VdbeCoverage(v);
106988     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
106989     p->nSelectRow += pPrior->nSelectRow;
106990   }
106991 
106992   /* Generate a subroutine to run when the results from select B
106993   ** are exhausted and only data in select A remains.
106994   */
106995   if( op==TK_INTERSECT ){
106996     addrEofB = addrEofA;
106997     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
106998   }else{
106999     VdbeNoopComment((v, "eof-B subroutine"));
107000     addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
107001     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
107002     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
107003   }
107004 
107005   /* Generate code to handle the case of A<B
107006   */
107007   VdbeNoopComment((v, "A-lt-B subroutine"));
107008   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
107009   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
107010   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
107011 
107012   /* Generate code to handle the case of A==B
107013   */
107014   if( op==TK_ALL ){
107015     addrAeqB = addrAltB;
107016   }else if( op==TK_INTERSECT ){
107017     addrAeqB = addrAltB;
107018     addrAltB++;
107019   }else{
107020     VdbeNoopComment((v, "A-eq-B subroutine"));
107021     addrAeqB =
107022     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
107023     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
107024   }
107025 
107026   /* Generate code to handle the case of A>B
107027   */
107028   VdbeNoopComment((v, "A-gt-B subroutine"));
107029   addrAgtB = sqlite3VdbeCurrentAddr(v);
107030   if( op==TK_ALL || op==TK_UNION ){
107031     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
107032   }
107033   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
107034   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
107035 
107036   /* This code runs once to initialize everything.
107037   */
107038   sqlite3VdbeJumpHere(v, j1);
107039   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
107040   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
107041 
107042   /* Implement the main merge loop
107043   */
107044   sqlite3VdbeResolveLabel(v, labelCmpr);
107045   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
107046   sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
107047                          (char*)pKeyMerge, P4_KEYINFO);
107048   sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
107049   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
107050 
107051   /* Jump to the this point in order to terminate the query.
107052   */
107053   sqlite3VdbeResolveLabel(v, labelEnd);
107054 
107055   /* Set the number of output columns
107056   */
107057   if( pDest->eDest==SRT_Output ){
107058     Select *pFirst = pPrior;
107059     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
107060     generateColumnNames(pParse, 0, pFirst->pEList);
107061   }
107062 
107063   /* Reassembly the compound query so that it will be freed correctly
107064   ** by the calling function */
107065   if( p->pPrior ){
107066     sqlite3SelectDelete(db, p->pPrior);
107067   }
107068   p->pPrior = pPrior;
107069   pPrior->pNext = p;
107070 
107071   /*** TBD:  Insert subroutine calls to close cursors on incomplete
107072   **** subqueries ****/
107073   explainComposite(pParse, p->op, iSub1, iSub2, 0);
107074   return SQLITE_OK;
107075 }
107076 #endif
107077 
107078 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
107079 /* Forward Declarations */
107080 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
107081 static void substSelect(sqlite3*, Select *, int, ExprList *);
107082 
107083 /*
107084 ** Scan through the expression pExpr.  Replace every reference to
107085 ** a column in table number iTable with a copy of the iColumn-th
107086 ** entry in pEList.  (But leave references to the ROWID column
107087 ** unchanged.)
107088 **
107089 ** This routine is part of the flattening procedure.  A subquery
107090 ** whose result set is defined by pEList appears as entry in the
107091 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
107092 ** FORM clause entry is iTable.  This routine make the necessary
107093 ** changes to pExpr so that it refers directly to the source table
107094 ** of the subquery rather the result set of the subquery.
107095 */
107096 static Expr *substExpr(
107097   sqlite3 *db,        /* Report malloc errors to this connection */
107098   Expr *pExpr,        /* Expr in which substitution occurs */
107099   int iTable,         /* Table to be substituted */
107100   ExprList *pEList    /* Substitute expressions */
107101 ){
107102   if( pExpr==0 ) return 0;
107103   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
107104     if( pExpr->iColumn<0 ){
107105       pExpr->op = TK_NULL;
107106     }else{
107107       Expr *pNew;
107108       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
107109       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
107110       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
107111       sqlite3ExprDelete(db, pExpr);
107112       pExpr = pNew;
107113     }
107114   }else{
107115     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
107116     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
107117     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
107118       substSelect(db, pExpr->x.pSelect, iTable, pEList);
107119     }else{
107120       substExprList(db, pExpr->x.pList, iTable, pEList);
107121     }
107122   }
107123   return pExpr;
107124 }
107125 static void substExprList(
107126   sqlite3 *db,         /* Report malloc errors here */
107127   ExprList *pList,     /* List to scan and in which to make substitutes */
107128   int iTable,          /* Table to be substituted */
107129   ExprList *pEList     /* Substitute values */
107130 ){
107131   int i;
107132   if( pList==0 ) return;
107133   for(i=0; i<pList->nExpr; i++){
107134     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
107135   }
107136 }
107137 static void substSelect(
107138   sqlite3 *db,         /* Report malloc errors here */
107139   Select *p,           /* SELECT statement in which to make substitutions */
107140   int iTable,          /* Table to be replaced */
107141   ExprList *pEList     /* Substitute values */
107142 ){
107143   SrcList *pSrc;
107144   struct SrcList_item *pItem;
107145   int i;
107146   if( !p ) return;
107147   substExprList(db, p->pEList, iTable, pEList);
107148   substExprList(db, p->pGroupBy, iTable, pEList);
107149   substExprList(db, p->pOrderBy, iTable, pEList);
107150   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
107151   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
107152   substSelect(db, p->pPrior, iTable, pEList);
107153   pSrc = p->pSrc;
107154   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
107155   if( ALWAYS(pSrc) ){
107156     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
107157       substSelect(db, pItem->pSelect, iTable, pEList);
107158     }
107159   }
107160 }
107161 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
107162 
107163 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
107164 /*
107165 ** This routine attempts to flatten subqueries as a performance optimization.
107166 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
107167 **
107168 ** To understand the concept of flattening, consider the following
107169 ** query:
107170 **
107171 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
107172 **
107173 ** The default way of implementing this query is to execute the
107174 ** subquery first and store the results in a temporary table, then
107175 ** run the outer query on that temporary table.  This requires two
107176 ** passes over the data.  Furthermore, because the temporary table
107177 ** has no indices, the WHERE clause on the outer query cannot be
107178 ** optimized.
107179 **
107180 ** This routine attempts to rewrite queries such as the above into
107181 ** a single flat select, like this:
107182 **
107183 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
107184 **
107185 ** The code generated for this simplification gives the same result
107186 ** but only has to scan the data once.  And because indices might
107187 ** exist on the table t1, a complete scan of the data might be
107188 ** avoided.
107189 **
107190 ** Flattening is only attempted if all of the following are true:
107191 **
107192 **   (1)  The subquery and the outer query do not both use aggregates.
107193 **
107194 **   (2)  The subquery is not an aggregate or the outer query is not a join.
107195 **
107196 **   (3)  The subquery is not the right operand of a left outer join
107197 **        (Originally ticket #306.  Strengthened by ticket #3300)
107198 **
107199 **   (4)  The subquery is not DISTINCT.
107200 **
107201 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
107202 **        sub-queries that were excluded from this optimization. Restriction
107203 **        (4) has since been expanded to exclude all DISTINCT subqueries.
107204 **
107205 **   (6)  The subquery does not use aggregates or the outer query is not
107206 **        DISTINCT.
107207 **
107208 **   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
107209 **        A FROM clause, consider adding a FROM close with the special
107210 **        table sqlite_once that consists of a single row containing a
107211 **        single NULL.
107212 **
107213 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
107214 **
107215 **   (9)  The subquery does not use LIMIT or the outer query does not use
107216 **        aggregates.
107217 **
107218 **  (**)  Restriction (10) was removed from the code on 2005-02-05 but we
107219 **        accidently carried the comment forward until 2014-09-15.  Original
107220 **        text: "The subquery does not use aggregates or the outer query does not
107221 **        use LIMIT."
107222 **
107223 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
107224 **
107225 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
107226 **        a separate restriction deriving from ticket #350.
107227 **
107228 **  (13)  The subquery and outer query do not both use LIMIT.
107229 **
107230 **  (14)  The subquery does not use OFFSET.
107231 **
107232 **  (15)  The outer query is not part of a compound select or the
107233 **        subquery does not have a LIMIT clause.
107234 **        (See ticket #2339 and ticket [02a8e81d44]).
107235 **
107236 **  (16)  The outer query is not an aggregate or the subquery does
107237 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
107238 **        until we introduced the group_concat() function.
107239 **
107240 **  (17)  The sub-query is not a compound select, or it is a UNION ALL
107241 **        compound clause made up entirely of non-aggregate queries, and
107242 **        the parent query:
107243 **
107244 **          * is not itself part of a compound select,
107245 **          * is not an aggregate or DISTINCT query, and
107246 **          * is not a join
107247 **
107248 **        The parent and sub-query may contain WHERE clauses. Subject to
107249 **        rules (11), (13) and (14), they may also contain ORDER BY,
107250 **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
107251 **        operator other than UNION ALL because all the other compound
107252 **        operators have an implied DISTINCT which is disallowed by
107253 **        restriction (4).
107254 **
107255 **        Also, each component of the sub-query must return the same number
107256 **        of result columns. This is actually a requirement for any compound
107257 **        SELECT statement, but all the code here does is make sure that no
107258 **        such (illegal) sub-query is flattened. The caller will detect the
107259 **        syntax error and return a detailed message.
107260 **
107261 **  (18)  If the sub-query is a compound select, then all terms of the
107262 **        ORDER by clause of the parent must be simple references to
107263 **        columns of the sub-query.
107264 **
107265 **  (19)  The subquery does not use LIMIT or the outer query does not
107266 **        have a WHERE clause.
107267 **
107268 **  (20)  If the sub-query is a compound select, then it must not use
107269 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
107270 **        somewhat by saying that the terms of the ORDER BY clause must
107271 **        appear as unmodified result columns in the outer query.  But we
107272 **        have other optimizations in mind to deal with that case.
107273 **
107274 **  (21)  The subquery does not use LIMIT or the outer query is not
107275 **        DISTINCT.  (See ticket [752e1646fc]).
107276 **
107277 **  (22)  The subquery is not a recursive CTE.
107278 **
107279 **  (23)  The parent is not a recursive CTE, or the sub-query is not a
107280 **        compound query. This restriction is because transforming the
107281 **        parent to a compound query confuses the code that handles
107282 **        recursive queries in multiSelect().
107283 **
107284 **  (24)  The subquery is not an aggregate that uses the built-in min() or
107285 **        or max() functions.  (Without this restriction, a query like:
107286 **        "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
107287 **        return the value X for which Y was maximal.)
107288 **
107289 **
107290 ** In this routine, the "p" parameter is a pointer to the outer query.
107291 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
107292 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
107293 **
107294 ** If flattening is not attempted, this routine is a no-op and returns 0.
107295 ** If flattening is attempted this routine returns 1.
107296 **
107297 ** All of the expression analysis must occur on both the outer query and
107298 ** the subquery before this routine runs.
107299 */
107300 static int flattenSubquery(
107301   Parse *pParse,       /* Parsing context */
107302   Select *p,           /* The parent or outer SELECT statement */
107303   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
107304   int isAgg,           /* True if outer SELECT uses aggregate functions */
107305   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
107306 ){
107307   const char *zSavedAuthContext = pParse->zAuthContext;
107308   Select *pParent;
107309   Select *pSub;       /* The inner query or "subquery" */
107310   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
107311   SrcList *pSrc;      /* The FROM clause of the outer query */
107312   SrcList *pSubSrc;   /* The FROM clause of the subquery */
107313   ExprList *pList;    /* The result set of the outer query */
107314   int iParent;        /* VDBE cursor number of the pSub result set temp table */
107315   int i;              /* Loop counter */
107316   Expr *pWhere;                    /* The WHERE clause */
107317   struct SrcList_item *pSubitem;   /* The subquery */
107318   sqlite3 *db = pParse->db;
107319 
107320   /* Check to see if flattening is permitted.  Return 0 if not.
107321   */
107322   assert( p!=0 );
107323   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
107324   if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
107325   pSrc = p->pSrc;
107326   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
107327   pSubitem = &pSrc->a[iFrom];
107328   iParent = pSubitem->iCursor;
107329   pSub = pSubitem->pSelect;
107330   assert( pSub!=0 );
107331   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
107332   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
107333   pSubSrc = pSub->pSrc;
107334   assert( pSubSrc );
107335   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
107336   ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
107337   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
107338   ** became arbitrary expressions, we were forced to add restrictions (13)
107339   ** and (14). */
107340   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
107341   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
107342   if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
107343     return 0;                                            /* Restriction (15) */
107344   }
107345   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
107346   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
107347   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
107348      return 0;         /* Restrictions (8)(9) */
107349   }
107350   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
107351      return 0;         /* Restriction (6)  */
107352   }
107353   if( p->pOrderBy && pSub->pOrderBy ){
107354      return 0;                                           /* Restriction (11) */
107355   }
107356   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
107357   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
107358   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
107359      return 0;         /* Restriction (21) */
107360   }
107361   testcase( pSub->selFlags & SF_Recursive );
107362   testcase( pSub->selFlags & SF_MinMaxAgg );
107363   if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
107364     return 0; /* Restrictions (22) and (24) */
107365   }
107366   if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
107367     return 0; /* Restriction (23) */
107368   }
107369 
107370   /* OBSOLETE COMMENT 1:
107371   ** Restriction 3:  If the subquery is a join, make sure the subquery is
107372   ** not used as the right operand of an outer join.  Examples of why this
107373   ** is not allowed:
107374   **
107375   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
107376   **
107377   ** If we flatten the above, we would get
107378   **
107379   **         (t1 LEFT OUTER JOIN t2) JOIN t3
107380   **
107381   ** which is not at all the same thing.
107382   **
107383   ** OBSOLETE COMMENT 2:
107384   ** Restriction 12:  If the subquery is the right operand of a left outer
107385   ** join, make sure the subquery has no WHERE clause.
107386   ** An examples of why this is not allowed:
107387   **
107388   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
107389   **
107390   ** If we flatten the above, we would get
107391   **
107392   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
107393   **
107394   ** But the t2.x>0 test will always fail on a NULL row of t2, which
107395   ** effectively converts the OUTER JOIN into an INNER JOIN.
107396   **
107397   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
107398   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
107399   ** is fraught with danger.  Best to avoid the whole thing.  If the
107400   ** subquery is the right term of a LEFT JOIN, then do not flatten.
107401   */
107402   if( (pSubitem->jointype & JT_OUTER)!=0 ){
107403     return 0;
107404   }
107405 
107406   /* Restriction 17: If the sub-query is a compound SELECT, then it must
107407   ** use only the UNION ALL operator. And none of the simple select queries
107408   ** that make up the compound SELECT are allowed to be aggregate or distinct
107409   ** queries.
107410   */
107411   if( pSub->pPrior ){
107412     if( pSub->pOrderBy ){
107413       return 0;  /* Restriction 20 */
107414     }
107415     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
107416       return 0;
107417     }
107418     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
107419       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
107420       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
107421       assert( pSub->pSrc!=0 );
107422       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
107423        || (pSub1->pPrior && pSub1->op!=TK_ALL)
107424        || pSub1->pSrc->nSrc<1
107425        || pSub->pEList->nExpr!=pSub1->pEList->nExpr
107426       ){
107427         return 0;
107428       }
107429       testcase( pSub1->pSrc->nSrc>1 );
107430     }
107431 
107432     /* Restriction 18. */
107433     if( p->pOrderBy ){
107434       int ii;
107435       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
107436         if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
107437       }
107438     }
107439   }
107440 
107441   /***** If we reach this point, flattening is permitted. *****/
107442   SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
107443                    pSub->zSelName, pSub, iFrom));
107444 
107445   /* Authorize the subquery */
107446   pParse->zAuthContext = pSubitem->zName;
107447   TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
107448   testcase( i==SQLITE_DENY );
107449   pParse->zAuthContext = zSavedAuthContext;
107450 
107451   /* If the sub-query is a compound SELECT statement, then (by restrictions
107452   ** 17 and 18 above) it must be a UNION ALL and the parent query must
107453   ** be of the form:
107454   **
107455   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
107456   **
107457   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
107458   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
107459   ** OFFSET clauses and joins them to the left-hand-side of the original
107460   ** using UNION ALL operators. In this case N is the number of simple
107461   ** select statements in the compound sub-query.
107462   **
107463   ** Example:
107464   **
107465   **     SELECT a+1 FROM (
107466   **        SELECT x FROM tab
107467   **        UNION ALL
107468   **        SELECT y FROM tab
107469   **        UNION ALL
107470   **        SELECT abs(z*2) FROM tab2
107471   **     ) WHERE a!=5 ORDER BY 1
107472   **
107473   ** Transformed into:
107474   **
107475   **     SELECT x+1 FROM tab WHERE x+1!=5
107476   **     UNION ALL
107477   **     SELECT y+1 FROM tab WHERE y+1!=5
107478   **     UNION ALL
107479   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
107480   **     ORDER BY 1
107481   **
107482   ** We call this the "compound-subquery flattening".
107483   */
107484   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
107485     Select *pNew;
107486     ExprList *pOrderBy = p->pOrderBy;
107487     Expr *pLimit = p->pLimit;
107488     Expr *pOffset = p->pOffset;
107489     Select *pPrior = p->pPrior;
107490     p->pOrderBy = 0;
107491     p->pSrc = 0;
107492     p->pPrior = 0;
107493     p->pLimit = 0;
107494     p->pOffset = 0;
107495     pNew = sqlite3SelectDup(db, p, 0);
107496     sqlite3SelectSetName(pNew, pSub->zSelName);
107497     p->pOffset = pOffset;
107498     p->pLimit = pLimit;
107499     p->pOrderBy = pOrderBy;
107500     p->pSrc = pSrc;
107501     p->op = TK_ALL;
107502     if( pNew==0 ){
107503       p->pPrior = pPrior;
107504     }else{
107505       pNew->pPrior = pPrior;
107506       if( pPrior ) pPrior->pNext = pNew;
107507       pNew->pNext = p;
107508       p->pPrior = pNew;
107509       SELECTTRACE(2,pParse,p,
107510          ("compound-subquery flattener creates %s.%p as peer\n",
107511          pNew->zSelName, pNew));
107512     }
107513     if( db->mallocFailed ) return 1;
107514   }
107515 
107516   /* Begin flattening the iFrom-th entry of the FROM clause
107517   ** in the outer query.
107518   */
107519   pSub = pSub1 = pSubitem->pSelect;
107520 
107521   /* Delete the transient table structure associated with the
107522   ** subquery
107523   */
107524   sqlite3DbFree(db, pSubitem->zDatabase);
107525   sqlite3DbFree(db, pSubitem->zName);
107526   sqlite3DbFree(db, pSubitem->zAlias);
107527   pSubitem->zDatabase = 0;
107528   pSubitem->zName = 0;
107529   pSubitem->zAlias = 0;
107530   pSubitem->pSelect = 0;
107531 
107532   /* Defer deleting the Table object associated with the
107533   ** subquery until code generation is
107534   ** complete, since there may still exist Expr.pTab entries that
107535   ** refer to the subquery even after flattening.  Ticket #3346.
107536   **
107537   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
107538   */
107539   if( ALWAYS(pSubitem->pTab!=0) ){
107540     Table *pTabToDel = pSubitem->pTab;
107541     if( pTabToDel->nRef==1 ){
107542       Parse *pToplevel = sqlite3ParseToplevel(pParse);
107543       pTabToDel->pNextZombie = pToplevel->pZombieTab;
107544       pToplevel->pZombieTab = pTabToDel;
107545     }else{
107546       pTabToDel->nRef--;
107547     }
107548     pSubitem->pTab = 0;
107549   }
107550 
107551   /* The following loop runs once for each term in a compound-subquery
107552   ** flattening (as described above).  If we are doing a different kind
107553   ** of flattening - a flattening other than a compound-subquery flattening -
107554   ** then this loop only runs once.
107555   **
107556   ** This loop moves all of the FROM elements of the subquery into the
107557   ** the FROM clause of the outer query.  Before doing this, remember
107558   ** the cursor number for the original outer query FROM element in
107559   ** iParent.  The iParent cursor will never be used.  Subsequent code
107560   ** will scan expressions looking for iParent references and replace
107561   ** those references with expressions that resolve to the subquery FROM
107562   ** elements we are now copying in.
107563   */
107564   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
107565     int nSubSrc;
107566     u8 jointype = 0;
107567     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
107568     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
107569     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
107570 
107571     if( pSrc ){
107572       assert( pParent==p );  /* First time through the loop */
107573       jointype = pSubitem->jointype;
107574     }else{
107575       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
107576       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
107577       if( pSrc==0 ){
107578         assert( db->mallocFailed );
107579         break;
107580       }
107581     }
107582 
107583     /* The subquery uses a single slot of the FROM clause of the outer
107584     ** query.  If the subquery has more than one element in its FROM clause,
107585     ** then expand the outer query to make space for it to hold all elements
107586     ** of the subquery.
107587     **
107588     ** Example:
107589     **
107590     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
107591     **
107592     ** The outer query has 3 slots in its FROM clause.  One slot of the
107593     ** outer query (the middle slot) is used by the subquery.  The next
107594     ** block of code will expand the out query to 4 slots.  The middle
107595     ** slot is expanded to two slots in order to make space for the
107596     ** two elements in the FROM clause of the subquery.
107597     */
107598     if( nSubSrc>1 ){
107599       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
107600       if( db->mallocFailed ){
107601         break;
107602       }
107603     }
107604 
107605     /* Transfer the FROM clause terms from the subquery into the
107606     ** outer query.
107607     */
107608     for(i=0; i<nSubSrc; i++){
107609       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
107610       pSrc->a[i+iFrom] = pSubSrc->a[i];
107611       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
107612     }
107613     pSrc->a[iFrom].jointype = jointype;
107614 
107615     /* Now begin substituting subquery result set expressions for
107616     ** references to the iParent in the outer query.
107617     **
107618     ** Example:
107619     **
107620     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
107621     **   \                     \_____________ subquery __________/          /
107622     **    \_____________________ outer query ______________________________/
107623     **
107624     ** We look at every expression in the outer query and every place we see
107625     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
107626     */
107627     pList = pParent->pEList;
107628     for(i=0; i<pList->nExpr; i++){
107629       if( pList->a[i].zName==0 ){
107630         char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
107631         sqlite3Dequote(zName);
107632         pList->a[i].zName = zName;
107633       }
107634     }
107635     substExprList(db, pParent->pEList, iParent, pSub->pEList);
107636     if( isAgg ){
107637       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
107638       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
107639     }
107640     if( pSub->pOrderBy ){
107641       /* At this point, any non-zero iOrderByCol values indicate that the
107642       ** ORDER BY column expression is identical to the iOrderByCol'th
107643       ** expression returned by SELECT statement pSub. Since these values
107644       ** do not necessarily correspond to columns in SELECT statement pParent,
107645       ** zero them before transfering the ORDER BY clause.
107646       **
107647       ** Not doing this may cause an error if a subsequent call to this
107648       ** function attempts to flatten a compound sub-query into pParent
107649       ** (the only way this can happen is if the compound sub-query is
107650       ** currently part of pSub->pSrc). See ticket [d11a6e908f].  */
107651       ExprList *pOrderBy = pSub->pOrderBy;
107652       for(i=0; i<pOrderBy->nExpr; i++){
107653         pOrderBy->a[i].u.x.iOrderByCol = 0;
107654       }
107655       assert( pParent->pOrderBy==0 );
107656       assert( pSub->pPrior==0 );
107657       pParent->pOrderBy = pOrderBy;
107658       pSub->pOrderBy = 0;
107659     }else if( pParent->pOrderBy ){
107660       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
107661     }
107662     if( pSub->pWhere ){
107663       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
107664     }else{
107665       pWhere = 0;
107666     }
107667     if( subqueryIsAgg ){
107668       assert( pParent->pHaving==0 );
107669       pParent->pHaving = pParent->pWhere;
107670       pParent->pWhere = pWhere;
107671       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
107672       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
107673                                   sqlite3ExprDup(db, pSub->pHaving, 0));
107674       assert( pParent->pGroupBy==0 );
107675       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
107676     }else{
107677       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
107678       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
107679     }
107680 
107681     /* The flattened query is distinct if either the inner or the
107682     ** outer query is distinct.
107683     */
107684     pParent->selFlags |= pSub->selFlags & SF_Distinct;
107685 
107686     /*
107687     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
107688     **
107689     ** One is tempted to try to add a and b to combine the limits.  But this
107690     ** does not work if either limit is negative.
107691     */
107692     if( pSub->pLimit ){
107693       pParent->pLimit = pSub->pLimit;
107694       pSub->pLimit = 0;
107695     }
107696   }
107697 
107698   /* Finially, delete what is left of the subquery and return
107699   ** success.
107700   */
107701   sqlite3SelectDelete(db, pSub1);
107702 
107703 #if SELECTTRACE_ENABLED
107704   if( sqlite3SelectTrace & 0x100 ){
107705     sqlite3DebugPrintf("After flattening:\n");
107706     sqlite3TreeViewSelect(0, p, 0);
107707   }
107708 #endif
107709 
107710   return 1;
107711 }
107712 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
107713 
107714 /*
107715 ** Based on the contents of the AggInfo structure indicated by the first
107716 ** argument, this function checks if the following are true:
107717 **
107718 **    * the query contains just a single aggregate function,
107719 **    * the aggregate function is either min() or max(), and
107720 **    * the argument to the aggregate function is a column value.
107721 **
107722 ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
107723 ** is returned as appropriate. Also, *ppMinMax is set to point to the
107724 ** list of arguments passed to the aggregate before returning.
107725 **
107726 ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
107727 ** WHERE_ORDERBY_NORMAL is returned.
107728 */
107729 static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
107730   int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
107731 
107732   *ppMinMax = 0;
107733   if( pAggInfo->nFunc==1 ){
107734     Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
107735     ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
107736 
107737     assert( pExpr->op==TK_AGG_FUNCTION );
107738     if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
107739       const char *zFunc = pExpr->u.zToken;
107740       if( sqlite3StrICmp(zFunc, "min")==0 ){
107741         eRet = WHERE_ORDERBY_MIN;
107742         *ppMinMax = pEList;
107743       }else if( sqlite3StrICmp(zFunc, "max")==0 ){
107744         eRet = WHERE_ORDERBY_MAX;
107745         *ppMinMax = pEList;
107746       }
107747     }
107748   }
107749 
107750   assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
107751   return eRet;
107752 }
107753 
107754 /*
107755 ** The select statement passed as the first argument is an aggregate query.
107756 ** The second argument is the associated aggregate-info object. This
107757 ** function tests if the SELECT is of the form:
107758 **
107759 **   SELECT count(*) FROM <tbl>
107760 **
107761 ** where table is a database table, not a sub-select or view. If the query
107762 ** does match this pattern, then a pointer to the Table object representing
107763 ** <tbl> is returned. Otherwise, 0 is returned.
107764 */
107765 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
107766   Table *pTab;
107767   Expr *pExpr;
107768 
107769   assert( !p->pGroupBy );
107770 
107771   if( p->pWhere || p->pEList->nExpr!=1
107772    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
107773   ){
107774     return 0;
107775   }
107776   pTab = p->pSrc->a[0].pTab;
107777   pExpr = p->pEList->a[0].pExpr;
107778   assert( pTab && !pTab->pSelect && pExpr );
107779 
107780   if( IsVirtual(pTab) ) return 0;
107781   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
107782   if( NEVER(pAggInfo->nFunc==0) ) return 0;
107783   if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
107784   if( pExpr->flags&EP_Distinct ) return 0;
107785 
107786   return pTab;
107787 }
107788 
107789 /*
107790 ** If the source-list item passed as an argument was augmented with an
107791 ** INDEXED BY clause, then try to locate the specified index. If there
107792 ** was such a clause and the named index cannot be found, return
107793 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
107794 ** pFrom->pIndex and return SQLITE_OK.
107795 */
107796 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
107797   if( pFrom->pTab && pFrom->zIndex ){
107798     Table *pTab = pFrom->pTab;
107799     char *zIndex = pFrom->zIndex;
107800     Index *pIdx;
107801     for(pIdx=pTab->pIndex;
107802         pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
107803         pIdx=pIdx->pNext
107804     );
107805     if( !pIdx ){
107806       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
107807       pParse->checkSchema = 1;
107808       return SQLITE_ERROR;
107809     }
107810     pFrom->pIndex = pIdx;
107811   }
107812   return SQLITE_OK;
107813 }
107814 /*
107815 ** Detect compound SELECT statements that use an ORDER BY clause with
107816 ** an alternative collating sequence.
107817 **
107818 **    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
107819 **
107820 ** These are rewritten as a subquery:
107821 **
107822 **    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
107823 **     ORDER BY ... COLLATE ...
107824 **
107825 ** This transformation is necessary because the multiSelectOrderBy() routine
107826 ** above that generates the code for a compound SELECT with an ORDER BY clause
107827 ** uses a merge algorithm that requires the same collating sequence on the
107828 ** result columns as on the ORDER BY clause.  See ticket
107829 ** http://www.sqlite.org/src/info/6709574d2a
107830 **
107831 ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
107832 ** The UNION ALL operator works fine with multiSelectOrderBy() even when
107833 ** there are COLLATE terms in the ORDER BY.
107834 */
107835 static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
107836   int i;
107837   Select *pNew;
107838   Select *pX;
107839   sqlite3 *db;
107840   struct ExprList_item *a;
107841   SrcList *pNewSrc;
107842   Parse *pParse;
107843   Token dummy;
107844 
107845   if( p->pPrior==0 ) return WRC_Continue;
107846   if( p->pOrderBy==0 ) return WRC_Continue;
107847   for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
107848   if( pX==0 ) return WRC_Continue;
107849   a = p->pOrderBy->a;
107850   for(i=p->pOrderBy->nExpr-1; i>=0; i--){
107851     if( a[i].pExpr->flags & EP_Collate ) break;
107852   }
107853   if( i<0 ) return WRC_Continue;
107854 
107855   /* If we reach this point, that means the transformation is required. */
107856 
107857   pParse = pWalker->pParse;
107858   db = pParse->db;
107859   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
107860   if( pNew==0 ) return WRC_Abort;
107861   memset(&dummy, 0, sizeof(dummy));
107862   pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
107863   if( pNewSrc==0 ) return WRC_Abort;
107864   *pNew = *p;
107865   p->pSrc = pNewSrc;
107866   p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
107867   p->op = TK_SELECT;
107868   p->pWhere = 0;
107869   pNew->pGroupBy = 0;
107870   pNew->pHaving = 0;
107871   pNew->pOrderBy = 0;
107872   p->pPrior = 0;
107873   p->pNext = 0;
107874   p->selFlags &= ~SF_Compound;
107875   assert( pNew->pPrior!=0 );
107876   pNew->pPrior->pNext = pNew;
107877   pNew->pLimit = 0;
107878   pNew->pOffset = 0;
107879   return WRC_Continue;
107880 }
107881 
107882 #ifndef SQLITE_OMIT_CTE
107883 /*
107884 ** Argument pWith (which may be NULL) points to a linked list of nested
107885 ** WITH contexts, from inner to outermost. If the table identified by
107886 ** FROM clause element pItem is really a common-table-expression (CTE)
107887 ** then return a pointer to the CTE definition for that table. Otherwise
107888 ** return NULL.
107889 **
107890 ** If a non-NULL value is returned, set *ppContext to point to the With
107891 ** object that the returned CTE belongs to.
107892 */
107893 static struct Cte *searchWith(
107894   With *pWith,                    /* Current outermost WITH clause */
107895   struct SrcList_item *pItem,     /* FROM clause element to resolve */
107896   With **ppContext                /* OUT: WITH clause return value belongs to */
107897 ){
107898   const char *zName;
107899   if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
107900     With *p;
107901     for(p=pWith; p; p=p->pOuter){
107902       int i;
107903       for(i=0; i<p->nCte; i++){
107904         if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
107905           *ppContext = p;
107906           return &p->a[i];
107907         }
107908       }
107909     }
107910   }
107911   return 0;
107912 }
107913 
107914 /* The code generator maintains a stack of active WITH clauses
107915 ** with the inner-most WITH clause being at the top of the stack.
107916 **
107917 ** This routine pushes the WITH clause passed as the second argument
107918 ** onto the top of the stack. If argument bFree is true, then this
107919 ** WITH clause will never be popped from the stack. In this case it
107920 ** should be freed along with the Parse object. In other cases, when
107921 ** bFree==0, the With object will be freed along with the SELECT
107922 ** statement with which it is associated.
107923 */
107924 SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
107925   assert( bFree==0 || pParse->pWith==0 );
107926   if( pWith ){
107927     pWith->pOuter = pParse->pWith;
107928     pParse->pWith = pWith;
107929     pParse->bFreeWith = bFree;
107930   }
107931 }
107932 
107933 /*
107934 ** This function checks if argument pFrom refers to a CTE declared by
107935 ** a WITH clause on the stack currently maintained by the parser. And,
107936 ** if currently processing a CTE expression, if it is a recursive
107937 ** reference to the current CTE.
107938 **
107939 ** If pFrom falls into either of the two categories above, pFrom->pTab
107940 ** and other fields are populated accordingly. The caller should check
107941 ** (pFrom->pTab!=0) to determine whether or not a successful match
107942 ** was found.
107943 **
107944 ** Whether or not a match is found, SQLITE_OK is returned if no error
107945 ** occurs. If an error does occur, an error message is stored in the
107946 ** parser and some error code other than SQLITE_OK returned.
107947 */
107948 static int withExpand(
107949   Walker *pWalker,
107950   struct SrcList_item *pFrom
107951 ){
107952   Parse *pParse = pWalker->pParse;
107953   sqlite3 *db = pParse->db;
107954   struct Cte *pCte;               /* Matched CTE (or NULL if no match) */
107955   With *pWith;                    /* WITH clause that pCte belongs to */
107956 
107957   assert( pFrom->pTab==0 );
107958 
107959   pCte = searchWith(pParse->pWith, pFrom, &pWith);
107960   if( pCte ){
107961     Table *pTab;
107962     ExprList *pEList;
107963     Select *pSel;
107964     Select *pLeft;                /* Left-most SELECT statement */
107965     int bMayRecursive;            /* True if compound joined by UNION [ALL] */
107966     With *pSavedWith;             /* Initial value of pParse->pWith */
107967 
107968     /* If pCte->zErr is non-NULL at this point, then this is an illegal
107969     ** recursive reference to CTE pCte. Leave an error in pParse and return
107970     ** early. If pCte->zErr is NULL, then this is not a recursive reference.
107971     ** In this case, proceed.  */
107972     if( pCte->zErr ){
107973       sqlite3ErrorMsg(pParse, pCte->zErr, pCte->zName);
107974       return SQLITE_ERROR;
107975     }
107976 
107977     assert( pFrom->pTab==0 );
107978     pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
107979     if( pTab==0 ) return WRC_Abort;
107980     pTab->nRef = 1;
107981     pTab->zName = sqlite3DbStrDup(db, pCte->zName);
107982     pTab->iPKey = -1;
107983     pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
107984     pTab->tabFlags |= TF_Ephemeral;
107985     pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
107986     if( db->mallocFailed ) return SQLITE_NOMEM;
107987     assert( pFrom->pSelect );
107988 
107989     /* Check if this is a recursive CTE. */
107990     pSel = pFrom->pSelect;
107991     bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
107992     if( bMayRecursive ){
107993       int i;
107994       SrcList *pSrc = pFrom->pSelect->pSrc;
107995       for(i=0; i<pSrc->nSrc; i++){
107996         struct SrcList_item *pItem = &pSrc->a[i];
107997         if( pItem->zDatabase==0
107998          && pItem->zName!=0
107999          && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
108000           ){
108001           pItem->pTab = pTab;
108002           pItem->isRecursive = 1;
108003           pTab->nRef++;
108004           pSel->selFlags |= SF_Recursive;
108005         }
108006       }
108007     }
108008 
108009     /* Only one recursive reference is permitted. */
108010     if( pTab->nRef>2 ){
108011       sqlite3ErrorMsg(
108012           pParse, "multiple references to recursive table: %s", pCte->zName
108013       );
108014       return SQLITE_ERROR;
108015     }
108016     assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
108017 
108018     pCte->zErr = "circular reference: %s";
108019     pSavedWith = pParse->pWith;
108020     pParse->pWith = pWith;
108021     sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
108022 
108023     for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
108024     pEList = pLeft->pEList;
108025     if( pCte->pCols ){
108026       if( pEList->nExpr!=pCte->pCols->nExpr ){
108027         sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
108028             pCte->zName, pEList->nExpr, pCte->pCols->nExpr
108029         );
108030         pParse->pWith = pSavedWith;
108031         return SQLITE_ERROR;
108032       }
108033       pEList = pCte->pCols;
108034     }
108035 
108036     selectColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
108037     if( bMayRecursive ){
108038       if( pSel->selFlags & SF_Recursive ){
108039         pCte->zErr = "multiple recursive references: %s";
108040       }else{
108041         pCte->zErr = "recursive reference in a subquery: %s";
108042       }
108043       sqlite3WalkSelect(pWalker, pSel);
108044     }
108045     pCte->zErr = 0;
108046     pParse->pWith = pSavedWith;
108047   }
108048 
108049   return SQLITE_OK;
108050 }
108051 #endif
108052 
108053 #ifndef SQLITE_OMIT_CTE
108054 /*
108055 ** If the SELECT passed as the second argument has an associated WITH
108056 ** clause, pop it from the stack stored as part of the Parse object.
108057 **
108058 ** This function is used as the xSelectCallback2() callback by
108059 ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
108060 ** names and other FROM clause elements.
108061 */
108062 static void selectPopWith(Walker *pWalker, Select *p){
108063   Parse *pParse = pWalker->pParse;
108064   With *pWith = findRightmost(p)->pWith;
108065   if( pWith!=0 ){
108066     assert( pParse->pWith==pWith );
108067     pParse->pWith = pWith->pOuter;
108068   }
108069 }
108070 #else
108071 #define selectPopWith 0
108072 #endif
108073 
108074 /*
108075 ** This routine is a Walker callback for "expanding" a SELECT statement.
108076 ** "Expanding" means to do the following:
108077 **
108078 **    (1)  Make sure VDBE cursor numbers have been assigned to every
108079 **         element of the FROM clause.
108080 **
108081 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
108082 **         defines FROM clause.  When views appear in the FROM clause,
108083 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
108084 **         that implements the view.  A copy is made of the view's SELECT
108085 **         statement so that we can freely modify or delete that statement
108086 **         without worrying about messing up the persistent representation
108087 **         of the view.
108088 **
108089 **    (3)  Add terms to the WHERE clause to accommodate the NATURAL keyword
108090 **         on joins and the ON and USING clause of joins.
108091 **
108092 **    (4)  Scan the list of columns in the result set (pEList) looking
108093 **         for instances of the "*" operator or the TABLE.* operator.
108094 **         If found, expand each "*" to be every column in every table
108095 **         and TABLE.* to be every column in TABLE.
108096 **
108097 */
108098 static int selectExpander(Walker *pWalker, Select *p){
108099   Parse *pParse = pWalker->pParse;
108100   int i, j, k;
108101   SrcList *pTabList;
108102   ExprList *pEList;
108103   struct SrcList_item *pFrom;
108104   sqlite3 *db = pParse->db;
108105   Expr *pE, *pRight, *pExpr;
108106   u16 selFlags = p->selFlags;
108107 
108108   p->selFlags |= SF_Expanded;
108109   if( db->mallocFailed  ){
108110     return WRC_Abort;
108111   }
108112   if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
108113     return WRC_Prune;
108114   }
108115   pTabList = p->pSrc;
108116   pEList = p->pEList;
108117   sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
108118 
108119   /* Make sure cursor numbers have been assigned to all entries in
108120   ** the FROM clause of the SELECT statement.
108121   */
108122   sqlite3SrcListAssignCursors(pParse, pTabList);
108123 
108124   /* Look up every table named in the FROM clause of the select.  If
108125   ** an entry of the FROM clause is a subquery instead of a table or view,
108126   ** then create a transient table structure to describe the subquery.
108127   */
108128   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
108129     Table *pTab;
108130     assert( pFrom->isRecursive==0 || pFrom->pTab );
108131     if( pFrom->isRecursive ) continue;
108132     if( pFrom->pTab!=0 ){
108133       /* This statement has already been prepared.  There is no need
108134       ** to go further. */
108135       assert( i==0 );
108136 #ifndef SQLITE_OMIT_CTE
108137       selectPopWith(pWalker, p);
108138 #endif
108139       return WRC_Prune;
108140     }
108141 #ifndef SQLITE_OMIT_CTE
108142     if( withExpand(pWalker, pFrom) ) return WRC_Abort;
108143     if( pFrom->pTab ) {} else
108144 #endif
108145     if( pFrom->zName==0 ){
108146 #ifndef SQLITE_OMIT_SUBQUERY
108147       Select *pSel = pFrom->pSelect;
108148       /* A sub-query in the FROM clause of a SELECT */
108149       assert( pSel!=0 );
108150       assert( pFrom->pTab==0 );
108151       sqlite3WalkSelect(pWalker, pSel);
108152       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
108153       if( pTab==0 ) return WRC_Abort;
108154       pTab->nRef = 1;
108155       pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
108156       while( pSel->pPrior ){ pSel = pSel->pPrior; }
108157       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
108158       pTab->iPKey = -1;
108159       pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
108160       pTab->tabFlags |= TF_Ephemeral;
108161 #endif
108162     }else{
108163       /* An ordinary table or view name in the FROM clause */
108164       assert( pFrom->pTab==0 );
108165       pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
108166       if( pTab==0 ) return WRC_Abort;
108167       if( pTab->nRef==0xffff ){
108168         sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
108169            pTab->zName);
108170         pFrom->pTab = 0;
108171         return WRC_Abort;
108172       }
108173       pTab->nRef++;
108174 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
108175       if( pTab->pSelect || IsVirtual(pTab) ){
108176         /* We reach here if the named table is a really a view */
108177         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
108178         assert( pFrom->pSelect==0 );
108179         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
108180         sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
108181         sqlite3WalkSelect(pWalker, pFrom->pSelect);
108182       }
108183 #endif
108184     }
108185 
108186     /* Locate the index named by the INDEXED BY clause, if any. */
108187     if( sqlite3IndexedByLookup(pParse, pFrom) ){
108188       return WRC_Abort;
108189     }
108190   }
108191 
108192   /* Process NATURAL keywords, and ON and USING clauses of joins.
108193   */
108194   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
108195     return WRC_Abort;
108196   }
108197 
108198   /* For every "*" that occurs in the column list, insert the names of
108199   ** all columns in all tables.  And for every TABLE.* insert the names
108200   ** of all columns in TABLE.  The parser inserted a special expression
108201   ** with the TK_ALL operator for each "*" that it found in the column list.
108202   ** The following code just has to locate the TK_ALL expressions and expand
108203   ** each one to the list of all columns in all tables.
108204   **
108205   ** The first loop just checks to see if there are any "*" operators
108206   ** that need expanding.
108207   */
108208   for(k=0; k<pEList->nExpr; k++){
108209     pE = pEList->a[k].pExpr;
108210     if( pE->op==TK_ALL ) break;
108211     assert( pE->op!=TK_DOT || pE->pRight!=0 );
108212     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
108213     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
108214   }
108215   if( k<pEList->nExpr ){
108216     /*
108217     ** If we get here it means the result set contains one or more "*"
108218     ** operators that need to be expanded.  Loop through each expression
108219     ** in the result set and expand them one by one.
108220     */
108221     struct ExprList_item *a = pEList->a;
108222     ExprList *pNew = 0;
108223     int flags = pParse->db->flags;
108224     int longNames = (flags & SQLITE_FullColNames)!=0
108225                       && (flags & SQLITE_ShortColNames)==0;
108226 
108227     /* When processing FROM-clause subqueries, it is always the case
108228     ** that full_column_names=OFF and short_column_names=ON.  The
108229     ** sqlite3ResultSetOfSelect() routine makes it so. */
108230     assert( (p->selFlags & SF_NestedFrom)==0
108231           || ((flags & SQLITE_FullColNames)==0 &&
108232               (flags & SQLITE_ShortColNames)!=0) );
108233 
108234     for(k=0; k<pEList->nExpr; k++){
108235       pE = a[k].pExpr;
108236       pRight = pE->pRight;
108237       assert( pE->op!=TK_DOT || pRight!=0 );
108238       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
108239         /* This particular expression does not need to be expanded.
108240         */
108241         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
108242         if( pNew ){
108243           pNew->a[pNew->nExpr-1].zName = a[k].zName;
108244           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
108245           a[k].zName = 0;
108246           a[k].zSpan = 0;
108247         }
108248         a[k].pExpr = 0;
108249       }else{
108250         /* This expression is a "*" or a "TABLE.*" and needs to be
108251         ** expanded. */
108252         int tableSeen = 0;      /* Set to 1 when TABLE matches */
108253         char *zTName = 0;       /* text of name of TABLE */
108254         if( pE->op==TK_DOT ){
108255           assert( pE->pLeft!=0 );
108256           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
108257           zTName = pE->pLeft->u.zToken;
108258         }
108259         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
108260           Table *pTab = pFrom->pTab;
108261           Select *pSub = pFrom->pSelect;
108262           char *zTabName = pFrom->zAlias;
108263           const char *zSchemaName = 0;
108264           int iDb;
108265           if( zTabName==0 ){
108266             zTabName = pTab->zName;
108267           }
108268           if( db->mallocFailed ) break;
108269           if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
108270             pSub = 0;
108271             if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
108272               continue;
108273             }
108274             iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
108275             zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
108276           }
108277           for(j=0; j<pTab->nCol; j++){
108278             char *zName = pTab->aCol[j].zName;
108279             char *zColname;  /* The computed column name */
108280             char *zToFree;   /* Malloced string that needs to be freed */
108281             Token sColname;  /* Computed column name as a token */
108282 
108283             assert( zName );
108284             if( zTName && pSub
108285              && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
108286             ){
108287               continue;
108288             }
108289 
108290             /* If a column is marked as 'hidden' (currently only possible
108291             ** for virtual tables), do not include it in the expanded
108292             ** result-set list.
108293             */
108294             if( IsHiddenColumn(&pTab->aCol[j]) ){
108295               assert(IsVirtual(pTab));
108296               continue;
108297             }
108298             tableSeen = 1;
108299 
108300             if( i>0 && zTName==0 ){
108301               if( (pFrom->jointype & JT_NATURAL)!=0
108302                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
108303               ){
108304                 /* In a NATURAL join, omit the join columns from the
108305                 ** table to the right of the join */
108306                 continue;
108307               }
108308               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
108309                 /* In a join with a USING clause, omit columns in the
108310                 ** using clause from the table on the right. */
108311                 continue;
108312               }
108313             }
108314             pRight = sqlite3Expr(db, TK_ID, zName);
108315             zColname = zName;
108316             zToFree = 0;
108317             if( longNames || pTabList->nSrc>1 ){
108318               Expr *pLeft;
108319               pLeft = sqlite3Expr(db, TK_ID, zTabName);
108320               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
108321               if( zSchemaName ){
108322                 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
108323                 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
108324               }
108325               if( longNames ){
108326                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
108327                 zToFree = zColname;
108328               }
108329             }else{
108330               pExpr = pRight;
108331             }
108332             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
108333             sColname.z = zColname;
108334             sColname.n = sqlite3Strlen30(zColname);
108335             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
108336             if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
108337               struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
108338               if( pSub ){
108339                 pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
108340                 testcase( pX->zSpan==0 );
108341               }else{
108342                 pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
108343                                            zSchemaName, zTabName, zColname);
108344                 testcase( pX->zSpan==0 );
108345               }
108346               pX->bSpanIsTab = 1;
108347             }
108348             sqlite3DbFree(db, zToFree);
108349           }
108350         }
108351         if( !tableSeen ){
108352           if( zTName ){
108353             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
108354           }else{
108355             sqlite3ErrorMsg(pParse, "no tables specified");
108356           }
108357         }
108358       }
108359     }
108360     sqlite3ExprListDelete(db, pEList);
108361     p->pEList = pNew;
108362   }
108363 #if SQLITE_MAX_COLUMN
108364   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
108365     sqlite3ErrorMsg(pParse, "too many columns in result set");
108366   }
108367 #endif
108368   return WRC_Continue;
108369 }
108370 
108371 /*
108372 ** No-op routine for the parse-tree walker.
108373 **
108374 ** When this routine is the Walker.xExprCallback then expression trees
108375 ** are walked without any actions being taken at each node.  Presumably,
108376 ** when this routine is used for Walker.xExprCallback then
108377 ** Walker.xSelectCallback is set to do something useful for every
108378 ** subquery in the parser tree.
108379 */
108380 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
108381   UNUSED_PARAMETER2(NotUsed, NotUsed2);
108382   return WRC_Continue;
108383 }
108384 
108385 /*
108386 ** This routine "expands" a SELECT statement and all of its subqueries.
108387 ** For additional information on what it means to "expand" a SELECT
108388 ** statement, see the comment on the selectExpand worker callback above.
108389 **
108390 ** Expanding a SELECT statement is the first step in processing a
108391 ** SELECT statement.  The SELECT statement must be expanded before
108392 ** name resolution is performed.
108393 **
108394 ** If anything goes wrong, an error message is written into pParse.
108395 ** The calling function can detect the problem by looking at pParse->nErr
108396 ** and/or pParse->db->mallocFailed.
108397 */
108398 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
108399   Walker w;
108400   memset(&w, 0, sizeof(w));
108401   w.xExprCallback = exprWalkNoop;
108402   w.pParse = pParse;
108403   if( pParse->hasCompound ){
108404     w.xSelectCallback = convertCompoundSelectToSubquery;
108405     sqlite3WalkSelect(&w, pSelect);
108406   }
108407   w.xSelectCallback = selectExpander;
108408   w.xSelectCallback2 = selectPopWith;
108409   sqlite3WalkSelect(&w, pSelect);
108410 }
108411 
108412 
108413 #ifndef SQLITE_OMIT_SUBQUERY
108414 /*
108415 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
108416 ** interface.
108417 **
108418 ** For each FROM-clause subquery, add Column.zType and Column.zColl
108419 ** information to the Table structure that represents the result set
108420 ** of that subquery.
108421 **
108422 ** The Table structure that represents the result set was constructed
108423 ** by selectExpander() but the type and collation information was omitted
108424 ** at that point because identifiers had not yet been resolved.  This
108425 ** routine is called after identifier resolution.
108426 */
108427 static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
108428   Parse *pParse;
108429   int i;
108430   SrcList *pTabList;
108431   struct SrcList_item *pFrom;
108432 
108433   assert( p->selFlags & SF_Resolved );
108434   if( (p->selFlags & SF_HasTypeInfo)==0 ){
108435     p->selFlags |= SF_HasTypeInfo;
108436     pParse = pWalker->pParse;
108437     pTabList = p->pSrc;
108438     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
108439       Table *pTab = pFrom->pTab;
108440       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
108441         /* A sub-query in the FROM clause of a SELECT */
108442         Select *pSel = pFrom->pSelect;
108443         if( pSel ){
108444           while( pSel->pPrior ) pSel = pSel->pPrior;
108445           selectAddColumnTypeAndCollation(pParse, pTab, pSel);
108446         }
108447       }
108448     }
108449   }
108450 }
108451 #endif
108452 
108453 
108454 /*
108455 ** This routine adds datatype and collating sequence information to
108456 ** the Table structures of all FROM-clause subqueries in a
108457 ** SELECT statement.
108458 **
108459 ** Use this routine after name resolution.
108460 */
108461 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
108462 #ifndef SQLITE_OMIT_SUBQUERY
108463   Walker w;
108464   memset(&w, 0, sizeof(w));
108465   w.xSelectCallback2 = selectAddSubqueryTypeInfo;
108466   w.xExprCallback = exprWalkNoop;
108467   w.pParse = pParse;
108468   sqlite3WalkSelect(&w, pSelect);
108469 #endif
108470 }
108471 
108472 
108473 /*
108474 ** This routine sets up a SELECT statement for processing.  The
108475 ** following is accomplished:
108476 **
108477 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
108478 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
108479 **     *  ON and USING clauses are shifted into WHERE statements
108480 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
108481 **     *  Identifiers in expression are matched to tables.
108482 **
108483 ** This routine acts recursively on all subqueries within the SELECT.
108484 */
108485 SQLITE_PRIVATE void sqlite3SelectPrep(
108486   Parse *pParse,         /* The parser context */
108487   Select *p,             /* The SELECT statement being coded. */
108488   NameContext *pOuterNC  /* Name context for container */
108489 ){
108490   sqlite3 *db;
108491   if( NEVER(p==0) ) return;
108492   db = pParse->db;
108493   if( db->mallocFailed ) return;
108494   if( p->selFlags & SF_HasTypeInfo ) return;
108495   sqlite3SelectExpand(pParse, p);
108496   if( pParse->nErr || db->mallocFailed ) return;
108497   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
108498   if( pParse->nErr || db->mallocFailed ) return;
108499   sqlite3SelectAddTypeInfo(pParse, p);
108500 }
108501 
108502 /*
108503 ** Reset the aggregate accumulator.
108504 **
108505 ** The aggregate accumulator is a set of memory cells that hold
108506 ** intermediate results while calculating an aggregate.  This
108507 ** routine generates code that stores NULLs in all of those memory
108508 ** cells.
108509 */
108510 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
108511   Vdbe *v = pParse->pVdbe;
108512   int i;
108513   struct AggInfo_func *pFunc;
108514   int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
108515   if( nReg==0 ) return;
108516 #ifdef SQLITE_DEBUG
108517   /* Verify that all AggInfo registers are within the range specified by
108518   ** AggInfo.mnReg..AggInfo.mxReg */
108519   assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
108520   for(i=0; i<pAggInfo->nColumn; i++){
108521     assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
108522          && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
108523   }
108524   for(i=0; i<pAggInfo->nFunc; i++){
108525     assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
108526          && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
108527   }
108528 #endif
108529   sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
108530   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
108531     if( pFunc->iDistinct>=0 ){
108532       Expr *pE = pFunc->pExpr;
108533       assert( !ExprHasProperty(pE, EP_xIsSelect) );
108534       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
108535         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
108536            "argument");
108537         pFunc->iDistinct = -1;
108538       }else{
108539         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
108540         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
108541                           (char*)pKeyInfo, P4_KEYINFO);
108542       }
108543     }
108544   }
108545 }
108546 
108547 /*
108548 ** Invoke the OP_AggFinalize opcode for every aggregate function
108549 ** in the AggInfo structure.
108550 */
108551 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
108552   Vdbe *v = pParse->pVdbe;
108553   int i;
108554   struct AggInfo_func *pF;
108555   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
108556     ExprList *pList = pF->pExpr->x.pList;
108557     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
108558     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
108559                       (void*)pF->pFunc, P4_FUNCDEF);
108560   }
108561 }
108562 
108563 /*
108564 ** Update the accumulator memory cells for an aggregate based on
108565 ** the current cursor position.
108566 */
108567 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
108568   Vdbe *v = pParse->pVdbe;
108569   int i;
108570   int regHit = 0;
108571   int addrHitTest = 0;
108572   struct AggInfo_func *pF;
108573   struct AggInfo_col *pC;
108574 
108575   pAggInfo->directMode = 1;
108576   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
108577     int nArg;
108578     int addrNext = 0;
108579     int regAgg;
108580     ExprList *pList = pF->pExpr->x.pList;
108581     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
108582     if( pList ){
108583       nArg = pList->nExpr;
108584       regAgg = sqlite3GetTempRange(pParse, nArg);
108585       sqlite3ExprCodeExprList(pParse, pList, regAgg, SQLITE_ECEL_DUP);
108586     }else{
108587       nArg = 0;
108588       regAgg = 0;
108589     }
108590     if( pF->iDistinct>=0 ){
108591       addrNext = sqlite3VdbeMakeLabel(v);
108592       assert( nArg==1 );
108593       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
108594     }
108595     if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
108596       CollSeq *pColl = 0;
108597       struct ExprList_item *pItem;
108598       int j;
108599       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
108600       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
108601         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
108602       }
108603       if( !pColl ){
108604         pColl = pParse->db->pDfltColl;
108605       }
108606       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
108607       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
108608     }
108609     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
108610                       (void*)pF->pFunc, P4_FUNCDEF);
108611     sqlite3VdbeChangeP5(v, (u8)nArg);
108612     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
108613     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
108614     if( addrNext ){
108615       sqlite3VdbeResolveLabel(v, addrNext);
108616       sqlite3ExprCacheClear(pParse);
108617     }
108618   }
108619 
108620   /* Before populating the accumulator registers, clear the column cache.
108621   ** Otherwise, if any of the required column values are already present
108622   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
108623   ** to pC->iMem. But by the time the value is used, the original register
108624   ** may have been used, invalidating the underlying buffer holding the
108625   ** text or blob value. See ticket [883034dcb5].
108626   **
108627   ** Another solution would be to change the OP_SCopy used to copy cached
108628   ** values to an OP_Copy.
108629   */
108630   if( regHit ){
108631     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
108632   }
108633   sqlite3ExprCacheClear(pParse);
108634   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
108635     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
108636   }
108637   pAggInfo->directMode = 0;
108638   sqlite3ExprCacheClear(pParse);
108639   if( addrHitTest ){
108640     sqlite3VdbeJumpHere(v, addrHitTest);
108641   }
108642 }
108643 
108644 /*
108645 ** Add a single OP_Explain instruction to the VDBE to explain a simple
108646 ** count(*) query ("SELECT count(*) FROM pTab").
108647 */
108648 #ifndef SQLITE_OMIT_EXPLAIN
108649 static void explainSimpleCount(
108650   Parse *pParse,                  /* Parse context */
108651   Table *pTab,                    /* Table being queried */
108652   Index *pIdx                     /* Index used to optimize scan, or NULL */
108653 ){
108654   if( pParse->explain==2 ){
108655     int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
108656     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
108657         pTab->zName,
108658         bCover ? " USING COVERING INDEX " : "",
108659         bCover ? pIdx->zName : ""
108660     );
108661     sqlite3VdbeAddOp4(
108662         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
108663     );
108664   }
108665 }
108666 #else
108667 # define explainSimpleCount(a,b,c)
108668 #endif
108669 
108670 /*
108671 ** Generate code for the SELECT statement given in the p argument.
108672 **
108673 ** The results are returned according to the SelectDest structure.
108674 ** See comments in sqliteInt.h for further information.
108675 **
108676 ** This routine returns the number of errors.  If any errors are
108677 ** encountered, then an appropriate error message is left in
108678 ** pParse->zErrMsg.
108679 **
108680 ** This routine does NOT free the Select structure passed in.  The
108681 ** calling function needs to do that.
108682 */
108683 SQLITE_PRIVATE int sqlite3Select(
108684   Parse *pParse,         /* The parser context */
108685   Select *p,             /* The SELECT statement being coded. */
108686   SelectDest *pDest      /* What to do with the query results */
108687 ){
108688   int i, j;              /* Loop counters */
108689   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
108690   Vdbe *v;               /* The virtual machine under construction */
108691   int isAgg;             /* True for select lists like "count(*)" */
108692   ExprList *pEList;      /* List of columns to extract. */
108693   SrcList *pTabList;     /* List of tables to select from */
108694   Expr *pWhere;          /* The WHERE clause.  May be NULL */
108695   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
108696   Expr *pHaving;         /* The HAVING clause.  May be NULL */
108697   int rc = 1;            /* Value to return from this function */
108698   DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
108699   SortCtx sSort;         /* Info on how to code the ORDER BY clause */
108700   AggInfo sAggInfo;      /* Information used by aggregate queries */
108701   int iEnd;              /* Address of the end of the query */
108702   sqlite3 *db;           /* The database connection */
108703 
108704 #ifndef SQLITE_OMIT_EXPLAIN
108705   int iRestoreSelectId = pParse->iSelectId;
108706   pParse->iSelectId = pParse->iNextSelectId++;
108707 #endif
108708 
108709   db = pParse->db;
108710   if( p==0 || db->mallocFailed || pParse->nErr ){
108711     return 1;
108712   }
108713   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
108714   memset(&sAggInfo, 0, sizeof(sAggInfo));
108715 #if SELECTTRACE_ENABLED
108716   pParse->nSelectIndent++;
108717   SELECTTRACE(1,pParse,p, ("begin processing:\n"));
108718   if( sqlite3SelectTrace & 0x100 ){
108719     sqlite3TreeViewSelect(0, p, 0);
108720   }
108721 #endif
108722 
108723   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
108724   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
108725   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
108726   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
108727   if( IgnorableOrderby(pDest) ){
108728     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
108729            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
108730            pDest->eDest==SRT_Queue  || pDest->eDest==SRT_DistFifo ||
108731            pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
108732     /* If ORDER BY makes no difference in the output then neither does
108733     ** DISTINCT so it can be removed too. */
108734     sqlite3ExprListDelete(db, p->pOrderBy);
108735     p->pOrderBy = 0;
108736     p->selFlags &= ~SF_Distinct;
108737   }
108738   sqlite3SelectPrep(pParse, p, 0);
108739   memset(&sSort, 0, sizeof(sSort));
108740   sSort.pOrderBy = p->pOrderBy;
108741   pTabList = p->pSrc;
108742   pEList = p->pEList;
108743   if( pParse->nErr || db->mallocFailed ){
108744     goto select_end;
108745   }
108746   isAgg = (p->selFlags & SF_Aggregate)!=0;
108747   assert( pEList!=0 );
108748 
108749   /* Begin generating code.
108750   */
108751   v = sqlite3GetVdbe(pParse);
108752   if( v==0 ) goto select_end;
108753 
108754   /* If writing to memory or generating a set
108755   ** only a single column may be output.
108756   */
108757 #ifndef SQLITE_OMIT_SUBQUERY
108758   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
108759     goto select_end;
108760   }
108761 #endif
108762 
108763   /* Generate code for all sub-queries in the FROM clause
108764   */
108765 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
108766   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
108767     struct SrcList_item *pItem = &pTabList->a[i];
108768     SelectDest dest;
108769     Select *pSub = pItem->pSelect;
108770     int isAggSub;
108771 
108772     if( pSub==0 ) continue;
108773 
108774     /* Sometimes the code for a subquery will be generated more than
108775     ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
108776     ** for example.  In that case, do not regenerate the code to manifest
108777     ** a view or the co-routine to implement a view.  The first instance
108778     ** is sufficient, though the subroutine to manifest the view does need
108779     ** to be invoked again. */
108780     if( pItem->addrFillSub ){
108781       if( pItem->viaCoroutine==0 ){
108782         sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
108783       }
108784       continue;
108785     }
108786 
108787     /* Increment Parse.nHeight by the height of the largest expression
108788     ** tree referred to by this, the parent select. The child select
108789     ** may contain expression trees of at most
108790     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
108791     ** more conservative than necessary, but much easier than enforcing
108792     ** an exact limit.
108793     */
108794     pParse->nHeight += sqlite3SelectExprHeight(p);
108795 
108796     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
108797     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
108798       /* This subquery can be absorbed into its parent. */
108799       if( isAggSub ){
108800         isAgg = 1;
108801         p->selFlags |= SF_Aggregate;
108802       }
108803       i = -1;
108804     }else if( pTabList->nSrc==1
108805            && OptimizationEnabled(db, SQLITE_SubqCoroutine)
108806     ){
108807       /* Implement a co-routine that will return a single row of the result
108808       ** set on each invocation.
108809       */
108810       int addrTop = sqlite3VdbeCurrentAddr(v)+1;
108811       pItem->regReturn = ++pParse->nMem;
108812       sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
108813       VdbeComment((v, "%s", pItem->pTab->zName));
108814       pItem->addrFillSub = addrTop;
108815       sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
108816       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
108817       sqlite3Select(pParse, pSub, &dest);
108818       pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
108819       pItem->viaCoroutine = 1;
108820       pItem->regResult = dest.iSdst;
108821       sqlite3VdbeAddOp1(v, OP_EndCoroutine, pItem->regReturn);
108822       sqlite3VdbeJumpHere(v, addrTop-1);
108823       sqlite3ClearTempRegCache(pParse);
108824     }else{
108825       /* Generate a subroutine that will fill an ephemeral table with
108826       ** the content of this subquery.  pItem->addrFillSub will point
108827       ** to the address of the generated subroutine.  pItem->regReturn
108828       ** is a register allocated to hold the subroutine return address
108829       */
108830       int topAddr;
108831       int onceAddr = 0;
108832       int retAddr;
108833       assert( pItem->addrFillSub==0 );
108834       pItem->regReturn = ++pParse->nMem;
108835       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
108836       pItem->addrFillSub = topAddr+1;
108837       if( pItem->isCorrelated==0 ){
108838         /* If the subquery is not correlated and if we are not inside of
108839         ** a trigger, then we only need to compute the value of the subquery
108840         ** once. */
108841         onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
108842         VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
108843       }else{
108844         VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
108845       }
108846       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
108847       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
108848       sqlite3Select(pParse, pSub, &dest);
108849       pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
108850       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
108851       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
108852       VdbeComment((v, "end %s", pItem->pTab->zName));
108853       sqlite3VdbeChangeP1(v, topAddr, retAddr);
108854       sqlite3ClearTempRegCache(pParse);
108855     }
108856     if( /*pParse->nErr ||*/ db->mallocFailed ){
108857       goto select_end;
108858     }
108859     pParse->nHeight -= sqlite3SelectExprHeight(p);
108860     pTabList = p->pSrc;
108861     if( !IgnorableOrderby(pDest) ){
108862       sSort.pOrderBy = p->pOrderBy;
108863     }
108864   }
108865   pEList = p->pEList;
108866 #endif
108867   pWhere = p->pWhere;
108868   pGroupBy = p->pGroupBy;
108869   pHaving = p->pHaving;
108870   sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
108871 
108872 #ifndef SQLITE_OMIT_COMPOUND_SELECT
108873   /* If there is are a sequence of queries, do the earlier ones first.
108874   */
108875   if( p->pPrior ){
108876     rc = multiSelect(pParse, p, pDest);
108877     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
108878 #if SELECTTRACE_ENABLED
108879     SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
108880     pParse->nSelectIndent--;
108881 #endif
108882     return rc;
108883   }
108884 #endif
108885 
108886   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
108887   ** if the select-list is the same as the ORDER BY list, then this query
108888   ** can be rewritten as a GROUP BY. In other words, this:
108889   **
108890   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
108891   **
108892   ** is transformed to:
108893   **
108894   **     SELECT xyz FROM ... GROUP BY xyz
108895   **
108896   ** The second form is preferred as a single index (or temp-table) may be
108897   ** used for both the ORDER BY and DISTINCT processing. As originally
108898   ** written the query must use a temp-table for at least one of the ORDER
108899   ** BY and DISTINCT, and an index or separate temp-table for the other.
108900   */
108901   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
108902    && sqlite3ExprListCompare(sSort.pOrderBy, p->pEList, -1)==0
108903   ){
108904     p->selFlags &= ~SF_Distinct;
108905     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
108906     pGroupBy = p->pGroupBy;
108907     sSort.pOrderBy = 0;
108908     /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
108909     ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
108910     ** original setting of the SF_Distinct flag, not the current setting */
108911     assert( sDistinct.isTnct );
108912   }
108913 
108914   /* If there is an ORDER BY clause, then this sorting
108915   ** index might end up being unused if the data can be
108916   ** extracted in pre-sorted order.  If that is the case, then the
108917   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
108918   ** we figure out that the sorting index is not needed.  The addrSortIndex
108919   ** variable is used to facilitate that change.
108920   */
108921   if( sSort.pOrderBy ){
108922     KeyInfo *pKeyInfo;
108923     pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, 0);
108924     sSort.iECursor = pParse->nTab++;
108925     sSort.addrSortIndex =
108926       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
108927           sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
108928           (char*)pKeyInfo, P4_KEYINFO
108929       );
108930   }else{
108931     sSort.addrSortIndex = -1;
108932   }
108933 
108934   /* If the output is destined for a temporary table, open that table.
108935   */
108936   if( pDest->eDest==SRT_EphemTab ){
108937     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
108938   }
108939 
108940   /* Set the limiter.
108941   */
108942   iEnd = sqlite3VdbeMakeLabel(v);
108943   p->nSelectRow = LARGEST_INT64;
108944   computeLimitRegisters(pParse, p, iEnd);
108945   if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
108946     sqlite3VdbeGetOp(v, sSort.addrSortIndex)->opcode = OP_SorterOpen;
108947     sSort.sortFlags |= SORTFLAG_UseSorter;
108948   }
108949 
108950   /* Open a virtual index to use for the distinct set.
108951   */
108952   if( p->selFlags & SF_Distinct ){
108953     sDistinct.tabTnct = pParse->nTab++;
108954     sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
108955                                 sDistinct.tabTnct, 0, 0,
108956                                 (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
108957                                 P4_KEYINFO);
108958     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
108959     sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
108960   }else{
108961     sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
108962   }
108963 
108964   if( !isAgg && pGroupBy==0 ){
108965     /* No aggregate functions and no GROUP BY clause */
108966     u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
108967 
108968     /* Begin the database scan. */
108969     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
108970                                p->pEList, wctrlFlags, 0);
108971     if( pWInfo==0 ) goto select_end;
108972     if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
108973       p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
108974     }
108975     if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
108976       sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
108977     }
108978     if( sSort.pOrderBy ){
108979       sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
108980       if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
108981         sSort.pOrderBy = 0;
108982       }
108983     }
108984 
108985     /* If sorting index that was created by a prior OP_OpenEphemeral
108986     ** instruction ended up not being needed, then change the OP_OpenEphemeral
108987     ** into an OP_Noop.
108988     */
108989     if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
108990       sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
108991     }
108992 
108993     /* Use the standard inner loop. */
108994     selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
108995                     sqlite3WhereContinueLabel(pWInfo),
108996                     sqlite3WhereBreakLabel(pWInfo));
108997 
108998     /* End the database scan loop.
108999     */
109000     sqlite3WhereEnd(pWInfo);
109001   }else{
109002     /* This case when there exist aggregate functions or a GROUP BY clause
109003     ** or both */
109004     NameContext sNC;    /* Name context for processing aggregate information */
109005     int iAMem;          /* First Mem address for storing current GROUP BY */
109006     int iBMem;          /* First Mem address for previous GROUP BY */
109007     int iUseFlag;       /* Mem address holding flag indicating that at least
109008                         ** one row of the input to the aggregator has been
109009                         ** processed */
109010     int iAbortFlag;     /* Mem address which causes query abort if positive */
109011     int groupBySort;    /* Rows come from source in GROUP BY order */
109012     int addrEnd;        /* End of processing for this SELECT */
109013     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
109014     int sortOut = 0;    /* Output register from the sorter */
109015     int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
109016 
109017     /* Remove any and all aliases between the result set and the
109018     ** GROUP BY clause.
109019     */
109020     if( pGroupBy ){
109021       int k;                        /* Loop counter */
109022       struct ExprList_item *pItem;  /* For looping over expression in a list */
109023 
109024       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
109025         pItem->u.x.iAlias = 0;
109026       }
109027       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
109028         pItem->u.x.iAlias = 0;
109029       }
109030       if( p->nSelectRow>100 ) p->nSelectRow = 100;
109031     }else{
109032       p->nSelectRow = 1;
109033     }
109034 
109035 
109036     /* If there is both a GROUP BY and an ORDER BY clause and they are
109037     ** identical, then it may be possible to disable the ORDER BY clause
109038     ** on the grounds that the GROUP BY will cause elements to come out
109039     ** in the correct order. It also may not - the GROUP BY may use a
109040     ** database index that causes rows to be grouped together as required
109041     ** but not actually sorted. Either way, record the fact that the
109042     ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
109043     ** variable.  */
109044     if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
109045       orderByGrp = 1;
109046     }
109047 
109048     /* Create a label to jump to when we want to abort the query */
109049     addrEnd = sqlite3VdbeMakeLabel(v);
109050 
109051     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
109052     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
109053     ** SELECT statement.
109054     */
109055     memset(&sNC, 0, sizeof(sNC));
109056     sNC.pParse = pParse;
109057     sNC.pSrcList = pTabList;
109058     sNC.pAggInfo = &sAggInfo;
109059     sAggInfo.mnReg = pParse->nMem+1;
109060     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
109061     sAggInfo.pGroupBy = pGroupBy;
109062     sqlite3ExprAnalyzeAggList(&sNC, pEList);
109063     sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
109064     if( pHaving ){
109065       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
109066     }
109067     sAggInfo.nAccumulator = sAggInfo.nColumn;
109068     for(i=0; i<sAggInfo.nFunc; i++){
109069       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
109070       sNC.ncFlags |= NC_InAggFunc;
109071       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
109072       sNC.ncFlags &= ~NC_InAggFunc;
109073     }
109074     sAggInfo.mxReg = pParse->nMem;
109075     if( db->mallocFailed ) goto select_end;
109076 
109077     /* Processing for aggregates with GROUP BY is very different and
109078     ** much more complex than aggregates without a GROUP BY.
109079     */
109080     if( pGroupBy ){
109081       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
109082       int j1;             /* A-vs-B comparision jump */
109083       int addrOutputRow;  /* Start of subroutine that outputs a result row */
109084       int regOutputRow;   /* Return address register for output subroutine */
109085       int addrSetAbort;   /* Set the abort flag and return */
109086       int addrTopOfLoop;  /* Top of the input loop */
109087       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
109088       int addrReset;      /* Subroutine for resetting the accumulator */
109089       int regReset;       /* Return address register for reset subroutine */
109090 
109091       /* If there is a GROUP BY clause we might need a sorting index to
109092       ** implement it.  Allocate that sorting index now.  If it turns out
109093       ** that we do not need it after all, the OP_SorterOpen instruction
109094       ** will be converted into a Noop.
109095       */
109096       sAggInfo.sortingIdx = pParse->nTab++;
109097       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, 0);
109098       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
109099           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
109100           0, (char*)pKeyInfo, P4_KEYINFO);
109101 
109102       /* Initialize memory locations used by GROUP BY aggregate processing
109103       */
109104       iUseFlag = ++pParse->nMem;
109105       iAbortFlag = ++pParse->nMem;
109106       regOutputRow = ++pParse->nMem;
109107       addrOutputRow = sqlite3VdbeMakeLabel(v);
109108       regReset = ++pParse->nMem;
109109       addrReset = sqlite3VdbeMakeLabel(v);
109110       iAMem = pParse->nMem + 1;
109111       pParse->nMem += pGroupBy->nExpr;
109112       iBMem = pParse->nMem + 1;
109113       pParse->nMem += pGroupBy->nExpr;
109114       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
109115       VdbeComment((v, "clear abort flag"));
109116       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
109117       VdbeComment((v, "indicate accumulator empty"));
109118       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
109119 
109120       /* Begin a loop that will extract all source rows in GROUP BY order.
109121       ** This might involve two separate loops with an OP_Sort in between, or
109122       ** it might be a single loop that uses an index to extract information
109123       ** in the right order to begin with.
109124       */
109125       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
109126       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
109127           WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
109128       );
109129       if( pWInfo==0 ) goto select_end;
109130       if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
109131         /* The optimizer is able to deliver rows in group by order so
109132         ** we do not have to sort.  The OP_OpenEphemeral table will be
109133         ** cancelled later because we still need to use the pKeyInfo
109134         */
109135         groupBySort = 0;
109136       }else{
109137         /* Rows are coming out in undetermined order.  We have to push
109138         ** each row into a sorting index, terminate the first loop,
109139         ** then loop over the sorting index in order to get the output
109140         ** in sorted order
109141         */
109142         int regBase;
109143         int regRecord;
109144         int nCol;
109145         int nGroupBy;
109146 
109147         explainTempTable(pParse,
109148             (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
109149                     "DISTINCT" : "GROUP BY");
109150 
109151         groupBySort = 1;
109152         nGroupBy = pGroupBy->nExpr;
109153         nCol = nGroupBy;
109154         j = nGroupBy;
109155         for(i=0; i<sAggInfo.nColumn; i++){
109156           if( sAggInfo.aCol[i].iSorterColumn>=j ){
109157             nCol++;
109158             j++;
109159           }
109160         }
109161         regBase = sqlite3GetTempRange(pParse, nCol);
109162         sqlite3ExprCacheClear(pParse);
109163         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
109164         j = nGroupBy;
109165         for(i=0; i<sAggInfo.nColumn; i++){
109166           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
109167           if( pCol->iSorterColumn>=j ){
109168             int r1 = j + regBase;
109169             int r2;
109170 
109171             r2 = sqlite3ExprCodeGetColumn(pParse,
109172                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
109173             if( r1!=r2 ){
109174               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
109175             }
109176             j++;
109177           }
109178         }
109179         regRecord = sqlite3GetTempReg(pParse);
109180         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
109181         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
109182         sqlite3ReleaseTempReg(pParse, regRecord);
109183         sqlite3ReleaseTempRange(pParse, regBase, nCol);
109184         sqlite3WhereEnd(pWInfo);
109185         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
109186         sortOut = sqlite3GetTempReg(pParse);
109187         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
109188         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
109189         VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
109190         sAggInfo.useSortingIdx = 1;
109191         sqlite3ExprCacheClear(pParse);
109192 
109193       }
109194 
109195       /* If the index or temporary table used by the GROUP BY sort
109196       ** will naturally deliver rows in the order required by the ORDER BY
109197       ** clause, cancel the ephemeral table open coded earlier.
109198       **
109199       ** This is an optimization - the correct answer should result regardless.
109200       ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
109201       ** disable this optimization for testing purposes.  */
109202       if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
109203        && (groupBySort || sqlite3WhereIsSorted(pWInfo))
109204       ){
109205         sSort.pOrderBy = 0;
109206         sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
109207       }
109208 
109209       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
109210       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
109211       ** Then compare the current GROUP BY terms against the GROUP BY terms
109212       ** from the previous row currently stored in a0, a1, a2...
109213       */
109214       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
109215       sqlite3ExprCacheClear(pParse);
109216       if( groupBySort ){
109217         sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx, sortOut,sortPTab);
109218       }
109219       for(j=0; j<pGroupBy->nExpr; j++){
109220         if( groupBySort ){
109221           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
109222         }else{
109223           sAggInfo.directMode = 1;
109224           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
109225         }
109226       }
109227       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
109228                           (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
109229       j1 = sqlite3VdbeCurrentAddr(v);
109230       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); VdbeCoverage(v);
109231 
109232       /* Generate code that runs whenever the GROUP BY changes.
109233       ** Changes in the GROUP BY are detected by the previous code
109234       ** block.  If there were no changes, this block is skipped.
109235       **
109236       ** This code copies current group by terms in b0,b1,b2,...
109237       ** over to a0,a1,a2.  It then calls the output subroutine
109238       ** and resets the aggregate accumulator registers in preparation
109239       ** for the next GROUP BY batch.
109240       */
109241       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
109242       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
109243       VdbeComment((v, "output one row"));
109244       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
109245       VdbeComment((v, "check abort flag"));
109246       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
109247       VdbeComment((v, "reset accumulator"));
109248 
109249       /* Update the aggregate accumulators based on the content of
109250       ** the current row
109251       */
109252       sqlite3VdbeJumpHere(v, j1);
109253       updateAccumulator(pParse, &sAggInfo);
109254       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
109255       VdbeComment((v, "indicate data in accumulator"));
109256 
109257       /* End of the loop
109258       */
109259       if( groupBySort ){
109260         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
109261         VdbeCoverage(v);
109262       }else{
109263         sqlite3WhereEnd(pWInfo);
109264         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
109265       }
109266 
109267       /* Output the final row of result
109268       */
109269       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
109270       VdbeComment((v, "output final row"));
109271 
109272       /* Jump over the subroutines
109273       */
109274       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
109275 
109276       /* Generate a subroutine that outputs a single row of the result
109277       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
109278       ** is less than or equal to zero, the subroutine is a no-op.  If
109279       ** the processing calls for the query to abort, this subroutine
109280       ** increments the iAbortFlag memory location before returning in
109281       ** order to signal the caller to abort.
109282       */
109283       addrSetAbort = sqlite3VdbeCurrentAddr(v);
109284       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
109285       VdbeComment((v, "set abort flag"));
109286       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
109287       sqlite3VdbeResolveLabel(v, addrOutputRow);
109288       addrOutputRow = sqlite3VdbeCurrentAddr(v);
109289       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); VdbeCoverage(v);
109290       VdbeComment((v, "Groupby result generator entry point"));
109291       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
109292       finalizeAggFunctions(pParse, &sAggInfo);
109293       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
109294       selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
109295                       &sDistinct, pDest,
109296                       addrOutputRow+1, addrSetAbort);
109297       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
109298       VdbeComment((v, "end groupby result generator"));
109299 
109300       /* Generate a subroutine that will reset the group-by accumulator
109301       */
109302       sqlite3VdbeResolveLabel(v, addrReset);
109303       resetAccumulator(pParse, &sAggInfo);
109304       sqlite3VdbeAddOp1(v, OP_Return, regReset);
109305 
109306     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
109307     else {
109308       ExprList *pDel = 0;
109309 #ifndef SQLITE_OMIT_BTREECOUNT
109310       Table *pTab;
109311       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
109312         /* If isSimpleCount() returns a pointer to a Table structure, then
109313         ** the SQL statement is of the form:
109314         **
109315         **   SELECT count(*) FROM <tbl>
109316         **
109317         ** where the Table structure returned represents table <tbl>.
109318         **
109319         ** This statement is so common that it is optimized specially. The
109320         ** OP_Count instruction is executed either on the intkey table that
109321         ** contains the data for table <tbl> or on one of its indexes. It
109322         ** is better to execute the op on an index, as indexes are almost
109323         ** always spread across less pages than their corresponding tables.
109324         */
109325         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
109326         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
109327         Index *pIdx;                         /* Iterator variable */
109328         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
109329         Index *pBest = 0;                    /* Best index found so far */
109330         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
109331 
109332         sqlite3CodeVerifySchema(pParse, iDb);
109333         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
109334 
109335         /* Search for the index that has the lowest scan cost.
109336         **
109337         ** (2011-04-15) Do not do a full scan of an unordered index.
109338         **
109339         ** (2013-10-03) Do not count the entries in a partial index.
109340         **
109341         ** In practice the KeyInfo structure will not be used. It is only
109342         ** passed to keep OP_OpenRead happy.
109343         */
109344         if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
109345         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
109346           if( pIdx->bUnordered==0
109347            && pIdx->szIdxRow<pTab->szTabRow
109348            && pIdx->pPartIdxWhere==0
109349            && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
109350           ){
109351             pBest = pIdx;
109352           }
109353         }
109354         if( pBest ){
109355           iRoot = pBest->tnum;
109356           pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
109357         }
109358 
109359         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
109360         sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
109361         if( pKeyInfo ){
109362           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
109363         }
109364         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
109365         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
109366         explainSimpleCount(pParse, pTab, pBest);
109367       }else
109368 #endif /* SQLITE_OMIT_BTREECOUNT */
109369       {
109370         /* Check if the query is of one of the following forms:
109371         **
109372         **   SELECT min(x) FROM ...
109373         **   SELECT max(x) FROM ...
109374         **
109375         ** If it is, then ask the code in where.c to attempt to sort results
109376         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
109377         ** If where.c is able to produce results sorted in this order, then
109378         ** add vdbe code to break out of the processing loop after the
109379         ** first iteration (since the first iteration of the loop is
109380         ** guaranteed to operate on the row with the minimum or maximum
109381         ** value of x, the only row required).
109382         **
109383         ** A special flag must be passed to sqlite3WhereBegin() to slightly
109384         ** modify behavior as follows:
109385         **
109386         **   + If the query is a "SELECT min(x)", then the loop coded by
109387         **     where.c should not iterate over any values with a NULL value
109388         **     for x.
109389         **
109390         **   + The optimizer code in where.c (the thing that decides which
109391         **     index or indices to use) should place a different priority on
109392         **     satisfying the 'ORDER BY' clause than it does in other cases.
109393         **     Refer to code and comments in where.c for details.
109394         */
109395         ExprList *pMinMax = 0;
109396         u8 flag = WHERE_ORDERBY_NORMAL;
109397 
109398         assert( p->pGroupBy==0 );
109399         assert( flag==0 );
109400         if( p->pHaving==0 ){
109401           flag = minMaxQuery(&sAggInfo, &pMinMax);
109402         }
109403         assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
109404 
109405         if( flag ){
109406           pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
109407           pDel = pMinMax;
109408           if( pMinMax && !db->mallocFailed ){
109409             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
109410             pMinMax->a[0].pExpr->op = TK_COLUMN;
109411           }
109412         }
109413 
109414         /* This case runs if the aggregate has no GROUP BY clause.  The
109415         ** processing is much simpler since there is only a single row
109416         ** of output.
109417         */
109418         resetAccumulator(pParse, &sAggInfo);
109419         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
109420         if( pWInfo==0 ){
109421           sqlite3ExprListDelete(db, pDel);
109422           goto select_end;
109423         }
109424         updateAccumulator(pParse, &sAggInfo);
109425         assert( pMinMax==0 || pMinMax->nExpr==1 );
109426         if( sqlite3WhereIsOrdered(pWInfo)>0 ){
109427           sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
109428           VdbeComment((v, "%s() by index",
109429                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
109430         }
109431         sqlite3WhereEnd(pWInfo);
109432         finalizeAggFunctions(pParse, &sAggInfo);
109433       }
109434 
109435       sSort.pOrderBy = 0;
109436       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
109437       selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
109438                       pDest, addrEnd, addrEnd);
109439       sqlite3ExprListDelete(db, pDel);
109440     }
109441     sqlite3VdbeResolveLabel(v, addrEnd);
109442 
109443   } /* endif aggregate query */
109444 
109445   if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
109446     explainTempTable(pParse, "DISTINCT");
109447   }
109448 
109449   /* If there is an ORDER BY clause, then we need to sort the results
109450   ** and send them to the callback one by one.
109451   */
109452   if( sSort.pOrderBy ){
109453     explainTempTable(pParse, sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
109454     generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
109455   }
109456 
109457   /* Jump here to skip this query
109458   */
109459   sqlite3VdbeResolveLabel(v, iEnd);
109460 
109461   /* The SELECT was successfully coded.   Set the return code to 0
109462   ** to indicate no errors.
109463   */
109464   rc = 0;
109465 
109466   /* Control jumps to here if an error is encountered above, or upon
109467   ** successful coding of the SELECT.
109468   */
109469 select_end:
109470   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
109471 
109472   /* Identify column names if results of the SELECT are to be output.
109473   */
109474   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
109475     generateColumnNames(pParse, pTabList, pEList);
109476   }
109477 
109478   sqlite3DbFree(db, sAggInfo.aCol);
109479   sqlite3DbFree(db, sAggInfo.aFunc);
109480 #if SELECTTRACE_ENABLED
109481   SELECTTRACE(1,pParse,p,("end processing\n"));
109482   pParse->nSelectIndent--;
109483 #endif
109484   return rc;
109485 }
109486 
109487 #ifdef SQLITE_DEBUG
109488 /*
109489 ** Generate a human-readable description of a the Select object.
109490 */
109491 SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
109492   int n = 0;
109493   pView = sqlite3TreeViewPush(pView, moreToFollow);
109494   sqlite3TreeViewLine(pView, "SELECT%s%s",
109495     ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
109496     ((p->selFlags & SF_Aggregate) ? " agg_flag" : "")
109497   );
109498   if( p->pSrc && p->pSrc->nSrc ) n++;
109499   if( p->pWhere ) n++;
109500   if( p->pGroupBy ) n++;
109501   if( p->pHaving ) n++;
109502   if( p->pOrderBy ) n++;
109503   if( p->pLimit ) n++;
109504   if( p->pOffset ) n++;
109505   if( p->pPrior ) n++;
109506   sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
109507   if( p->pSrc && p->pSrc->nSrc ){
109508     int i;
109509     pView = sqlite3TreeViewPush(pView, (n--)>0);
109510     sqlite3TreeViewLine(pView, "FROM");
109511     for(i=0; i<p->pSrc->nSrc; i++){
109512       struct SrcList_item *pItem = &p->pSrc->a[i];
109513       StrAccum x;
109514       char zLine[100];
109515       sqlite3StrAccumInit(&x, zLine, sizeof(zLine), 0);
109516       sqlite3XPrintf(&x, 0, "{%d,*}", pItem->iCursor);
109517       if( pItem->zDatabase ){
109518         sqlite3XPrintf(&x, 0, " %s.%s", pItem->zDatabase, pItem->zName);
109519       }else if( pItem->zName ){
109520         sqlite3XPrintf(&x, 0, " %s", pItem->zName);
109521       }
109522       if( pItem->pTab ){
109523         sqlite3XPrintf(&x, 0, " tabname=%Q", pItem->pTab->zName);
109524       }
109525       if( pItem->zAlias ){
109526         sqlite3XPrintf(&x, 0, " (AS %s)", pItem->zAlias);
109527       }
109528       if( pItem->jointype & JT_LEFT ){
109529         sqlite3XPrintf(&x, 0, " LEFT-JOIN");
109530       }
109531       sqlite3StrAccumFinish(&x);
109532       sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
109533       if( pItem->pSelect ){
109534         sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
109535       }
109536       sqlite3TreeViewPop(pView);
109537     }
109538     sqlite3TreeViewPop(pView);
109539   }
109540   if( p->pWhere ){
109541     sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
109542     sqlite3TreeViewExpr(pView, p->pWhere, 0);
109543     sqlite3TreeViewPop(pView);
109544   }
109545   if( p->pGroupBy ){
109546     sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
109547   }
109548   if( p->pHaving ){
109549     sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
109550     sqlite3TreeViewExpr(pView, p->pHaving, 0);
109551     sqlite3TreeViewPop(pView);
109552   }
109553   if( p->pOrderBy ){
109554     sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
109555   }
109556   if( p->pLimit ){
109557     sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
109558     sqlite3TreeViewExpr(pView, p->pLimit, 0);
109559     sqlite3TreeViewPop(pView);
109560   }
109561   if( p->pOffset ){
109562     sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
109563     sqlite3TreeViewExpr(pView, p->pOffset, 0);
109564     sqlite3TreeViewPop(pView);
109565   }
109566   if( p->pPrior ){
109567     const char *zOp = "UNION";
109568     switch( p->op ){
109569       case TK_ALL:         zOp = "UNION ALL";  break;
109570       case TK_INTERSECT:   zOp = "INTERSECT";  break;
109571       case TK_EXCEPT:      zOp = "EXCEPT";     break;
109572     }
109573     sqlite3TreeViewItem(pView, zOp, (n--)>0);
109574     sqlite3TreeViewSelect(pView, p->pPrior, 0);
109575     sqlite3TreeViewPop(pView);
109576   }
109577   sqlite3TreeViewPop(pView);
109578 }
109579 #endif /* SQLITE_DEBUG */
109580 
109581 /************** End of select.c **********************************************/
109582 /************** Begin file table.c *******************************************/
109583 /*
109584 ** 2001 September 15
109585 **
109586 ** The author disclaims copyright to this source code.  In place of
109587 ** a legal notice, here is a blessing:
109588 **
109589 **    May you do good and not evil.
109590 **    May you find forgiveness for yourself and forgive others.
109591 **    May you share freely, never taking more than you give.
109592 **
109593 *************************************************************************
109594 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
109595 ** interface routines.  These are just wrappers around the main
109596 ** interface routine of sqlite3_exec().
109597 **
109598 ** These routines are in a separate files so that they will not be linked
109599 ** if they are not used.
109600 */
109601 /* #include <stdlib.h> */
109602 /* #include <string.h> */
109603 
109604 #ifndef SQLITE_OMIT_GET_TABLE
109605 
109606 /*
109607 ** This structure is used to pass data from sqlite3_get_table() through
109608 ** to the callback function is uses to build the result.
109609 */
109610 typedef struct TabResult {
109611   char **azResult;   /* Accumulated output */
109612   char *zErrMsg;     /* Error message text, if an error occurs */
109613   u32 nAlloc;        /* Slots allocated for azResult[] */
109614   u32 nRow;          /* Number of rows in the result */
109615   u32 nColumn;       /* Number of columns in the result */
109616   u32 nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
109617   int rc;            /* Return code from sqlite3_exec() */
109618 } TabResult;
109619 
109620 /*
109621 ** This routine is called once for each row in the result table.  Its job
109622 ** is to fill in the TabResult structure appropriately, allocating new
109623 ** memory as necessary.
109624 */
109625 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
109626   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
109627   int need;                         /* Slots needed in p->azResult[] */
109628   int i;                            /* Loop counter */
109629   char *z;                          /* A single column of result */
109630 
109631   /* Make sure there is enough space in p->azResult to hold everything
109632   ** we need to remember from this invocation of the callback.
109633   */
109634   if( p->nRow==0 && argv!=0 ){
109635     need = nCol*2;
109636   }else{
109637     need = nCol;
109638   }
109639   if( p->nData + need > p->nAlloc ){
109640     char **azNew;
109641     p->nAlloc = p->nAlloc*2 + need;
109642     azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
109643     if( azNew==0 ) goto malloc_failed;
109644     p->azResult = azNew;
109645   }
109646 
109647   /* If this is the first row, then generate an extra row containing
109648   ** the names of all columns.
109649   */
109650   if( p->nRow==0 ){
109651     p->nColumn = nCol;
109652     for(i=0; i<nCol; i++){
109653       z = sqlite3_mprintf("%s", colv[i]);
109654       if( z==0 ) goto malloc_failed;
109655       p->azResult[p->nData++] = z;
109656     }
109657   }else if( (int)p->nColumn!=nCol ){
109658     sqlite3_free(p->zErrMsg);
109659     p->zErrMsg = sqlite3_mprintf(
109660        "sqlite3_get_table() called with two or more incompatible queries"
109661     );
109662     p->rc = SQLITE_ERROR;
109663     return 1;
109664   }
109665 
109666   /* Copy over the row data
109667   */
109668   if( argv!=0 ){
109669     for(i=0; i<nCol; i++){
109670       if( argv[i]==0 ){
109671         z = 0;
109672       }else{
109673         int n = sqlite3Strlen30(argv[i])+1;
109674         z = sqlite3_malloc( n );
109675         if( z==0 ) goto malloc_failed;
109676         memcpy(z, argv[i], n);
109677       }
109678       p->azResult[p->nData++] = z;
109679     }
109680     p->nRow++;
109681   }
109682   return 0;
109683 
109684 malloc_failed:
109685   p->rc = SQLITE_NOMEM;
109686   return 1;
109687 }
109688 
109689 /*
109690 ** Query the database.  But instead of invoking a callback for each row,
109691 ** malloc() for space to hold the result and return the entire results
109692 ** at the conclusion of the call.
109693 **
109694 ** The result that is written to ***pazResult is held in memory obtained
109695 ** from malloc().  But the caller cannot free this memory directly.
109696 ** Instead, the entire table should be passed to sqlite3_free_table() when
109697 ** the calling procedure is finished using it.
109698 */
109699 SQLITE_API int sqlite3_get_table(
109700   sqlite3 *db,                /* The database on which the SQL executes */
109701   const char *zSql,           /* The SQL to be executed */
109702   char ***pazResult,          /* Write the result table here */
109703   int *pnRow,                 /* Write the number of rows in the result here */
109704   int *pnColumn,              /* Write the number of columns of result here */
109705   char **pzErrMsg             /* Write error messages here */
109706 ){
109707   int rc;
109708   TabResult res;
109709 
109710   *pazResult = 0;
109711   if( pnColumn ) *pnColumn = 0;
109712   if( pnRow ) *pnRow = 0;
109713   if( pzErrMsg ) *pzErrMsg = 0;
109714   res.zErrMsg = 0;
109715   res.nRow = 0;
109716   res.nColumn = 0;
109717   res.nData = 1;
109718   res.nAlloc = 20;
109719   res.rc = SQLITE_OK;
109720   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
109721   if( res.azResult==0 ){
109722      db->errCode = SQLITE_NOMEM;
109723      return SQLITE_NOMEM;
109724   }
109725   res.azResult[0] = 0;
109726   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
109727   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
109728   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
109729   if( (rc&0xff)==SQLITE_ABORT ){
109730     sqlite3_free_table(&res.azResult[1]);
109731     if( res.zErrMsg ){
109732       if( pzErrMsg ){
109733         sqlite3_free(*pzErrMsg);
109734         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
109735       }
109736       sqlite3_free(res.zErrMsg);
109737     }
109738     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
109739     return res.rc;
109740   }
109741   sqlite3_free(res.zErrMsg);
109742   if( rc!=SQLITE_OK ){
109743     sqlite3_free_table(&res.azResult[1]);
109744     return rc;
109745   }
109746   if( res.nAlloc>res.nData ){
109747     char **azNew;
109748     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
109749     if( azNew==0 ){
109750       sqlite3_free_table(&res.azResult[1]);
109751       db->errCode = SQLITE_NOMEM;
109752       return SQLITE_NOMEM;
109753     }
109754     res.azResult = azNew;
109755   }
109756   *pazResult = &res.azResult[1];
109757   if( pnColumn ) *pnColumn = res.nColumn;
109758   if( pnRow ) *pnRow = res.nRow;
109759   return rc;
109760 }
109761 
109762 /*
109763 ** This routine frees the space the sqlite3_get_table() malloced.
109764 */
109765 SQLITE_API void sqlite3_free_table(
109766   char **azResult            /* Result returned from sqlite3_get_table() */
109767 ){
109768   if( azResult ){
109769     int i, n;
109770     azResult--;
109771     assert( azResult!=0 );
109772     n = SQLITE_PTR_TO_INT(azResult[0]);
109773     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
109774     sqlite3_free(azResult);
109775   }
109776 }
109777 
109778 #endif /* SQLITE_OMIT_GET_TABLE */
109779 
109780 /************** End of table.c ***********************************************/
109781 /************** Begin file trigger.c *****************************************/
109782 /*
109783 **
109784 ** The author disclaims copyright to this source code.  In place of
109785 ** a legal notice, here is a blessing:
109786 **
109787 **    May you do good and not evil.
109788 **    May you find forgiveness for yourself and forgive others.
109789 **    May you share freely, never taking more than you give.
109790 **
109791 *************************************************************************
109792 ** This file contains the implementation for TRIGGERs
109793 */
109794 
109795 #ifndef SQLITE_OMIT_TRIGGER
109796 /*
109797 ** Delete a linked list of TriggerStep structures.
109798 */
109799 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
109800   while( pTriggerStep ){
109801     TriggerStep * pTmp = pTriggerStep;
109802     pTriggerStep = pTriggerStep->pNext;
109803 
109804     sqlite3ExprDelete(db, pTmp->pWhere);
109805     sqlite3ExprListDelete(db, pTmp->pExprList);
109806     sqlite3SelectDelete(db, pTmp->pSelect);
109807     sqlite3IdListDelete(db, pTmp->pIdList);
109808 
109809     sqlite3DbFree(db, pTmp);
109810   }
109811 }
109812 
109813 /*
109814 ** Given table pTab, return a list of all the triggers attached to
109815 ** the table. The list is connected by Trigger.pNext pointers.
109816 **
109817 ** All of the triggers on pTab that are in the same database as pTab
109818 ** are already attached to pTab->pTrigger.  But there might be additional
109819 ** triggers on pTab in the TEMP schema.  This routine prepends all
109820 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
109821 ** and returns the combined list.
109822 **
109823 ** To state it another way:  This routine returns a list of all triggers
109824 ** that fire off of pTab.  The list will include any TEMP triggers on
109825 ** pTab as well as the triggers lised in pTab->pTrigger.
109826 */
109827 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
109828   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
109829   Trigger *pList = 0;                  /* List of triggers to return */
109830 
109831   if( pParse->disableTriggers ){
109832     return 0;
109833   }
109834 
109835   if( pTmpSchema!=pTab->pSchema ){
109836     HashElem *p;
109837     assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
109838     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
109839       Trigger *pTrig = (Trigger *)sqliteHashData(p);
109840       if( pTrig->pTabSchema==pTab->pSchema
109841        && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
109842       ){
109843         pTrig->pNext = (pList ? pList : pTab->pTrigger);
109844         pList = pTrig;
109845       }
109846     }
109847   }
109848 
109849   return (pList ? pList : pTab->pTrigger);
109850 }
109851 
109852 /*
109853 ** This is called by the parser when it sees a CREATE TRIGGER statement
109854 ** up to the point of the BEGIN before the trigger actions.  A Trigger
109855 ** structure is generated based on the information available and stored
109856 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
109857 ** sqlite3FinishTrigger() function is called to complete the trigger
109858 ** construction process.
109859 */
109860 SQLITE_PRIVATE void sqlite3BeginTrigger(
109861   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
109862   Token *pName1,      /* The name of the trigger */
109863   Token *pName2,      /* The name of the trigger */
109864   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
109865   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
109866   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
109867   SrcList *pTableName,/* The name of the table/view the trigger applies to */
109868   Expr *pWhen,        /* WHEN clause */
109869   int isTemp,         /* True if the TEMPORARY keyword is present */
109870   int noErr           /* Suppress errors if the trigger already exists */
109871 ){
109872   Trigger *pTrigger = 0;  /* The new trigger */
109873   Table *pTab;            /* Table that the trigger fires off of */
109874   char *zName = 0;        /* Name of the trigger */
109875   sqlite3 *db = pParse->db;  /* The database connection */
109876   int iDb;                /* The database to store the trigger in */
109877   Token *pName;           /* The unqualified db name */
109878   DbFixer sFix;           /* State vector for the DB fixer */
109879   int iTabDb;             /* Index of the database holding pTab */
109880 
109881   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
109882   assert( pName2!=0 );
109883   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
109884   assert( op>0 && op<0xff );
109885   if( isTemp ){
109886     /* If TEMP was specified, then the trigger name may not be qualified. */
109887     if( pName2->n>0 ){
109888       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
109889       goto trigger_cleanup;
109890     }
109891     iDb = 1;
109892     pName = pName1;
109893   }else{
109894     /* Figure out the db that the trigger will be created in */
109895     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
109896     if( iDb<0 ){
109897       goto trigger_cleanup;
109898     }
109899   }
109900   if( !pTableName || db->mallocFailed ){
109901     goto trigger_cleanup;
109902   }
109903 
109904   /* A long-standing parser bug is that this syntax was allowed:
109905   **
109906   **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
109907   **                                                 ^^^^^^^^
109908   **
109909   ** To maintain backwards compatibility, ignore the database
109910   ** name on pTableName if we are reparsing out of SQLITE_MASTER.
109911   */
109912   if( db->init.busy && iDb!=1 ){
109913     sqlite3DbFree(db, pTableName->a[0].zDatabase);
109914     pTableName->a[0].zDatabase = 0;
109915   }
109916 
109917   /* If the trigger name was unqualified, and the table is a temp table,
109918   ** then set iDb to 1 to create the trigger in the temporary database.
109919   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
109920   ** exist, the error is caught by the block below.
109921   */
109922   pTab = sqlite3SrcListLookup(pParse, pTableName);
109923   if( db->init.busy==0 && pName2->n==0 && pTab
109924         && pTab->pSchema==db->aDb[1].pSchema ){
109925     iDb = 1;
109926   }
109927 
109928   /* Ensure the table name matches database name and that the table exists */
109929   if( db->mallocFailed ) goto trigger_cleanup;
109930   assert( pTableName->nSrc==1 );
109931   sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
109932   if( sqlite3FixSrcList(&sFix, pTableName) ){
109933     goto trigger_cleanup;
109934   }
109935   pTab = sqlite3SrcListLookup(pParse, pTableName);
109936   if( !pTab ){
109937     /* The table does not exist. */
109938     if( db->init.iDb==1 ){
109939       /* Ticket #3810.
109940       ** Normally, whenever a table is dropped, all associated triggers are
109941       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
109942       ** and the table is dropped by a different database connection, the
109943       ** trigger is not visible to the database connection that does the
109944       ** drop so the trigger cannot be dropped.  This results in an
109945       ** "orphaned trigger" - a trigger whose associated table is missing.
109946       */
109947       db->init.orphanTrigger = 1;
109948     }
109949     goto trigger_cleanup;
109950   }
109951   if( IsVirtual(pTab) ){
109952     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
109953     goto trigger_cleanup;
109954   }
109955 
109956   /* Check that the trigger name is not reserved and that no trigger of the
109957   ** specified name exists */
109958   zName = sqlite3NameFromToken(db, pName);
109959   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
109960     goto trigger_cleanup;
109961   }
109962   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
109963   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
109964     if( !noErr ){
109965       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
109966     }else{
109967       assert( !db->init.busy );
109968       sqlite3CodeVerifySchema(pParse, iDb);
109969     }
109970     goto trigger_cleanup;
109971   }
109972 
109973   /* Do not create a trigger on a system table */
109974   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
109975     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
109976     pParse->nErr++;
109977     goto trigger_cleanup;
109978   }
109979 
109980   /* INSTEAD of triggers are only for views and views only support INSTEAD
109981   ** of triggers.
109982   */
109983   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
109984     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
109985         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
109986     goto trigger_cleanup;
109987   }
109988   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
109989     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
109990         " trigger on table: %S", pTableName, 0);
109991     goto trigger_cleanup;
109992   }
109993   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
109994 
109995 #ifndef SQLITE_OMIT_AUTHORIZATION
109996   {
109997     int code = SQLITE_CREATE_TRIGGER;
109998     const char *zDb = db->aDb[iTabDb].zName;
109999     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
110000     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
110001     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
110002       goto trigger_cleanup;
110003     }
110004     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
110005       goto trigger_cleanup;
110006     }
110007   }
110008 #endif
110009 
110010   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
110011   ** cannot appear on views.  So we might as well translate every
110012   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
110013   ** elsewhere.
110014   */
110015   if (tr_tm == TK_INSTEAD){
110016     tr_tm = TK_BEFORE;
110017   }
110018 
110019   /* Build the Trigger object */
110020   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
110021   if( pTrigger==0 ) goto trigger_cleanup;
110022   pTrigger->zName = zName;
110023   zName = 0;
110024   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
110025   pTrigger->pSchema = db->aDb[iDb].pSchema;
110026   pTrigger->pTabSchema = pTab->pSchema;
110027   pTrigger->op = (u8)op;
110028   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
110029   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
110030   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
110031   assert( pParse->pNewTrigger==0 );
110032   pParse->pNewTrigger = pTrigger;
110033 
110034 trigger_cleanup:
110035   sqlite3DbFree(db, zName);
110036   sqlite3SrcListDelete(db, pTableName);
110037   sqlite3IdListDelete(db, pColumns);
110038   sqlite3ExprDelete(db, pWhen);
110039   if( !pParse->pNewTrigger ){
110040     sqlite3DeleteTrigger(db, pTrigger);
110041   }else{
110042     assert( pParse->pNewTrigger==pTrigger );
110043   }
110044 }
110045 
110046 /*
110047 ** This routine is called after all of the trigger actions have been parsed
110048 ** in order to complete the process of building the trigger.
110049 */
110050 SQLITE_PRIVATE void sqlite3FinishTrigger(
110051   Parse *pParse,          /* Parser context */
110052   TriggerStep *pStepList, /* The triggered program */
110053   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
110054 ){
110055   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
110056   char *zName;                            /* Name of trigger */
110057   sqlite3 *db = pParse->db;               /* The database */
110058   DbFixer sFix;                           /* Fixer object */
110059   int iDb;                                /* Database containing the trigger */
110060   Token nameToken;                        /* Trigger name for error reporting */
110061 
110062   pParse->pNewTrigger = 0;
110063   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
110064   zName = pTrig->zName;
110065   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
110066   pTrig->step_list = pStepList;
110067   while( pStepList ){
110068     pStepList->pTrig = pTrig;
110069     pStepList = pStepList->pNext;
110070   }
110071   nameToken.z = pTrig->zName;
110072   nameToken.n = sqlite3Strlen30(nameToken.z);
110073   sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
110074   if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
110075    || sqlite3FixExpr(&sFix, pTrig->pWhen)
110076   ){
110077     goto triggerfinish_cleanup;
110078   }
110079 
110080   /* if we are not initializing,
110081   ** build the sqlite_master entry
110082   */
110083   if( !db->init.busy ){
110084     Vdbe *v;
110085     char *z;
110086 
110087     /* Make an entry in the sqlite_master table */
110088     v = sqlite3GetVdbe(pParse);
110089     if( v==0 ) goto triggerfinish_cleanup;
110090     sqlite3BeginWriteOperation(pParse, 0, iDb);
110091     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
110092     sqlite3NestedParse(pParse,
110093        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
110094        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
110095        pTrig->table, z);
110096     sqlite3DbFree(db, z);
110097     sqlite3ChangeCookie(pParse, iDb);
110098     sqlite3VdbeAddParseSchemaOp(v, iDb,
110099         sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
110100   }
110101 
110102   if( db->init.busy ){
110103     Trigger *pLink = pTrig;
110104     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
110105     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
110106     pTrig = sqlite3HashInsert(pHash, zName, pTrig);
110107     if( pTrig ){
110108       db->mallocFailed = 1;
110109     }else if( pLink->pSchema==pLink->pTabSchema ){
110110       Table *pTab;
110111       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
110112       assert( pTab!=0 );
110113       pLink->pNext = pTab->pTrigger;
110114       pTab->pTrigger = pLink;
110115     }
110116   }
110117 
110118 triggerfinish_cleanup:
110119   sqlite3DeleteTrigger(db, pTrig);
110120   assert( !pParse->pNewTrigger );
110121   sqlite3DeleteTriggerStep(db, pStepList);
110122 }
110123 
110124 /*
110125 ** Turn a SELECT statement (that the pSelect parameter points to) into
110126 ** a trigger step.  Return a pointer to a TriggerStep structure.
110127 **
110128 ** The parser calls this routine when it finds a SELECT statement in
110129 ** body of a TRIGGER.
110130 */
110131 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
110132   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
110133   if( pTriggerStep==0 ) {
110134     sqlite3SelectDelete(db, pSelect);
110135     return 0;
110136   }
110137   pTriggerStep->op = TK_SELECT;
110138   pTriggerStep->pSelect = pSelect;
110139   pTriggerStep->orconf = OE_Default;
110140   return pTriggerStep;
110141 }
110142 
110143 /*
110144 ** Allocate space to hold a new trigger step.  The allocated space
110145 ** holds both the TriggerStep object and the TriggerStep.target.z string.
110146 **
110147 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
110148 */
110149 static TriggerStep *triggerStepAllocate(
110150   sqlite3 *db,                /* Database connection */
110151   u8 op,                      /* Trigger opcode */
110152   Token *pName                /* The target name */
110153 ){
110154   TriggerStep *pTriggerStep;
110155 
110156   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
110157   if( pTriggerStep ){
110158     char *z = (char*)&pTriggerStep[1];
110159     memcpy(z, pName->z, pName->n);
110160     pTriggerStep->target.z = z;
110161     pTriggerStep->target.n = pName->n;
110162     pTriggerStep->op = op;
110163   }
110164   return pTriggerStep;
110165 }
110166 
110167 /*
110168 ** Build a trigger step out of an INSERT statement.  Return a pointer
110169 ** to the new trigger step.
110170 **
110171 ** The parser calls this routine when it sees an INSERT inside the
110172 ** body of a trigger.
110173 */
110174 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
110175   sqlite3 *db,        /* The database connection */
110176   Token *pTableName,  /* Name of the table into which we insert */
110177   IdList *pColumn,    /* List of columns in pTableName to insert into */
110178   Select *pSelect,    /* A SELECT statement that supplies values */
110179   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
110180 ){
110181   TriggerStep *pTriggerStep;
110182 
110183   assert(pSelect != 0 || db->mallocFailed);
110184 
110185   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
110186   if( pTriggerStep ){
110187     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
110188     pTriggerStep->pIdList = pColumn;
110189     pTriggerStep->orconf = orconf;
110190   }else{
110191     sqlite3IdListDelete(db, pColumn);
110192   }
110193   sqlite3SelectDelete(db, pSelect);
110194 
110195   return pTriggerStep;
110196 }
110197 
110198 /*
110199 ** Construct a trigger step that implements an UPDATE statement and return
110200 ** a pointer to that trigger step.  The parser calls this routine when it
110201 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
110202 */
110203 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
110204   sqlite3 *db,         /* The database connection */
110205   Token *pTableName,   /* Name of the table to be updated */
110206   ExprList *pEList,    /* The SET clause: list of column and new values */
110207   Expr *pWhere,        /* The WHERE clause */
110208   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
110209 ){
110210   TriggerStep *pTriggerStep;
110211 
110212   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
110213   if( pTriggerStep ){
110214     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
110215     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
110216     pTriggerStep->orconf = orconf;
110217   }
110218   sqlite3ExprListDelete(db, pEList);
110219   sqlite3ExprDelete(db, pWhere);
110220   return pTriggerStep;
110221 }
110222 
110223 /*
110224 ** Construct a trigger step that implements a DELETE statement and return
110225 ** a pointer to that trigger step.  The parser calls this routine when it
110226 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
110227 */
110228 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
110229   sqlite3 *db,            /* Database connection */
110230   Token *pTableName,      /* The table from which rows are deleted */
110231   Expr *pWhere            /* The WHERE clause */
110232 ){
110233   TriggerStep *pTriggerStep;
110234 
110235   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
110236   if( pTriggerStep ){
110237     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
110238     pTriggerStep->orconf = OE_Default;
110239   }
110240   sqlite3ExprDelete(db, pWhere);
110241   return pTriggerStep;
110242 }
110243 
110244 /*
110245 ** Recursively delete a Trigger structure
110246 */
110247 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
110248   if( pTrigger==0 ) return;
110249   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
110250   sqlite3DbFree(db, pTrigger->zName);
110251   sqlite3DbFree(db, pTrigger->table);
110252   sqlite3ExprDelete(db, pTrigger->pWhen);
110253   sqlite3IdListDelete(db, pTrigger->pColumns);
110254   sqlite3DbFree(db, pTrigger);
110255 }
110256 
110257 /*
110258 ** This function is called to drop a trigger from the database schema.
110259 **
110260 ** This may be called directly from the parser and therefore identifies
110261 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
110262 ** same job as this routine except it takes a pointer to the trigger
110263 ** instead of the trigger name.
110264 **/
110265 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
110266   Trigger *pTrigger = 0;
110267   int i;
110268   const char *zDb;
110269   const char *zName;
110270   sqlite3 *db = pParse->db;
110271 
110272   if( db->mallocFailed ) goto drop_trigger_cleanup;
110273   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
110274     goto drop_trigger_cleanup;
110275   }
110276 
110277   assert( pName->nSrc==1 );
110278   zDb = pName->a[0].zDatabase;
110279   zName = pName->a[0].zName;
110280   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
110281   for(i=OMIT_TEMPDB; i<db->nDb; i++){
110282     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
110283     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
110284     assert( sqlite3SchemaMutexHeld(db, j, 0) );
110285     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
110286     if( pTrigger ) break;
110287   }
110288   if( !pTrigger ){
110289     if( !noErr ){
110290       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
110291     }else{
110292       sqlite3CodeVerifyNamedSchema(pParse, zDb);
110293     }
110294     pParse->checkSchema = 1;
110295     goto drop_trigger_cleanup;
110296   }
110297   sqlite3DropTriggerPtr(pParse, pTrigger);
110298 
110299 drop_trigger_cleanup:
110300   sqlite3SrcListDelete(db, pName);
110301 }
110302 
110303 /*
110304 ** Return a pointer to the Table structure for the table that a trigger
110305 ** is set on.
110306 */
110307 static Table *tableOfTrigger(Trigger *pTrigger){
110308   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
110309 }
110310 
110311 
110312 /*
110313 ** Drop a trigger given a pointer to that trigger.
110314 */
110315 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
110316   Table   *pTable;
110317   Vdbe *v;
110318   sqlite3 *db = pParse->db;
110319   int iDb;
110320 
110321   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
110322   assert( iDb>=0 && iDb<db->nDb );
110323   pTable = tableOfTrigger(pTrigger);
110324   assert( pTable );
110325   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
110326 #ifndef SQLITE_OMIT_AUTHORIZATION
110327   {
110328     int code = SQLITE_DROP_TRIGGER;
110329     const char *zDb = db->aDb[iDb].zName;
110330     const char *zTab = SCHEMA_TABLE(iDb);
110331     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
110332     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
110333       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
110334       return;
110335     }
110336   }
110337 #endif
110338 
110339   /* Generate code to destroy the database record of the trigger.
110340   */
110341   assert( pTable!=0 );
110342   if( (v = sqlite3GetVdbe(pParse))!=0 ){
110343     int base;
110344     static const int iLn = VDBE_OFFSET_LINENO(2);
110345     static const VdbeOpList dropTrigger[] = {
110346       { OP_Rewind,     0, ADDR(9),  0},
110347       { OP_String8,    0, 1,        0}, /* 1 */
110348       { OP_Column,     0, 1,        2},
110349       { OP_Ne,         2, ADDR(8),  1},
110350       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
110351       { OP_Column,     0, 0,        2},
110352       { OP_Ne,         2, ADDR(8),  1},
110353       { OP_Delete,     0, 0,        0},
110354       { OP_Next,       0, ADDR(1),  0}, /* 8 */
110355     };
110356 
110357     sqlite3BeginWriteOperation(pParse, 0, iDb);
110358     sqlite3OpenMasterTable(pParse, iDb);
110359     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger, iLn);
110360     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
110361     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
110362     sqlite3ChangeCookie(pParse, iDb);
110363     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
110364     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
110365     if( pParse->nMem<3 ){
110366       pParse->nMem = 3;
110367     }
110368   }
110369 }
110370 
110371 /*
110372 ** Remove a trigger from the hash tables of the sqlite* pointer.
110373 */
110374 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
110375   Trigger *pTrigger;
110376   Hash *pHash;
110377 
110378   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
110379   pHash = &(db->aDb[iDb].pSchema->trigHash);
110380   pTrigger = sqlite3HashInsert(pHash, zName, 0);
110381   if( ALWAYS(pTrigger) ){
110382     if( pTrigger->pSchema==pTrigger->pTabSchema ){
110383       Table *pTab = tableOfTrigger(pTrigger);
110384       Trigger **pp;
110385       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
110386       *pp = (*pp)->pNext;
110387     }
110388     sqlite3DeleteTrigger(db, pTrigger);
110389     db->flags |= SQLITE_InternChanges;
110390   }
110391 }
110392 
110393 /*
110394 ** pEList is the SET clause of an UPDATE statement.  Each entry
110395 ** in pEList is of the format <id>=<expr>.  If any of the entries
110396 ** in pEList have an <id> which matches an identifier in pIdList,
110397 ** then return TRUE.  If pIdList==NULL, then it is considered a
110398 ** wildcard that matches anything.  Likewise if pEList==NULL then
110399 ** it matches anything so always return true.  Return false only
110400 ** if there is no match.
110401 */
110402 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
110403   int e;
110404   if( pIdList==0 || NEVER(pEList==0) ) return 1;
110405   for(e=0; e<pEList->nExpr; e++){
110406     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
110407   }
110408   return 0;
110409 }
110410 
110411 /*
110412 ** Return a list of all triggers on table pTab if there exists at least
110413 ** one trigger that must be fired when an operation of type 'op' is
110414 ** performed on the table, and, if that operation is an UPDATE, if at
110415 ** least one of the columns in pChanges is being modified.
110416 */
110417 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
110418   Parse *pParse,          /* Parse context */
110419   Table *pTab,            /* The table the contains the triggers */
110420   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
110421   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
110422   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
110423 ){
110424   int mask = 0;
110425   Trigger *pList = 0;
110426   Trigger *p;
110427 
110428   if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
110429     pList = sqlite3TriggerList(pParse, pTab);
110430   }
110431   assert( pList==0 || IsVirtual(pTab)==0 );
110432   for(p=pList; p; p=p->pNext){
110433     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
110434       mask |= p->tr_tm;
110435     }
110436   }
110437   if( pMask ){
110438     *pMask = mask;
110439   }
110440   return (mask ? pList : 0);
110441 }
110442 
110443 /*
110444 ** Convert the pStep->target token into a SrcList and return a pointer
110445 ** to that SrcList.
110446 **
110447 ** This routine adds a specific database name, if needed, to the target when
110448 ** forming the SrcList.  This prevents a trigger in one database from
110449 ** referring to a target in another database.  An exception is when the
110450 ** trigger is in TEMP in which case it can refer to any other database it
110451 ** wants.
110452 */
110453 static SrcList *targetSrcList(
110454   Parse *pParse,       /* The parsing context */
110455   TriggerStep *pStep   /* The trigger containing the target token */
110456 ){
110457   int iDb;             /* Index of the database to use */
110458   SrcList *pSrc;       /* SrcList to be returned */
110459 
110460   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
110461   if( pSrc ){
110462     assert( pSrc->nSrc>0 );
110463     assert( pSrc->a!=0 );
110464     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
110465     if( iDb==0 || iDb>=2 ){
110466       sqlite3 *db = pParse->db;
110467       assert( iDb<pParse->db->nDb );
110468       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
110469     }
110470   }
110471   return pSrc;
110472 }
110473 
110474 /*
110475 ** Generate VDBE code for the statements inside the body of a single
110476 ** trigger.
110477 */
110478 static int codeTriggerProgram(
110479   Parse *pParse,            /* The parser context */
110480   TriggerStep *pStepList,   /* List of statements inside the trigger body */
110481   int orconf                /* Conflict algorithm. (OE_Abort, etc) */
110482 ){
110483   TriggerStep *pStep;
110484   Vdbe *v = pParse->pVdbe;
110485   sqlite3 *db = pParse->db;
110486 
110487   assert( pParse->pTriggerTab && pParse->pToplevel );
110488   assert( pStepList );
110489   assert( v!=0 );
110490   for(pStep=pStepList; pStep; pStep=pStep->pNext){
110491     /* Figure out the ON CONFLICT policy that will be used for this step
110492     ** of the trigger program. If the statement that caused this trigger
110493     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
110494     ** the ON CONFLICT policy that was specified as part of the trigger
110495     ** step statement. Example:
110496     **
110497     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
110498     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
110499     **   END;
110500     **
110501     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
110502     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
110503     */
110504     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
110505     assert( pParse->okConstFactor==0 );
110506 
110507     switch( pStep->op ){
110508       case TK_UPDATE: {
110509         sqlite3Update(pParse,
110510           targetSrcList(pParse, pStep),
110511           sqlite3ExprListDup(db, pStep->pExprList, 0),
110512           sqlite3ExprDup(db, pStep->pWhere, 0),
110513           pParse->eOrconf
110514         );
110515         break;
110516       }
110517       case TK_INSERT: {
110518         sqlite3Insert(pParse,
110519           targetSrcList(pParse, pStep),
110520           sqlite3SelectDup(db, pStep->pSelect, 0),
110521           sqlite3IdListDup(db, pStep->pIdList),
110522           pParse->eOrconf
110523         );
110524         break;
110525       }
110526       case TK_DELETE: {
110527         sqlite3DeleteFrom(pParse,
110528           targetSrcList(pParse, pStep),
110529           sqlite3ExprDup(db, pStep->pWhere, 0)
110530         );
110531         break;
110532       }
110533       default: assert( pStep->op==TK_SELECT ); {
110534         SelectDest sDest;
110535         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
110536         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
110537         sqlite3Select(pParse, pSelect, &sDest);
110538         sqlite3SelectDelete(db, pSelect);
110539         break;
110540       }
110541     }
110542     if( pStep->op!=TK_SELECT ){
110543       sqlite3VdbeAddOp0(v, OP_ResetCount);
110544     }
110545   }
110546 
110547   return 0;
110548 }
110549 
110550 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
110551 /*
110552 ** This function is used to add VdbeComment() annotations to a VDBE
110553 ** program. It is not used in production code, only for debugging.
110554 */
110555 static const char *onErrorText(int onError){
110556   switch( onError ){
110557     case OE_Abort:    return "abort";
110558     case OE_Rollback: return "rollback";
110559     case OE_Fail:     return "fail";
110560     case OE_Replace:  return "replace";
110561     case OE_Ignore:   return "ignore";
110562     case OE_Default:  return "default";
110563   }
110564   return "n/a";
110565 }
110566 #endif
110567 
110568 /*
110569 ** Parse context structure pFrom has just been used to create a sub-vdbe
110570 ** (trigger program). If an error has occurred, transfer error information
110571 ** from pFrom to pTo.
110572 */
110573 static void transferParseError(Parse *pTo, Parse *pFrom){
110574   assert( pFrom->zErrMsg==0 || pFrom->nErr );
110575   assert( pTo->zErrMsg==0 || pTo->nErr );
110576   if( pTo->nErr==0 ){
110577     pTo->zErrMsg = pFrom->zErrMsg;
110578     pTo->nErr = pFrom->nErr;
110579   }else{
110580     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
110581   }
110582 }
110583 
110584 /*
110585 ** Create and populate a new TriggerPrg object with a sub-program
110586 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
110587 */
110588 static TriggerPrg *codeRowTrigger(
110589   Parse *pParse,       /* Current parse context */
110590   Trigger *pTrigger,   /* Trigger to code */
110591   Table *pTab,         /* The table pTrigger is attached to */
110592   int orconf           /* ON CONFLICT policy to code trigger program with */
110593 ){
110594   Parse *pTop = sqlite3ParseToplevel(pParse);
110595   sqlite3 *db = pParse->db;   /* Database handle */
110596   TriggerPrg *pPrg;           /* Value to return */
110597   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
110598   Vdbe *v;                    /* Temporary VM */
110599   NameContext sNC;            /* Name context for sub-vdbe */
110600   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
110601   Parse *pSubParse;           /* Parse context for sub-vdbe */
110602   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
110603 
110604   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
110605   assert( pTop->pVdbe );
110606 
110607   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
110608   ** are freed if an error occurs, link them into the Parse.pTriggerPrg
110609   ** list of the top-level Parse object sooner rather than later.  */
110610   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
110611   if( !pPrg ) return 0;
110612   pPrg->pNext = pTop->pTriggerPrg;
110613   pTop->pTriggerPrg = pPrg;
110614   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
110615   if( !pProgram ) return 0;
110616   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
110617   pPrg->pTrigger = pTrigger;
110618   pPrg->orconf = orconf;
110619   pPrg->aColmask[0] = 0xffffffff;
110620   pPrg->aColmask[1] = 0xffffffff;
110621 
110622   /* Allocate and populate a new Parse context to use for coding the
110623   ** trigger sub-program.  */
110624   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
110625   if( !pSubParse ) return 0;
110626   memset(&sNC, 0, sizeof(sNC));
110627   sNC.pParse = pSubParse;
110628   pSubParse->db = db;
110629   pSubParse->pTriggerTab = pTab;
110630   pSubParse->pToplevel = pTop;
110631   pSubParse->zAuthContext = pTrigger->zName;
110632   pSubParse->eTriggerOp = pTrigger->op;
110633   pSubParse->nQueryLoop = pParse->nQueryLoop;
110634 
110635   v = sqlite3GetVdbe(pSubParse);
110636   if( v ){
110637     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
110638       pTrigger->zName, onErrorText(orconf),
110639       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
110640         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
110641         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
110642         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
110643       pTab->zName
110644     ));
110645 #ifndef SQLITE_OMIT_TRACE
110646     sqlite3VdbeChangeP4(v, -1,
110647       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
110648     );
110649 #endif
110650 
110651     /* If one was specified, code the WHEN clause. If it evaluates to false
110652     ** (or NULL) the sub-vdbe is immediately halted by jumping to the
110653     ** OP_Halt inserted at the end of the program.  */
110654     if( pTrigger->pWhen ){
110655       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
110656       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
110657        && db->mallocFailed==0
110658       ){
110659         iEndTrigger = sqlite3VdbeMakeLabel(v);
110660         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
110661       }
110662       sqlite3ExprDelete(db, pWhen);
110663     }
110664 
110665     /* Code the trigger program into the sub-vdbe. */
110666     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
110667 
110668     /* Insert an OP_Halt at the end of the sub-program. */
110669     if( iEndTrigger ){
110670       sqlite3VdbeResolveLabel(v, iEndTrigger);
110671     }
110672     sqlite3VdbeAddOp0(v, OP_Halt);
110673     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
110674 
110675     transferParseError(pParse, pSubParse);
110676     if( db->mallocFailed==0 ){
110677       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
110678     }
110679     pProgram->nMem = pSubParse->nMem;
110680     pProgram->nCsr = pSubParse->nTab;
110681     pProgram->nOnce = pSubParse->nOnce;
110682     pProgram->token = (void *)pTrigger;
110683     pPrg->aColmask[0] = pSubParse->oldmask;
110684     pPrg->aColmask[1] = pSubParse->newmask;
110685     sqlite3VdbeDelete(v);
110686   }
110687 
110688   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
110689   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
110690   sqlite3ParserReset(pSubParse);
110691   sqlite3StackFree(db, pSubParse);
110692 
110693   return pPrg;
110694 }
110695 
110696 /*
110697 ** Return a pointer to a TriggerPrg object containing the sub-program for
110698 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
110699 ** TriggerPrg object exists, a new object is allocated and populated before
110700 ** being returned.
110701 */
110702 static TriggerPrg *getRowTrigger(
110703   Parse *pParse,       /* Current parse context */
110704   Trigger *pTrigger,   /* Trigger to code */
110705   Table *pTab,         /* The table trigger pTrigger is attached to */
110706   int orconf           /* ON CONFLICT algorithm. */
110707 ){
110708   Parse *pRoot = sqlite3ParseToplevel(pParse);
110709   TriggerPrg *pPrg;
110710 
110711   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
110712 
110713   /* It may be that this trigger has already been coded (or is in the
110714   ** process of being coded). If this is the case, then an entry with
110715   ** a matching TriggerPrg.pTrigger field will be present somewhere
110716   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
110717   for(pPrg=pRoot->pTriggerPrg;
110718       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
110719       pPrg=pPrg->pNext
110720   );
110721 
110722   /* If an existing TriggerPrg could not be located, create a new one. */
110723   if( !pPrg ){
110724     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
110725   }
110726 
110727   return pPrg;
110728 }
110729 
110730 /*
110731 ** Generate code for the trigger program associated with trigger p on
110732 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
110733 ** function are the same as those described in the header function for
110734 ** sqlite3CodeRowTrigger()
110735 */
110736 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
110737   Parse *pParse,       /* Parse context */
110738   Trigger *p,          /* Trigger to code */
110739   Table *pTab,         /* The table to code triggers from */
110740   int reg,             /* Reg array containing OLD.* and NEW.* values */
110741   int orconf,          /* ON CONFLICT policy */
110742   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
110743 ){
110744   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
110745   TriggerPrg *pPrg;
110746   pPrg = getRowTrigger(pParse, p, pTab, orconf);
110747   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
110748 
110749   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
110750   ** is a pointer to the sub-vdbe containing the trigger program.  */
110751   if( pPrg ){
110752     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
110753 
110754     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
110755     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
110756     VdbeComment(
110757         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
110758 
110759     /* Set the P5 operand of the OP_Program instruction to non-zero if
110760     ** recursive invocation of this trigger program is disallowed. Recursive
110761     ** invocation is disallowed if (a) the sub-program is really a trigger,
110762     ** not a foreign key action, and (b) the flag to enable recursive triggers
110763     ** is clear.  */
110764     sqlite3VdbeChangeP5(v, (u8)bRecursive);
110765   }
110766 }
110767 
110768 /*
110769 ** This is called to code the required FOR EACH ROW triggers for an operation
110770 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
110771 ** is given by the op parameter. The tr_tm parameter determines whether the
110772 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
110773 ** parameter pChanges is passed the list of columns being modified.
110774 **
110775 ** If there are no triggers that fire at the specified time for the specified
110776 ** operation on pTab, this function is a no-op.
110777 **
110778 ** The reg argument is the address of the first in an array of registers
110779 ** that contain the values substituted for the new.* and old.* references
110780 ** in the trigger program. If N is the number of columns in table pTab
110781 ** (a copy of pTab->nCol), then registers are populated as follows:
110782 **
110783 **   Register       Contains
110784 **   ------------------------------------------------------
110785 **   reg+0          OLD.rowid
110786 **   reg+1          OLD.* value of left-most column of pTab
110787 **   ...            ...
110788 **   reg+N          OLD.* value of right-most column of pTab
110789 **   reg+N+1        NEW.rowid
110790 **   reg+N+2        OLD.* value of left-most column of pTab
110791 **   ...            ...
110792 **   reg+N+N+1      NEW.* value of right-most column of pTab
110793 **
110794 ** For ON DELETE triggers, the registers containing the NEW.* values will
110795 ** never be accessed by the trigger program, so they are not allocated or
110796 ** populated by the caller (there is no data to populate them with anyway).
110797 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
110798 ** are never accessed, and so are not allocated by the caller. So, for an
110799 ** ON INSERT trigger, the value passed to this function as parameter reg
110800 ** is not a readable register, although registers (reg+N) through
110801 ** (reg+N+N+1) are.
110802 **
110803 ** Parameter orconf is the default conflict resolution algorithm for the
110804 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
110805 ** is the instruction that control should jump to if a trigger program
110806 ** raises an IGNORE exception.
110807 */
110808 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
110809   Parse *pParse,       /* Parse context */
110810   Trigger *pTrigger,   /* List of triggers on table pTab */
110811   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
110812   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
110813   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
110814   Table *pTab,         /* The table to code triggers from */
110815   int reg,             /* The first in an array of registers (see above) */
110816   int orconf,          /* ON CONFLICT policy */
110817   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
110818 ){
110819   Trigger *p;          /* Used to iterate through pTrigger list */
110820 
110821   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
110822   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
110823   assert( (op==TK_UPDATE)==(pChanges!=0) );
110824 
110825   for(p=pTrigger; p; p=p->pNext){
110826 
110827     /* Sanity checking:  The schema for the trigger and for the table are
110828     ** always defined.  The trigger must be in the same schema as the table
110829     ** or else it must be a TEMP trigger. */
110830     assert( p->pSchema!=0 );
110831     assert( p->pTabSchema!=0 );
110832     assert( p->pSchema==p->pTabSchema
110833          || p->pSchema==pParse->db->aDb[1].pSchema );
110834 
110835     /* Determine whether we should code this trigger */
110836     if( p->op==op
110837      && p->tr_tm==tr_tm
110838      && checkColumnOverlap(p->pColumns, pChanges)
110839     ){
110840       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
110841     }
110842   }
110843 }
110844 
110845 /*
110846 ** Triggers may access values stored in the old.* or new.* pseudo-table.
110847 ** This function returns a 32-bit bitmask indicating which columns of the
110848 ** old.* or new.* tables actually are used by triggers. This information
110849 ** may be used by the caller, for example, to avoid having to load the entire
110850 ** old.* record into memory when executing an UPDATE or DELETE command.
110851 **
110852 ** Bit 0 of the returned mask is set if the left-most column of the
110853 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
110854 ** the second leftmost column value is required, and so on. If there
110855 ** are more than 32 columns in the table, and at least one of the columns
110856 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
110857 **
110858 ** It is not possible to determine if the old.rowid or new.rowid column is
110859 ** accessed by triggers. The caller must always assume that it is.
110860 **
110861 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
110862 ** applies to the old.* table. If 1, the new.* table.
110863 **
110864 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
110865 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
110866 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
110867 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
110868 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
110869 */
110870 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
110871   Parse *pParse,       /* Parse context */
110872   Trigger *pTrigger,   /* List of triggers on table pTab */
110873   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
110874   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
110875   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
110876   Table *pTab,         /* The table to code triggers from */
110877   int orconf           /* Default ON CONFLICT policy for trigger steps */
110878 ){
110879   const int op = pChanges ? TK_UPDATE : TK_DELETE;
110880   u32 mask = 0;
110881   Trigger *p;
110882 
110883   assert( isNew==1 || isNew==0 );
110884   for(p=pTrigger; p; p=p->pNext){
110885     if( p->op==op && (tr_tm&p->tr_tm)
110886      && checkColumnOverlap(p->pColumns,pChanges)
110887     ){
110888       TriggerPrg *pPrg;
110889       pPrg = getRowTrigger(pParse, p, pTab, orconf);
110890       if( pPrg ){
110891         mask |= pPrg->aColmask[isNew];
110892       }
110893     }
110894   }
110895 
110896   return mask;
110897 }
110898 
110899 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
110900 
110901 /************** End of trigger.c *********************************************/
110902 /************** Begin file update.c ******************************************/
110903 /*
110904 ** 2001 September 15
110905 **
110906 ** The author disclaims copyright to this source code.  In place of
110907 ** a legal notice, here is a blessing:
110908 **
110909 **    May you do good and not evil.
110910 **    May you find forgiveness for yourself and forgive others.
110911 **    May you share freely, never taking more than you give.
110912 **
110913 *************************************************************************
110914 ** This file contains C code routines that are called by the parser
110915 ** to handle UPDATE statements.
110916 */
110917 
110918 #ifndef SQLITE_OMIT_VIRTUALTABLE
110919 /* Forward declaration */
110920 static void updateVirtualTable(
110921   Parse *pParse,       /* The parsing context */
110922   SrcList *pSrc,       /* The virtual table to be modified */
110923   Table *pTab,         /* The virtual table */
110924   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
110925   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
110926   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
110927   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
110928   int onError          /* ON CONFLICT strategy */
110929 );
110930 #endif /* SQLITE_OMIT_VIRTUALTABLE */
110931 
110932 /*
110933 ** The most recently coded instruction was an OP_Column to retrieve the
110934 ** i-th column of table pTab. This routine sets the P4 parameter of the
110935 ** OP_Column to the default value, if any.
110936 **
110937 ** The default value of a column is specified by a DEFAULT clause in the
110938 ** column definition. This was either supplied by the user when the table
110939 ** was created, or added later to the table definition by an ALTER TABLE
110940 ** command. If the latter, then the row-records in the table btree on disk
110941 ** may not contain a value for the column and the default value, taken
110942 ** from the P4 parameter of the OP_Column instruction, is returned instead.
110943 ** If the former, then all row-records are guaranteed to include a value
110944 ** for the column and the P4 value is not required.
110945 **
110946 ** Column definitions created by an ALTER TABLE command may only have
110947 ** literal default values specified: a number, null or a string. (If a more
110948 ** complicated default expression value was provided, it is evaluated
110949 ** when the ALTER TABLE is executed and one of the literal values written
110950 ** into the sqlite_master table.)
110951 **
110952 ** Therefore, the P4 parameter is only required if the default value for
110953 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
110954 ** function is capable of transforming these types of expressions into
110955 ** sqlite3_value objects.
110956 **
110957 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
110958 ** on register iReg. This is used when an equivalent integer value is
110959 ** stored in place of an 8-byte floating point value in order to save
110960 ** space.
110961 */
110962 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
110963   assert( pTab!=0 );
110964   if( !pTab->pSelect ){
110965     sqlite3_value *pValue = 0;
110966     u8 enc = ENC(sqlite3VdbeDb(v));
110967     Column *pCol = &pTab->aCol[i];
110968     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
110969     assert( i<pTab->nCol );
110970     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
110971                          pCol->affinity, &pValue);
110972     if( pValue ){
110973       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
110974     }
110975 #ifndef SQLITE_OMIT_FLOATING_POINT
110976     if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
110977       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
110978     }
110979 #endif
110980   }
110981 }
110982 
110983 /*
110984 ** Process an UPDATE statement.
110985 **
110986 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
110987 **          \_______/ \________/     \______/       \________________/
110988 *            onError   pTabList      pChanges             pWhere
110989 */
110990 SQLITE_PRIVATE void sqlite3Update(
110991   Parse *pParse,         /* The parser context */
110992   SrcList *pTabList,     /* The table in which we should change things */
110993   ExprList *pChanges,    /* Things to be changed */
110994   Expr *pWhere,          /* The WHERE clause.  May be null */
110995   int onError            /* How to handle constraint errors */
110996 ){
110997   int i, j;              /* Loop counters */
110998   Table *pTab;           /* The table to be updated */
110999   int addrTop = 0;       /* VDBE instruction address of the start of the loop */
111000   WhereInfo *pWInfo;     /* Information about the WHERE clause */
111001   Vdbe *v;               /* The virtual database engine */
111002   Index *pIdx;           /* For looping over indices */
111003   Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */
111004   int nIdx;              /* Number of indices that need updating */
111005   int iBaseCur;          /* Base cursor number */
111006   int iDataCur;          /* Cursor for the canonical data btree */
111007   int iIdxCur;           /* Cursor for the first index */
111008   sqlite3 *db;           /* The database structure */
111009   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
111010   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
111011                          ** an expression for the i-th column of the table.
111012                          ** aXRef[i]==-1 if the i-th column is not changed. */
111013   u8 *aToOpen;           /* 1 for tables and indices to be opened */
111014   u8 chngPk;             /* PRIMARY KEY changed in a WITHOUT ROWID table */
111015   u8 chngRowid;          /* Rowid changed in a normal table */
111016   u8 chngKey;            /* Either chngPk or chngRowid */
111017   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
111018   AuthContext sContext;  /* The authorization context */
111019   NameContext sNC;       /* The name-context to resolve expressions in */
111020   int iDb;               /* Database containing the table being updated */
111021   int okOnePass;         /* True for one-pass algorithm without the FIFO */
111022   int hasFK;             /* True if foreign key processing is required */
111023   int labelBreak;        /* Jump here to break out of UPDATE loop */
111024   int labelContinue;     /* Jump here to continue next step of UPDATE loop */
111025 
111026 #ifndef SQLITE_OMIT_TRIGGER
111027   int isView;            /* True when updating a view (INSTEAD OF trigger) */
111028   Trigger *pTrigger;     /* List of triggers on pTab, if required */
111029   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
111030 #endif
111031   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
111032   int iEph = 0;          /* Ephemeral table holding all primary key values */
111033   int nKey = 0;          /* Number of elements in regKey for WITHOUT ROWID */
111034   int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
111035 
111036   /* Register Allocations */
111037   int regRowCount = 0;   /* A count of rows changed */
111038   int regOldRowid;       /* The old rowid */
111039   int regNewRowid;       /* The new rowid */
111040   int regNew;            /* Content of the NEW.* table in triggers */
111041   int regOld = 0;        /* Content of OLD.* table in triggers */
111042   int regRowSet = 0;     /* Rowset of rows to be updated */
111043   int regKey = 0;        /* composite PRIMARY KEY value */
111044 
111045   memset(&sContext, 0, sizeof(sContext));
111046   db = pParse->db;
111047   if( pParse->nErr || db->mallocFailed ){
111048     goto update_cleanup;
111049   }
111050   assert( pTabList->nSrc==1 );
111051 
111052   /* Locate the table which we want to update.
111053   */
111054   pTab = sqlite3SrcListLookup(pParse, pTabList);
111055   if( pTab==0 ) goto update_cleanup;
111056   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
111057 
111058   /* Figure out if we have any triggers and if the table being
111059   ** updated is a view.
111060   */
111061 #ifndef SQLITE_OMIT_TRIGGER
111062   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
111063   isView = pTab->pSelect!=0;
111064   assert( pTrigger || tmask==0 );
111065 #else
111066 # define pTrigger 0
111067 # define isView 0
111068 # define tmask 0
111069 #endif
111070 #ifdef SQLITE_OMIT_VIEW
111071 # undef isView
111072 # define isView 0
111073 #endif
111074 
111075   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
111076     goto update_cleanup;
111077   }
111078   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
111079     goto update_cleanup;
111080   }
111081 
111082   /* Allocate a cursors for the main database table and for all indices.
111083   ** The index cursors might not be used, but if they are used they
111084   ** need to occur right after the database cursor.  So go ahead and
111085   ** allocate enough space, just in case.
111086   */
111087   pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
111088   iIdxCur = iDataCur+1;
111089   pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
111090   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
111091     if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
111092       iDataCur = pParse->nTab;
111093       pTabList->a[0].iCursor = iDataCur;
111094     }
111095     pParse->nTab++;
111096   }
111097 
111098   /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
111099   ** Initialize aXRef[] and aToOpen[] to their default values.
111100   */
111101   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
111102   if( aXRef==0 ) goto update_cleanup;
111103   aRegIdx = aXRef+pTab->nCol;
111104   aToOpen = (u8*)(aRegIdx+nIdx);
111105   memset(aToOpen, 1, nIdx+1);
111106   aToOpen[nIdx+1] = 0;
111107   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
111108 
111109   /* Initialize the name-context */
111110   memset(&sNC, 0, sizeof(sNC));
111111   sNC.pParse = pParse;
111112   sNC.pSrcList = pTabList;
111113 
111114   /* Resolve the column names in all the expressions of the
111115   ** of the UPDATE statement.  Also find the column index
111116   ** for each column to be updated in the pChanges array.  For each
111117   ** column to be updated, make sure we have authorization to change
111118   ** that column.
111119   */
111120   chngRowid = chngPk = 0;
111121   for(i=0; i<pChanges->nExpr; i++){
111122     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
111123       goto update_cleanup;
111124     }
111125     for(j=0; j<pTab->nCol; j++){
111126       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
111127         if( j==pTab->iPKey ){
111128           chngRowid = 1;
111129           pRowidExpr = pChanges->a[i].pExpr;
111130         }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
111131           chngPk = 1;
111132         }
111133         aXRef[j] = i;
111134         break;
111135       }
111136     }
111137     if( j>=pTab->nCol ){
111138       if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
111139         j = -1;
111140         chngRowid = 1;
111141         pRowidExpr = pChanges->a[i].pExpr;
111142       }else{
111143         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
111144         pParse->checkSchema = 1;
111145         goto update_cleanup;
111146       }
111147     }
111148 #ifndef SQLITE_OMIT_AUTHORIZATION
111149     {
111150       int rc;
111151       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
111152                             j<0 ? "ROWID" : pTab->aCol[j].zName,
111153                             db->aDb[iDb].zName);
111154       if( rc==SQLITE_DENY ){
111155         goto update_cleanup;
111156       }else if( rc==SQLITE_IGNORE ){
111157         aXRef[j] = -1;
111158       }
111159     }
111160 #endif
111161   }
111162   assert( (chngRowid & chngPk)==0 );
111163   assert( chngRowid==0 || chngRowid==1 );
111164   assert( chngPk==0 || chngPk==1 );
111165   chngKey = chngRowid + chngPk;
111166 
111167   /* The SET expressions are not actually used inside the WHERE loop.
111168   ** So reset the colUsed mask
111169   */
111170   pTabList->a[0].colUsed = 0;
111171 
111172   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
111173 
111174   /* There is one entry in the aRegIdx[] array for each index on the table
111175   ** being updated.  Fill in aRegIdx[] with a register number that will hold
111176   ** the key for accessing each index.
111177   */
111178   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
111179     int reg;
111180     if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
111181       reg = ++pParse->nMem;
111182     }else{
111183       reg = 0;
111184       for(i=0; i<pIdx->nKeyCol; i++){
111185         if( aXRef[pIdx->aiColumn[i]]>=0 ){
111186           reg = ++pParse->nMem;
111187           break;
111188         }
111189       }
111190     }
111191     if( reg==0 ) aToOpen[j+1] = 0;
111192     aRegIdx[j] = reg;
111193   }
111194 
111195   /* Begin generating code. */
111196   v = sqlite3GetVdbe(pParse);
111197   if( v==0 ) goto update_cleanup;
111198   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
111199   sqlite3BeginWriteOperation(pParse, 1, iDb);
111200 
111201 #ifndef SQLITE_OMIT_VIRTUALTABLE
111202   /* Virtual tables must be handled separately */
111203   if( IsVirtual(pTab) ){
111204     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
111205                        pWhere, onError);
111206     pWhere = 0;
111207     pTabList = 0;
111208     goto update_cleanup;
111209   }
111210 #endif
111211 
111212   /* Allocate required registers. */
111213   regRowSet = ++pParse->nMem;
111214   regOldRowid = regNewRowid = ++pParse->nMem;
111215   if( chngPk || pTrigger || hasFK ){
111216     regOld = pParse->nMem + 1;
111217     pParse->nMem += pTab->nCol;
111218   }
111219   if( chngKey || pTrigger || hasFK ){
111220     regNewRowid = ++pParse->nMem;
111221   }
111222   regNew = pParse->nMem + 1;
111223   pParse->nMem += pTab->nCol;
111224 
111225   /* Start the view context. */
111226   if( isView ){
111227     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
111228   }
111229 
111230   /* If we are trying to update a view, realize that view into
111231   ** an ephemeral table.
111232   */
111233 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
111234   if( isView ){
111235     sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
111236   }
111237 #endif
111238 
111239   /* Resolve the column names in all the expressions in the
111240   ** WHERE clause.
111241   */
111242   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
111243     goto update_cleanup;
111244   }
111245 
111246   /* Begin the database scan
111247   */
111248   if( HasRowid(pTab) ){
111249     sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
111250     pWInfo = sqlite3WhereBegin(
111251         pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur
111252     );
111253     if( pWInfo==0 ) goto update_cleanup;
111254     okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
111255 
111256     /* Remember the rowid of every item to be updated.
111257     */
111258     sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
111259     if( !okOnePass ){
111260       sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
111261     }
111262 
111263     /* End the database scan loop.
111264     */
111265     sqlite3WhereEnd(pWInfo);
111266   }else{
111267     int iPk;         /* First of nPk memory cells holding PRIMARY KEY value */
111268     i16 nPk;         /* Number of components of the PRIMARY KEY */
111269     int addrOpen;    /* Address of the OpenEphemeral instruction */
111270 
111271     assert( pPk!=0 );
111272     nPk = pPk->nKeyCol;
111273     iPk = pParse->nMem+1;
111274     pParse->nMem += nPk;
111275     regKey = ++pParse->nMem;
111276     iEph = pParse->nTab++;
111277     sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
111278     addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
111279     sqlite3VdbeSetP4KeyInfo(pParse, pPk);
111280     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
111281                                WHERE_ONEPASS_DESIRED, iIdxCur);
111282     if( pWInfo==0 ) goto update_cleanup;
111283     okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
111284     for(i=0; i<nPk; i++){
111285       sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
111286                                       iPk+i);
111287     }
111288     if( okOnePass ){
111289       sqlite3VdbeChangeToNoop(v, addrOpen);
111290       nKey = nPk;
111291       regKey = iPk;
111292     }else{
111293       sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
111294                         sqlite3IndexAffinityStr(v, pPk), nPk);
111295       sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
111296     }
111297     sqlite3WhereEnd(pWInfo);
111298   }
111299 
111300   /* Initialize the count of updated rows
111301   */
111302   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
111303     regRowCount = ++pParse->nMem;
111304     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
111305   }
111306 
111307   labelBreak = sqlite3VdbeMakeLabel(v);
111308   if( !isView ){
111309     /*
111310     ** Open every index that needs updating.  Note that if any
111311     ** index could potentially invoke a REPLACE conflict resolution
111312     ** action, then we need to open all indices because we might need
111313     ** to be deleting some records.
111314     */
111315     if( onError==OE_Replace ){
111316       memset(aToOpen, 1, nIdx+1);
111317     }else{
111318       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
111319         if( pIdx->onError==OE_Replace ){
111320           memset(aToOpen, 1, nIdx+1);
111321           break;
111322         }
111323       }
111324     }
111325     if( okOnePass ){
111326       if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
111327       if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
111328     }
111329     sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iBaseCur, aToOpen,
111330                                0, 0);
111331   }
111332 
111333   /* Top of the update loop */
111334   if( okOnePass ){
111335     if( aToOpen[iDataCur-iBaseCur] && !isView ){
111336       assert( pPk );
111337       sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
111338       VdbeCoverageNeverTaken(v);
111339     }
111340     labelContinue = labelBreak;
111341     sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
111342     VdbeCoverageIf(v, pPk==0);
111343     VdbeCoverageIf(v, pPk!=0);
111344   }else if( pPk ){
111345     labelContinue = sqlite3VdbeMakeLabel(v);
111346     sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
111347     addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
111348     sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
111349     VdbeCoverage(v);
111350   }else{
111351     labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
111352                              regOldRowid);
111353     VdbeCoverage(v);
111354     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
111355     VdbeCoverage(v);
111356   }
111357 
111358   /* If the record number will change, set register regNewRowid to
111359   ** contain the new value. If the record number is not being modified,
111360   ** then regNewRowid is the same register as regOldRowid, which is
111361   ** already populated.  */
111362   assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
111363   if( chngRowid ){
111364     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
111365     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
111366   }
111367 
111368   /* Compute the old pre-UPDATE content of the row being changed, if that
111369   ** information is needed */
111370   if( chngPk || hasFK || pTrigger ){
111371     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
111372     oldmask |= sqlite3TriggerColmask(pParse,
111373         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
111374     );
111375     for(i=0; i<pTab->nCol; i++){
111376       if( oldmask==0xffffffff
111377        || (i<32 && (oldmask & MASKBIT32(i))!=0)
111378        || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
111379       ){
111380         testcase(  oldmask!=0xffffffff && i==31 );
111381         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
111382       }else{
111383         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
111384       }
111385     }
111386     if( chngRowid==0 && pPk==0 ){
111387       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
111388     }
111389   }
111390 
111391   /* Populate the array of registers beginning at regNew with the new
111392   ** row data. This array is used to check constants, create the new
111393   ** table and index records, and as the values for any new.* references
111394   ** made by triggers.
111395   **
111396   ** If there are one or more BEFORE triggers, then do not populate the
111397   ** registers associated with columns that are (a) not modified by
111398   ** this UPDATE statement and (b) not accessed by new.* references. The
111399   ** values for registers not modified by the UPDATE must be reloaded from
111400   ** the database after the BEFORE triggers are fired anyway (as the trigger
111401   ** may have modified them). So not loading those that are not going to
111402   ** be used eliminates some redundant opcodes.
111403   */
111404   newmask = sqlite3TriggerColmask(
111405       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
111406   );
111407   /*sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);*/
111408   for(i=0; i<pTab->nCol; i++){
111409     if( i==pTab->iPKey ){
111410       sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
111411     }else{
111412       j = aXRef[i];
111413       if( j>=0 ){
111414         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
111415       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
111416         /* This branch loads the value of a column that will not be changed
111417         ** into a register. This is done if there are no BEFORE triggers, or
111418         ** if there are one or more BEFORE triggers that use this value via
111419         ** a new.* reference in a trigger program.
111420         */
111421         testcase( i==31 );
111422         testcase( i==32 );
111423         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
111424       }else{
111425         sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
111426       }
111427     }
111428   }
111429 
111430   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
111431   ** verified. One could argue that this is wrong.
111432   */
111433   if( tmask&TRIGGER_BEFORE ){
111434     sqlite3TableAffinity(v, pTab, regNew);
111435     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
111436         TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
111437 
111438     /* The row-trigger may have deleted the row being updated. In this
111439     ** case, jump to the next row. No updates or AFTER triggers are
111440     ** required. This behavior - what happens when the row being updated
111441     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
111442     ** documentation.
111443     */
111444     if( pPk ){
111445       sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
111446       VdbeCoverage(v);
111447     }else{
111448       sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
111449       VdbeCoverage(v);
111450     }
111451 
111452     /* If it did not delete it, the row-trigger may still have modified
111453     ** some of the columns of the row being updated. Load the values for
111454     ** all columns not modified by the update statement into their
111455     ** registers in case this has happened.
111456     */
111457     for(i=0; i<pTab->nCol; i++){
111458       if( aXRef[i]<0 && i!=pTab->iPKey ){
111459         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
111460       }
111461     }
111462   }
111463 
111464   if( !isView ){
111465     int j1 = 0;           /* Address of jump instruction */
111466     int bReplace = 0;     /* True if REPLACE conflict resolution might happen */
111467 
111468     /* Do constraint checks. */
111469     assert( regOldRowid>0 );
111470     sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
111471         regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace);
111472 
111473     /* Do FK constraint checks. */
111474     if( hasFK ){
111475       sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
111476     }
111477 
111478     /* Delete the index entries associated with the current record.  */
111479     if( bReplace || chngKey ){
111480       if( pPk ){
111481         j1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
111482       }else{
111483         j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
111484       }
111485       VdbeCoverageNeverTaken(v);
111486     }
111487     sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx);
111488 
111489     /* If changing the record number, delete the old record.  */
111490     if( hasFK || chngKey || pPk!=0 ){
111491       sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
111492     }
111493     if( bReplace || chngKey ){
111494       sqlite3VdbeJumpHere(v, j1);
111495     }
111496 
111497     if( hasFK ){
111498       sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
111499     }
111500 
111501     /* Insert the new index entries and the new record. */
111502     sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
111503                              regNewRowid, aRegIdx, 1, 0, 0);
111504 
111505     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
111506     ** handle rows (possibly in other tables) that refer via a foreign key
111507     ** to the row just updated. */
111508     if( hasFK ){
111509       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
111510     }
111511   }
111512 
111513   /* Increment the row counter
111514   */
111515   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
111516     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
111517   }
111518 
111519   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
111520       TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
111521 
111522   /* Repeat the above with the next record to be updated, until
111523   ** all record selected by the WHERE clause have been updated.
111524   */
111525   if( okOnePass ){
111526     /* Nothing to do at end-of-loop for a single-pass */
111527   }else if( pPk ){
111528     sqlite3VdbeResolveLabel(v, labelContinue);
111529     sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
111530   }else{
111531     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelContinue);
111532   }
111533   sqlite3VdbeResolveLabel(v, labelBreak);
111534 
111535   /* Close all tables */
111536   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
111537     assert( aRegIdx );
111538     if( aToOpen[i+1] ){
111539       sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
111540     }
111541   }
111542   if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
111543 
111544   /* Update the sqlite_sequence table by storing the content of the
111545   ** maximum rowid counter values recorded while inserting into
111546   ** autoincrement tables.
111547   */
111548   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
111549     sqlite3AutoincrementEnd(pParse);
111550   }
111551 
111552   /*
111553   ** Return the number of rows that were changed. If this routine is
111554   ** generating code because of a call to sqlite3NestedParse(), do not
111555   ** invoke the callback function.
111556   */
111557   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
111558     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
111559     sqlite3VdbeSetNumCols(v, 1);
111560     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
111561   }
111562 
111563 update_cleanup:
111564   sqlite3AuthContextPop(&sContext);
111565   sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
111566   sqlite3SrcListDelete(db, pTabList);
111567   sqlite3ExprListDelete(db, pChanges);
111568   sqlite3ExprDelete(db, pWhere);
111569   return;
111570 }
111571 /* Make sure "isView" and other macros defined above are undefined. Otherwise
111572 ** they may interfere with compilation of other functions in this file
111573 ** (or in another file, if this file becomes part of the amalgamation).  */
111574 #ifdef isView
111575  #undef isView
111576 #endif
111577 #ifdef pTrigger
111578  #undef pTrigger
111579 #endif
111580 
111581 #ifndef SQLITE_OMIT_VIRTUALTABLE
111582 /*
111583 ** Generate code for an UPDATE of a virtual table.
111584 **
111585 ** The strategy is that we create an ephemeral table that contains
111586 ** for each row to be changed:
111587 **
111588 **   (A)  The original rowid of that row.
111589 **   (B)  The revised rowid for the row. (note1)
111590 **   (C)  The content of every column in the row.
111591 **
111592 ** Then we loop over this ephemeral table and for each row in
111593 ** the ephemeral table call VUpdate.
111594 **
111595 ** When finished, drop the ephemeral table.
111596 **
111597 ** (note1) Actually, if we know in advance that (A) is always the same
111598 ** as (B) we only store (A), then duplicate (A) when pulling
111599 ** it out of the ephemeral table before calling VUpdate.
111600 */
111601 static void updateVirtualTable(
111602   Parse *pParse,       /* The parsing context */
111603   SrcList *pSrc,       /* The virtual table to be modified */
111604   Table *pTab,         /* The virtual table */
111605   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
111606   Expr *pRowid,        /* Expression used to recompute the rowid */
111607   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
111608   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
111609   int onError          /* ON CONFLICT strategy */
111610 ){
111611   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
111612   ExprList *pEList = 0;     /* The result set of the SELECT statement */
111613   Select *pSelect = 0;      /* The SELECT statement */
111614   Expr *pExpr;              /* Temporary expression */
111615   int ephemTab;             /* Table holding the result of the SELECT */
111616   int i;                    /* Loop counter */
111617   int addr;                 /* Address of top of loop */
111618   int iReg;                 /* First register in set passed to OP_VUpdate */
111619   sqlite3 *db = pParse->db; /* Database connection */
111620   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
111621   SelectDest dest;
111622 
111623   /* Construct the SELECT statement that will find the new values for
111624   ** all updated rows.
111625   */
111626   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
111627   if( pRowid ){
111628     pEList = sqlite3ExprListAppend(pParse, pEList,
111629                                    sqlite3ExprDup(db, pRowid, 0));
111630   }
111631   assert( pTab->iPKey<0 );
111632   for(i=0; i<pTab->nCol; i++){
111633     if( aXRef[i]>=0 ){
111634       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
111635     }else{
111636       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
111637     }
111638     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
111639   }
111640   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
111641 
111642   /* Create the ephemeral table into which the update results will
111643   ** be stored.
111644   */
111645   assert( v );
111646   ephemTab = pParse->nTab++;
111647   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
111648   sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
111649 
111650   /* fill the ephemeral table
111651   */
111652   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
111653   sqlite3Select(pParse, pSelect, &dest);
111654 
111655   /* Generate code to scan the ephemeral table and call VUpdate. */
111656   iReg = ++pParse->nMem;
111657   pParse->nMem += pTab->nCol+1;
111658   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0); VdbeCoverage(v);
111659   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
111660   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
111661   for(i=0; i<pTab->nCol; i++){
111662     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
111663   }
111664   sqlite3VtabMakeWritable(pParse, pTab);
111665   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
111666   sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
111667   sqlite3MayAbort(pParse);
111668   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
111669   sqlite3VdbeJumpHere(v, addr);
111670   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
111671 
111672   /* Cleanup */
111673   sqlite3SelectDelete(db, pSelect);
111674 }
111675 #endif /* SQLITE_OMIT_VIRTUALTABLE */
111676 
111677 /************** End of update.c **********************************************/
111678 /************** Begin file vacuum.c ******************************************/
111679 /*
111680 ** 2003 April 6
111681 **
111682 ** The author disclaims copyright to this source code.  In place of
111683 ** a legal notice, here is a blessing:
111684 **
111685 **    May you do good and not evil.
111686 **    May you find forgiveness for yourself and forgive others.
111687 **    May you share freely, never taking more than you give.
111688 **
111689 *************************************************************************
111690 ** This file contains code used to implement the VACUUM command.
111691 **
111692 ** Most of the code in this file may be omitted by defining the
111693 ** SQLITE_OMIT_VACUUM macro.
111694 */
111695 
111696 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
111697 /*
111698 ** Finalize a prepared statement.  If there was an error, store the
111699 ** text of the error message in *pzErrMsg.  Return the result code.
111700 */
111701 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
111702   int rc;
111703   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
111704   if( rc ){
111705     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
111706   }
111707   return rc;
111708 }
111709 
111710 /*
111711 ** Execute zSql on database db. Return an error code.
111712 */
111713 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
111714   sqlite3_stmt *pStmt;
111715   VVA_ONLY( int rc; )
111716   if( !zSql ){
111717     return SQLITE_NOMEM;
111718   }
111719   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
111720     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
111721     return sqlite3_errcode(db);
111722   }
111723   VVA_ONLY( rc = ) sqlite3_step(pStmt);
111724   assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
111725   return vacuumFinalize(db, pStmt, pzErrMsg);
111726 }
111727 
111728 /*
111729 ** Execute zSql on database db. The statement returns exactly
111730 ** one column. Execute this as SQL on the same database.
111731 */
111732 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
111733   sqlite3_stmt *pStmt;
111734   int rc;
111735 
111736   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
111737   if( rc!=SQLITE_OK ) return rc;
111738 
111739   while( SQLITE_ROW==sqlite3_step(pStmt) ){
111740     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
111741     if( rc!=SQLITE_OK ){
111742       vacuumFinalize(db, pStmt, pzErrMsg);
111743       return rc;
111744     }
111745   }
111746 
111747   return vacuumFinalize(db, pStmt, pzErrMsg);
111748 }
111749 
111750 /*
111751 ** The VACUUM command is used to clean up the database,
111752 ** collapse free space, etc.  It is modelled after the VACUUM command
111753 ** in PostgreSQL.  The VACUUM command works as follows:
111754 **
111755 **   (1)  Create a new transient database file
111756 **   (2)  Copy all content from the database being vacuumed into
111757 **        the new transient database file
111758 **   (3)  Copy content from the transient database back into the
111759 **        original database.
111760 **
111761 ** The transient database requires temporary disk space approximately
111762 ** equal to the size of the original database.  The copy operation of
111763 ** step (3) requires additional temporary disk space approximately equal
111764 ** to the size of the original database for the rollback journal.
111765 ** Hence, temporary disk space that is approximately 2x the size of the
111766 ** original database is required.  Every page of the database is written
111767 ** approximately 3 times:  Once for step (2) and twice for step (3).
111768 ** Two writes per page are required in step (3) because the original
111769 ** database content must be written into the rollback journal prior to
111770 ** overwriting the database with the vacuumed content.
111771 **
111772 ** Only 1x temporary space and only 1x writes would be required if
111773 ** the copy of step (3) were replace by deleting the original database
111774 ** and renaming the transient database as the original.  But that will
111775 ** not work if other processes are attached to the original database.
111776 ** And a power loss in between deleting the original and renaming the
111777 ** transient would cause the database file to appear to be deleted
111778 ** following reboot.
111779 */
111780 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
111781   Vdbe *v = sqlite3GetVdbe(pParse);
111782   if( v ){
111783     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
111784     sqlite3VdbeUsesBtree(v, 0);
111785   }
111786   return;
111787 }
111788 
111789 /*
111790 ** This routine implements the OP_Vacuum opcode of the VDBE.
111791 */
111792 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
111793   int rc = SQLITE_OK;     /* Return code from service routines */
111794   Btree *pMain;           /* The database being vacuumed */
111795   Btree *pTemp;           /* The temporary database we vacuum into */
111796   char *zSql = 0;         /* SQL statements */
111797   int saved_flags;        /* Saved value of the db->flags */
111798   int saved_nChange;      /* Saved value of db->nChange */
111799   int saved_nTotalChange; /* Saved value of db->nTotalChange */
111800   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
111801   Db *pDb = 0;            /* Database to detach at end of vacuum */
111802   int isMemDb;            /* True if vacuuming a :memory: database */
111803   int nRes;               /* Bytes of reserved space at the end of each page */
111804   int nDb;                /* Number of attached databases */
111805 
111806   if( !db->autoCommit ){
111807     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
111808     return SQLITE_ERROR;
111809   }
111810   if( db->nVdbeActive>1 ){
111811     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
111812     return SQLITE_ERROR;
111813   }
111814 
111815   /* Save the current value of the database flags so that it can be
111816   ** restored before returning. Then set the writable-schema flag, and
111817   ** disable CHECK and foreign key constraints.  */
111818   saved_flags = db->flags;
111819   saved_nChange = db->nChange;
111820   saved_nTotalChange = db->nTotalChange;
111821   saved_xTrace = db->xTrace;
111822   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
111823   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
111824   db->xTrace = 0;
111825 
111826   pMain = db->aDb[0].pBt;
111827   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
111828 
111829   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
111830   ** can be set to 'off' for this file, as it is not recovered if a crash
111831   ** occurs anyway. The integrity of the database is maintained by a
111832   ** (possibly synchronous) transaction opened on the main database before
111833   ** sqlite3BtreeCopyFile() is called.
111834   **
111835   ** An optimisation would be to use a non-journaled pager.
111836   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
111837   ** that actually made the VACUUM run slower.  Very little journalling
111838   ** actually occurs when doing a vacuum since the vacuum_db is initially
111839   ** empty.  Only the journal header is written.  Apparently it takes more
111840   ** time to parse and run the PRAGMA to turn journalling off than it does
111841   ** to write the journal header file.
111842   */
111843   nDb = db->nDb;
111844   if( sqlite3TempInMemory(db) ){
111845     zSql = "ATTACH ':memory:' AS vacuum_db;";
111846   }else{
111847     zSql = "ATTACH '' AS vacuum_db;";
111848   }
111849   rc = execSql(db, pzErrMsg, zSql);
111850   if( db->nDb>nDb ){
111851     pDb = &db->aDb[db->nDb-1];
111852     assert( strcmp(pDb->zName,"vacuum_db")==0 );
111853   }
111854   if( rc!=SQLITE_OK ) goto end_of_vacuum;
111855   pTemp = db->aDb[db->nDb-1].pBt;
111856 
111857   /* The call to execSql() to attach the temp database has left the file
111858   ** locked (as there was more than one active statement when the transaction
111859   ** to read the schema was concluded. Unlock it here so that this doesn't
111860   ** cause problems for the call to BtreeSetPageSize() below.  */
111861   sqlite3BtreeCommit(pTemp);
111862 
111863   nRes = sqlite3BtreeGetReserve(pMain);
111864 
111865   /* A VACUUM cannot change the pagesize of an encrypted database. */
111866 #ifdef SQLITE_HAS_CODEC
111867   if( db->nextPagesize ){
111868     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
111869     int nKey;
111870     char *zKey;
111871     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
111872     if( nKey ) db->nextPagesize = 0;
111873   }
111874 #endif
111875 
111876   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
111877   if( rc!=SQLITE_OK ) goto end_of_vacuum;
111878 
111879   /* Begin a transaction and take an exclusive lock on the main database
111880   ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
111881   ** to ensure that we do not try to change the page-size on a WAL database.
111882   */
111883   rc = execSql(db, pzErrMsg, "BEGIN;");
111884   if( rc!=SQLITE_OK ) goto end_of_vacuum;
111885   rc = sqlite3BtreeBeginTrans(pMain, 2);
111886   if( rc!=SQLITE_OK ) goto end_of_vacuum;
111887 
111888   /* Do not attempt to change the page size for a WAL database */
111889   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
111890                                                ==PAGER_JOURNALMODE_WAL ){
111891     db->nextPagesize = 0;
111892   }
111893 
111894   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
111895    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
111896    || NEVER(db->mallocFailed)
111897   ){
111898     rc = SQLITE_NOMEM;
111899     goto end_of_vacuum;
111900   }
111901 
111902 #ifndef SQLITE_OMIT_AUTOVACUUM
111903   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
111904                                            sqlite3BtreeGetAutoVacuum(pMain));
111905 #endif
111906 
111907   /* Query the schema of the main database. Create a mirror schema
111908   ** in the temporary database.
111909   */
111910   rc = execExecSql(db, pzErrMsg,
111911       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
111912       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
111913       "   AND coalesce(rootpage,1)>0"
111914   );
111915   if( rc!=SQLITE_OK ) goto end_of_vacuum;
111916   rc = execExecSql(db, pzErrMsg,
111917       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
111918       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
111919   if( rc!=SQLITE_OK ) goto end_of_vacuum;
111920   rc = execExecSql(db, pzErrMsg,
111921       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
111922       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
111923   if( rc!=SQLITE_OK ) goto end_of_vacuum;
111924 
111925   /* Loop through the tables in the main database. For each, do
111926   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
111927   ** the contents to the temporary database.
111928   */
111929   rc = execExecSql(db, pzErrMsg,
111930       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
111931       "|| ' SELECT * FROM main.' || quote(name) || ';'"
111932       "FROM main.sqlite_master "
111933       "WHERE type = 'table' AND name!='sqlite_sequence' "
111934       "  AND coalesce(rootpage,1)>0"
111935   );
111936   if( rc!=SQLITE_OK ) goto end_of_vacuum;
111937 
111938   /* Copy over the sequence table
111939   */
111940   rc = execExecSql(db, pzErrMsg,
111941       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
111942       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
111943   );
111944   if( rc!=SQLITE_OK ) goto end_of_vacuum;
111945   rc = execExecSql(db, pzErrMsg,
111946       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
111947       "|| ' SELECT * FROM main.' || quote(name) || ';' "
111948       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
111949   );
111950   if( rc!=SQLITE_OK ) goto end_of_vacuum;
111951 
111952 
111953   /* Copy the triggers, views, and virtual tables from the main database
111954   ** over to the temporary database.  None of these objects has any
111955   ** associated storage, so all we have to do is copy their entries
111956   ** from the SQLITE_MASTER table.
111957   */
111958   rc = execSql(db, pzErrMsg,
111959       "INSERT INTO vacuum_db.sqlite_master "
111960       "  SELECT type, name, tbl_name, rootpage, sql"
111961       "    FROM main.sqlite_master"
111962       "   WHERE type='view' OR type='trigger'"
111963       "      OR (type='table' AND rootpage=0)"
111964   );
111965   if( rc ) goto end_of_vacuum;
111966 
111967   /* At this point, there is a write transaction open on both the
111968   ** vacuum database and the main database. Assuming no error occurs,
111969   ** both transactions are closed by this block - the main database
111970   ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
111971   ** call to sqlite3BtreeCommit().
111972   */
111973   {
111974     u32 meta;
111975     int i;
111976 
111977     /* This array determines which meta meta values are preserved in the
111978     ** vacuum.  Even entries are the meta value number and odd entries
111979     ** are an increment to apply to the meta value after the vacuum.
111980     ** The increment is used to increase the schema cookie so that other
111981     ** connections to the same database will know to reread the schema.
111982     */
111983     static const unsigned char aCopy[] = {
111984        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
111985        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
111986        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
111987        BTREE_USER_VERSION,       0,  /* Preserve the user version */
111988        BTREE_APPLICATION_ID,     0,  /* Preserve the application id */
111989     };
111990 
111991     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
111992     assert( 1==sqlite3BtreeIsInTrans(pMain) );
111993 
111994     /* Copy Btree meta values */
111995     for(i=0; i<ArraySize(aCopy); i+=2){
111996       /* GetMeta() and UpdateMeta() cannot fail in this context because
111997       ** we already have page 1 loaded into cache and marked dirty. */
111998       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
111999       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
112000       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
112001     }
112002 
112003     rc = sqlite3BtreeCopyFile(pMain, pTemp);
112004     if( rc!=SQLITE_OK ) goto end_of_vacuum;
112005     rc = sqlite3BtreeCommit(pTemp);
112006     if( rc!=SQLITE_OK ) goto end_of_vacuum;
112007 #ifndef SQLITE_OMIT_AUTOVACUUM
112008     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
112009 #endif
112010   }
112011 
112012   assert( rc==SQLITE_OK );
112013   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
112014 
112015 end_of_vacuum:
112016   /* Restore the original value of db->flags */
112017   db->flags = saved_flags;
112018   db->nChange = saved_nChange;
112019   db->nTotalChange = saved_nTotalChange;
112020   db->xTrace = saved_xTrace;
112021   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
112022 
112023   /* Currently there is an SQL level transaction open on the vacuum
112024   ** database. No locks are held on any other files (since the main file
112025   ** was committed at the btree level). So it safe to end the transaction
112026   ** by manually setting the autoCommit flag to true and detaching the
112027   ** vacuum database. The vacuum_db journal file is deleted when the pager
112028   ** is closed by the DETACH.
112029   */
112030   db->autoCommit = 1;
112031 
112032   if( pDb ){
112033     sqlite3BtreeClose(pDb->pBt);
112034     pDb->pBt = 0;
112035     pDb->pSchema = 0;
112036   }
112037 
112038   /* This both clears the schemas and reduces the size of the db->aDb[]
112039   ** array. */
112040   sqlite3ResetAllSchemasOfConnection(db);
112041 
112042   return rc;
112043 }
112044 
112045 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
112046 
112047 /************** End of vacuum.c **********************************************/
112048 /************** Begin file vtab.c ********************************************/
112049 /*
112050 ** 2006 June 10
112051 **
112052 ** The author disclaims copyright to this source code.  In place of
112053 ** a legal notice, here is a blessing:
112054 **
112055 **    May you do good and not evil.
112056 **    May you find forgiveness for yourself and forgive others.
112057 **    May you share freely, never taking more than you give.
112058 **
112059 *************************************************************************
112060 ** This file contains code used to help implement virtual tables.
112061 */
112062 #ifndef SQLITE_OMIT_VIRTUALTABLE
112063 
112064 /*
112065 ** Before a virtual table xCreate() or xConnect() method is invoked, the
112066 ** sqlite3.pVtabCtx member variable is set to point to an instance of
112067 ** this struct allocated on the stack. It is used by the implementation of
112068 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
112069 ** are invoked only from within xCreate and xConnect methods.
112070 */
112071 struct VtabCtx {
112072   VTable *pVTable;    /* The virtual table being constructed */
112073   Table *pTab;        /* The Table object to which the virtual table belongs */
112074 };
112075 
112076 /*
112077 ** The actual function that does the work of creating a new module.
112078 ** This function implements the sqlite3_create_module() and
112079 ** sqlite3_create_module_v2() interfaces.
112080 */
112081 static int createModule(
112082   sqlite3 *db,                    /* Database in which module is registered */
112083   const char *zName,              /* Name assigned to this module */
112084   const sqlite3_module *pModule,  /* The definition of the module */
112085   void *pAux,                     /* Context pointer for xCreate/xConnect */
112086   void (*xDestroy)(void *)        /* Module destructor function */
112087 ){
112088   int rc = SQLITE_OK;
112089   int nName;
112090 
112091   sqlite3_mutex_enter(db->mutex);
112092   nName = sqlite3Strlen30(zName);
112093   if( sqlite3HashFind(&db->aModule, zName) ){
112094     rc = SQLITE_MISUSE_BKPT;
112095   }else{
112096     Module *pMod;
112097     pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
112098     if( pMod ){
112099       Module *pDel;
112100       char *zCopy = (char *)(&pMod[1]);
112101       memcpy(zCopy, zName, nName+1);
112102       pMod->zName = zCopy;
112103       pMod->pModule = pModule;
112104       pMod->pAux = pAux;
112105       pMod->xDestroy = xDestroy;
112106       pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
112107       assert( pDel==0 || pDel==pMod );
112108       if( pDel ){
112109         db->mallocFailed = 1;
112110         sqlite3DbFree(db, pDel);
112111       }
112112     }
112113   }
112114   rc = sqlite3ApiExit(db, rc);
112115   if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
112116 
112117   sqlite3_mutex_leave(db->mutex);
112118   return rc;
112119 }
112120 
112121 
112122 /*
112123 ** External API function used to create a new virtual-table module.
112124 */
112125 SQLITE_API int sqlite3_create_module(
112126   sqlite3 *db,                    /* Database in which module is registered */
112127   const char *zName,              /* Name assigned to this module */
112128   const sqlite3_module *pModule,  /* The definition of the module */
112129   void *pAux                      /* Context pointer for xCreate/xConnect */
112130 ){
112131   return createModule(db, zName, pModule, pAux, 0);
112132 }
112133 
112134 /*
112135 ** External API function used to create a new virtual-table module.
112136 */
112137 SQLITE_API int sqlite3_create_module_v2(
112138   sqlite3 *db,                    /* Database in which module is registered */
112139   const char *zName,              /* Name assigned to this module */
112140   const sqlite3_module *pModule,  /* The definition of the module */
112141   void *pAux,                     /* Context pointer for xCreate/xConnect */
112142   void (*xDestroy)(void *)        /* Module destructor function */
112143 ){
112144   return createModule(db, zName, pModule, pAux, xDestroy);
112145 }
112146 
112147 /*
112148 ** Lock the virtual table so that it cannot be disconnected.
112149 ** Locks nest.  Every lock should have a corresponding unlock.
112150 ** If an unlock is omitted, resources leaks will occur.
112151 **
112152 ** If a disconnect is attempted while a virtual table is locked,
112153 ** the disconnect is deferred until all locks have been removed.
112154 */
112155 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
112156   pVTab->nRef++;
112157 }
112158 
112159 
112160 /*
112161 ** pTab is a pointer to a Table structure representing a virtual-table.
112162 ** Return a pointer to the VTable object used by connection db to access
112163 ** this virtual-table, if one has been created, or NULL otherwise.
112164 */
112165 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
112166   VTable *pVtab;
112167   assert( IsVirtual(pTab) );
112168   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
112169   return pVtab;
112170 }
112171 
112172 /*
112173 ** Decrement the ref-count on a virtual table object. When the ref-count
112174 ** reaches zero, call the xDisconnect() method to delete the object.
112175 */
112176 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
112177   sqlite3 *db = pVTab->db;
112178 
112179   assert( db );
112180   assert( pVTab->nRef>0 );
112181   assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
112182 
112183   pVTab->nRef--;
112184   if( pVTab->nRef==0 ){
112185     sqlite3_vtab *p = pVTab->pVtab;
112186     if( p ){
112187       p->pModule->xDisconnect(p);
112188     }
112189     sqlite3DbFree(db, pVTab);
112190   }
112191 }
112192 
112193 /*
112194 ** Table p is a virtual table. This function moves all elements in the
112195 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
112196 ** database connections to be disconnected at the next opportunity.
112197 ** Except, if argument db is not NULL, then the entry associated with
112198 ** connection db is left in the p->pVTable list.
112199 */
112200 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
112201   VTable *pRet = 0;
112202   VTable *pVTable = p->pVTable;
112203   p->pVTable = 0;
112204 
112205   /* Assert that the mutex (if any) associated with the BtShared database
112206   ** that contains table p is held by the caller. See header comments
112207   ** above function sqlite3VtabUnlockList() for an explanation of why
112208   ** this makes it safe to access the sqlite3.pDisconnect list of any
112209   ** database connection that may have an entry in the p->pVTable list.
112210   */
112211   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
112212 
112213   while( pVTable ){
112214     sqlite3 *db2 = pVTable->db;
112215     VTable *pNext = pVTable->pNext;
112216     assert( db2 );
112217     if( db2==db ){
112218       pRet = pVTable;
112219       p->pVTable = pRet;
112220       pRet->pNext = 0;
112221     }else{
112222       pVTable->pNext = db2->pDisconnect;
112223       db2->pDisconnect = pVTable;
112224     }
112225     pVTable = pNext;
112226   }
112227 
112228   assert( !db || pRet );
112229   return pRet;
112230 }
112231 
112232 /*
112233 ** Table *p is a virtual table. This function removes the VTable object
112234 ** for table *p associated with database connection db from the linked
112235 ** list in p->pVTab. It also decrements the VTable ref count. This is
112236 ** used when closing database connection db to free all of its VTable
112237 ** objects without disturbing the rest of the Schema object (which may
112238 ** be being used by other shared-cache connections).
112239 */
112240 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
112241   VTable **ppVTab;
112242 
112243   assert( IsVirtual(p) );
112244   assert( sqlite3BtreeHoldsAllMutexes(db) );
112245   assert( sqlite3_mutex_held(db->mutex) );
112246 
112247   for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
112248     if( (*ppVTab)->db==db  ){
112249       VTable *pVTab = *ppVTab;
112250       *ppVTab = pVTab->pNext;
112251       sqlite3VtabUnlock(pVTab);
112252       break;
112253     }
112254   }
112255 }
112256 
112257 
112258 /*
112259 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
112260 **
112261 ** This function may only be called when the mutexes associated with all
112262 ** shared b-tree databases opened using connection db are held by the
112263 ** caller. This is done to protect the sqlite3.pDisconnect list. The
112264 ** sqlite3.pDisconnect list is accessed only as follows:
112265 **
112266 **   1) By this function. In this case, all BtShared mutexes and the mutex
112267 **      associated with the database handle itself must be held.
112268 **
112269 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
112270 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
112271 **      associated with the database the virtual table is stored in is held
112272 **      or, if the virtual table is stored in a non-sharable database, then
112273 **      the database handle mutex is held.
112274 **
112275 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
112276 ** by multiple threads. It is thread-safe.
112277 */
112278 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
112279   VTable *p = db->pDisconnect;
112280   db->pDisconnect = 0;
112281 
112282   assert( sqlite3BtreeHoldsAllMutexes(db) );
112283   assert( sqlite3_mutex_held(db->mutex) );
112284 
112285   if( p ){
112286     sqlite3ExpirePreparedStatements(db);
112287     do {
112288       VTable *pNext = p->pNext;
112289       sqlite3VtabUnlock(p);
112290       p = pNext;
112291     }while( p );
112292   }
112293 }
112294 
112295 /*
112296 ** Clear any and all virtual-table information from the Table record.
112297 ** This routine is called, for example, just before deleting the Table
112298 ** record.
112299 **
112300 ** Since it is a virtual-table, the Table structure contains a pointer
112301 ** to the head of a linked list of VTable structures. Each VTable
112302 ** structure is associated with a single sqlite3* user of the schema.
112303 ** The reference count of the VTable structure associated with database
112304 ** connection db is decremented immediately (which may lead to the
112305 ** structure being xDisconnected and free). Any other VTable structures
112306 ** in the list are moved to the sqlite3.pDisconnect list of the associated
112307 ** database connection.
112308 */
112309 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
112310   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
112311   if( p->azModuleArg ){
112312     int i;
112313     for(i=0; i<p->nModuleArg; i++){
112314       if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
112315     }
112316     sqlite3DbFree(db, p->azModuleArg);
112317   }
112318 }
112319 
112320 /*
112321 ** Add a new module argument to pTable->azModuleArg[].
112322 ** The string is not copied - the pointer is stored.  The
112323 ** string will be freed automatically when the table is
112324 ** deleted.
112325 */
112326 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
112327   int i = pTable->nModuleArg++;
112328   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
112329   char **azModuleArg;
112330   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
112331   if( azModuleArg==0 ){
112332     int j;
112333     for(j=0; j<i; j++){
112334       sqlite3DbFree(db, pTable->azModuleArg[j]);
112335     }
112336     sqlite3DbFree(db, zArg);
112337     sqlite3DbFree(db, pTable->azModuleArg);
112338     pTable->nModuleArg = 0;
112339   }else{
112340     azModuleArg[i] = zArg;
112341     azModuleArg[i+1] = 0;
112342   }
112343   pTable->azModuleArg = azModuleArg;
112344 }
112345 
112346 /*
112347 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
112348 ** statement.  The module name has been parsed, but the optional list
112349 ** of parameters that follow the module name are still pending.
112350 */
112351 SQLITE_PRIVATE void sqlite3VtabBeginParse(
112352   Parse *pParse,        /* Parsing context */
112353   Token *pName1,        /* Name of new table, or database name */
112354   Token *pName2,        /* Name of new table or NULL */
112355   Token *pModuleName,   /* Name of the module for the virtual table */
112356   int ifNotExists       /* No error if the table already exists */
112357 ){
112358   int iDb;              /* The database the table is being created in */
112359   Table *pTable;        /* The new virtual table */
112360   sqlite3 *db;          /* Database connection */
112361 
112362   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
112363   pTable = pParse->pNewTable;
112364   if( pTable==0 ) return;
112365   assert( 0==pTable->pIndex );
112366 
112367   db = pParse->db;
112368   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
112369   assert( iDb>=0 );
112370 
112371   pTable->tabFlags |= TF_Virtual;
112372   pTable->nModuleArg = 0;
112373   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
112374   addModuleArgument(db, pTable, 0);
112375   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
112376   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
112377 
112378 #ifndef SQLITE_OMIT_AUTHORIZATION
112379   /* Creating a virtual table invokes the authorization callback twice.
112380   ** The first invocation, to obtain permission to INSERT a row into the
112381   ** sqlite_master table, has already been made by sqlite3StartTable().
112382   ** The second call, to obtain permission to create the table, is made now.
112383   */
112384   if( pTable->azModuleArg ){
112385     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
112386             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
112387   }
112388 #endif
112389 }
112390 
112391 /*
112392 ** This routine takes the module argument that has been accumulating
112393 ** in pParse->zArg[] and appends it to the list of arguments on the
112394 ** virtual table currently under construction in pParse->pTable.
112395 */
112396 static void addArgumentToVtab(Parse *pParse){
112397   if( pParse->sArg.z && pParse->pNewTable ){
112398     const char *z = (const char*)pParse->sArg.z;
112399     int n = pParse->sArg.n;
112400     sqlite3 *db = pParse->db;
112401     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
112402   }
112403 }
112404 
112405 /*
112406 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
112407 ** has been completely parsed.
112408 */
112409 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
112410   Table *pTab = pParse->pNewTable;  /* The table being constructed */
112411   sqlite3 *db = pParse->db;         /* The database connection */
112412 
112413   if( pTab==0 ) return;
112414   addArgumentToVtab(pParse);
112415   pParse->sArg.z = 0;
112416   if( pTab->nModuleArg<1 ) return;
112417 
112418   /* If the CREATE VIRTUAL TABLE statement is being entered for the
112419   ** first time (in other words if the virtual table is actually being
112420   ** created now instead of just being read out of sqlite_master) then
112421   ** do additional initialization work and store the statement text
112422   ** in the sqlite_master table.
112423   */
112424   if( !db->init.busy ){
112425     char *zStmt;
112426     char *zWhere;
112427     int iDb;
112428     Vdbe *v;
112429 
112430     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
112431     if( pEnd ){
112432       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
112433     }
112434     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
112435 
112436     /* A slot for the record has already been allocated in the
112437     ** SQLITE_MASTER table.  We just need to update that slot with all
112438     ** the information we've collected.
112439     **
112440     ** The VM register number pParse->regRowid holds the rowid of an
112441     ** entry in the sqlite_master table tht was created for this vtab
112442     ** by sqlite3StartTable().
112443     */
112444     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
112445     sqlite3NestedParse(pParse,
112446       "UPDATE %Q.%s "
112447          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
112448        "WHERE rowid=#%d",
112449       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
112450       pTab->zName,
112451       pTab->zName,
112452       zStmt,
112453       pParse->regRowid
112454     );
112455     sqlite3DbFree(db, zStmt);
112456     v = sqlite3GetVdbe(pParse);
112457     sqlite3ChangeCookie(pParse, iDb);
112458 
112459     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
112460     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
112461     sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
112462     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
112463                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
112464   }
112465 
112466   /* If we are rereading the sqlite_master table create the in-memory
112467   ** record of the table. The xConnect() method is not called until
112468   ** the first time the virtual table is used in an SQL statement. This
112469   ** allows a schema that contains virtual tables to be loaded before
112470   ** the required virtual table implementations are registered.  */
112471   else {
112472     Table *pOld;
112473     Schema *pSchema = pTab->pSchema;
112474     const char *zName = pTab->zName;
112475     assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
112476     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
112477     if( pOld ){
112478       db->mallocFailed = 1;
112479       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
112480       return;
112481     }
112482     pParse->pNewTable = 0;
112483   }
112484 }
112485 
112486 /*
112487 ** The parser calls this routine when it sees the first token
112488 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
112489 */
112490 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
112491   addArgumentToVtab(pParse);
112492   pParse->sArg.z = 0;
112493   pParse->sArg.n = 0;
112494 }
112495 
112496 /*
112497 ** The parser calls this routine for each token after the first token
112498 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
112499 */
112500 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
112501   Token *pArg = &pParse->sArg;
112502   if( pArg->z==0 ){
112503     pArg->z = p->z;
112504     pArg->n = p->n;
112505   }else{
112506     assert(pArg->z < p->z);
112507     pArg->n = (int)(&p->z[p->n] - pArg->z);
112508   }
112509 }
112510 
112511 /*
112512 ** Invoke a virtual table constructor (either xCreate or xConnect). The
112513 ** pointer to the function to invoke is passed as the fourth parameter
112514 ** to this procedure.
112515 */
112516 static int vtabCallConstructor(
112517   sqlite3 *db,
112518   Table *pTab,
112519   Module *pMod,
112520   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
112521   char **pzErr
112522 ){
112523   VtabCtx sCtx, *pPriorCtx;
112524   VTable *pVTable;
112525   int rc;
112526   const char *const*azArg = (const char *const*)pTab->azModuleArg;
112527   int nArg = pTab->nModuleArg;
112528   char *zErr = 0;
112529   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
112530   int iDb;
112531 
112532   if( !zModuleName ){
112533     return SQLITE_NOMEM;
112534   }
112535 
112536   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
112537   if( !pVTable ){
112538     sqlite3DbFree(db, zModuleName);
112539     return SQLITE_NOMEM;
112540   }
112541   pVTable->db = db;
112542   pVTable->pMod = pMod;
112543 
112544   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
112545   pTab->azModuleArg[1] = db->aDb[iDb].zName;
112546 
112547   /* Invoke the virtual table constructor */
112548   assert( &db->pVtabCtx );
112549   assert( xConstruct );
112550   sCtx.pTab = pTab;
112551   sCtx.pVTable = pVTable;
112552   pPriorCtx = db->pVtabCtx;
112553   db->pVtabCtx = &sCtx;
112554   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
112555   db->pVtabCtx = pPriorCtx;
112556   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
112557 
112558   if( SQLITE_OK!=rc ){
112559     if( zErr==0 ){
112560       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
112561     }else {
112562       *pzErr = sqlite3MPrintf(db, "%s", zErr);
112563       sqlite3_free(zErr);
112564     }
112565     sqlite3DbFree(db, pVTable);
112566   }else if( ALWAYS(pVTable->pVtab) ){
112567     /* Justification of ALWAYS():  A correct vtab constructor must allocate
112568     ** the sqlite3_vtab object if successful.  */
112569     memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
112570     pVTable->pVtab->pModule = pMod->pModule;
112571     pVTable->nRef = 1;
112572     if( sCtx.pTab ){
112573       const char *zFormat = "vtable constructor did not declare schema: %s";
112574       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
112575       sqlite3VtabUnlock(pVTable);
112576       rc = SQLITE_ERROR;
112577     }else{
112578       int iCol;
112579       /* If everything went according to plan, link the new VTable structure
112580       ** into the linked list headed by pTab->pVTable. Then loop through the
112581       ** columns of the table to see if any of them contain the token "hidden".
112582       ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
112583       ** the type string.  */
112584       pVTable->pNext = pTab->pVTable;
112585       pTab->pVTable = pVTable;
112586 
112587       for(iCol=0; iCol<pTab->nCol; iCol++){
112588         char *zType = pTab->aCol[iCol].zType;
112589         int nType;
112590         int i = 0;
112591         if( !zType ) continue;
112592         nType = sqlite3Strlen30(zType);
112593         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
112594           for(i=0; i<nType; i++){
112595             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
112596              && (zType[i+7]=='\0' || zType[i+7]==' ')
112597             ){
112598               i++;
112599               break;
112600             }
112601           }
112602         }
112603         if( i<nType ){
112604           int j;
112605           int nDel = 6 + (zType[i+6] ? 1 : 0);
112606           for(j=i; (j+nDel)<=nType; j++){
112607             zType[j] = zType[j+nDel];
112608           }
112609           if( zType[i]=='\0' && i>0 ){
112610             assert(zType[i-1]==' ');
112611             zType[i-1] = '\0';
112612           }
112613           pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
112614         }
112615       }
112616     }
112617   }
112618 
112619   sqlite3DbFree(db, zModuleName);
112620   return rc;
112621 }
112622 
112623 /*
112624 ** This function is invoked by the parser to call the xConnect() method
112625 ** of the virtual table pTab. If an error occurs, an error code is returned
112626 ** and an error left in pParse.
112627 **
112628 ** This call is a no-op if table pTab is not a virtual table.
112629 */
112630 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
112631   sqlite3 *db = pParse->db;
112632   const char *zMod;
112633   Module *pMod;
112634   int rc;
112635 
112636   assert( pTab );
112637   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
112638     return SQLITE_OK;
112639   }
112640 
112641   /* Locate the required virtual table module */
112642   zMod = pTab->azModuleArg[0];
112643   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
112644 
112645   if( !pMod ){
112646     const char *zModule = pTab->azModuleArg[0];
112647     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
112648     rc = SQLITE_ERROR;
112649   }else{
112650     char *zErr = 0;
112651     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
112652     if( rc!=SQLITE_OK ){
112653       sqlite3ErrorMsg(pParse, "%s", zErr);
112654     }
112655     sqlite3DbFree(db, zErr);
112656   }
112657 
112658   return rc;
112659 }
112660 /*
112661 ** Grow the db->aVTrans[] array so that there is room for at least one
112662 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
112663 */
112664 static int growVTrans(sqlite3 *db){
112665   const int ARRAY_INCR = 5;
112666 
112667   /* Grow the sqlite3.aVTrans array if required */
112668   if( (db->nVTrans%ARRAY_INCR)==0 ){
112669     VTable **aVTrans;
112670     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
112671     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
112672     if( !aVTrans ){
112673       return SQLITE_NOMEM;
112674     }
112675     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
112676     db->aVTrans = aVTrans;
112677   }
112678 
112679   return SQLITE_OK;
112680 }
112681 
112682 /*
112683 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
112684 ** have already been reserved using growVTrans().
112685 */
112686 static void addToVTrans(sqlite3 *db, VTable *pVTab){
112687   /* Add pVtab to the end of sqlite3.aVTrans */
112688   db->aVTrans[db->nVTrans++] = pVTab;
112689   sqlite3VtabLock(pVTab);
112690 }
112691 
112692 /*
112693 ** This function is invoked by the vdbe to call the xCreate method
112694 ** of the virtual table named zTab in database iDb.
112695 **
112696 ** If an error occurs, *pzErr is set to point an an English language
112697 ** description of the error and an SQLITE_XXX error code is returned.
112698 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
112699 */
112700 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
112701   int rc = SQLITE_OK;
112702   Table *pTab;
112703   Module *pMod;
112704   const char *zMod;
112705 
112706   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
112707   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
112708 
112709   /* Locate the required virtual table module */
112710   zMod = pTab->azModuleArg[0];
112711   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
112712 
112713   /* If the module has been registered and includes a Create method,
112714   ** invoke it now. If the module has not been registered, return an
112715   ** error. Otherwise, do nothing.
112716   */
112717   if( !pMod ){
112718     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
112719     rc = SQLITE_ERROR;
112720   }else{
112721     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
112722   }
112723 
112724   /* Justification of ALWAYS():  The xConstructor method is required to
112725   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
112726   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
112727     rc = growVTrans(db);
112728     if( rc==SQLITE_OK ){
112729       addToVTrans(db, sqlite3GetVTable(db, pTab));
112730     }
112731   }
112732 
112733   return rc;
112734 }
112735 
112736 /*
112737 ** This function is used to set the schema of a virtual table.  It is only
112738 ** valid to call this function from within the xCreate() or xConnect() of a
112739 ** virtual table module.
112740 */
112741 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
112742   Parse *pParse;
112743 
112744   int rc = SQLITE_OK;
112745   Table *pTab;
112746   char *zErr = 0;
112747 
112748   sqlite3_mutex_enter(db->mutex);
112749   if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
112750     sqlite3Error(db, SQLITE_MISUSE);
112751     sqlite3_mutex_leave(db->mutex);
112752     return SQLITE_MISUSE_BKPT;
112753   }
112754   assert( (pTab->tabFlags & TF_Virtual)!=0 );
112755 
112756   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
112757   if( pParse==0 ){
112758     rc = SQLITE_NOMEM;
112759   }else{
112760     pParse->declareVtab = 1;
112761     pParse->db = db;
112762     pParse->nQueryLoop = 1;
112763 
112764     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
112765      && pParse->pNewTable
112766      && !db->mallocFailed
112767      && !pParse->pNewTable->pSelect
112768      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
112769     ){
112770       if( !pTab->aCol ){
112771         pTab->aCol = pParse->pNewTable->aCol;
112772         pTab->nCol = pParse->pNewTable->nCol;
112773         pParse->pNewTable->nCol = 0;
112774         pParse->pNewTable->aCol = 0;
112775       }
112776       db->pVtabCtx->pTab = 0;
112777     }else{
112778       sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
112779       sqlite3DbFree(db, zErr);
112780       rc = SQLITE_ERROR;
112781     }
112782     pParse->declareVtab = 0;
112783 
112784     if( pParse->pVdbe ){
112785       sqlite3VdbeFinalize(pParse->pVdbe);
112786     }
112787     sqlite3DeleteTable(db, pParse->pNewTable);
112788     sqlite3ParserReset(pParse);
112789     sqlite3StackFree(db, pParse);
112790   }
112791 
112792   assert( (rc&0xff)==rc );
112793   rc = sqlite3ApiExit(db, rc);
112794   sqlite3_mutex_leave(db->mutex);
112795   return rc;
112796 }
112797 
112798 /*
112799 ** This function is invoked by the vdbe to call the xDestroy method
112800 ** of the virtual table named zTab in database iDb. This occurs
112801 ** when a DROP TABLE is mentioned.
112802 **
112803 ** This call is a no-op if zTab is not a virtual table.
112804 */
112805 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
112806   int rc = SQLITE_OK;
112807   Table *pTab;
112808 
112809   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
112810   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
112811     VTable *p = vtabDisconnectAll(db, pTab);
112812 
112813     assert( rc==SQLITE_OK );
112814     rc = p->pMod->pModule->xDestroy(p->pVtab);
112815 
112816     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
112817     if( rc==SQLITE_OK ){
112818       assert( pTab->pVTable==p && p->pNext==0 );
112819       p->pVtab = 0;
112820       pTab->pVTable = 0;
112821       sqlite3VtabUnlock(p);
112822     }
112823   }
112824 
112825   return rc;
112826 }
112827 
112828 /*
112829 ** This function invokes either the xRollback or xCommit method
112830 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
112831 ** called is identified by the second argument, "offset", which is
112832 ** the offset of the method to call in the sqlite3_module structure.
112833 **
112834 ** The array is cleared after invoking the callbacks.
112835 */
112836 static void callFinaliser(sqlite3 *db, int offset){
112837   int i;
112838   if( db->aVTrans ){
112839     for(i=0; i<db->nVTrans; i++){
112840       VTable *pVTab = db->aVTrans[i];
112841       sqlite3_vtab *p = pVTab->pVtab;
112842       if( p ){
112843         int (*x)(sqlite3_vtab *);
112844         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
112845         if( x ) x(p);
112846       }
112847       pVTab->iSavepoint = 0;
112848       sqlite3VtabUnlock(pVTab);
112849     }
112850     sqlite3DbFree(db, db->aVTrans);
112851     db->nVTrans = 0;
112852     db->aVTrans = 0;
112853   }
112854 }
112855 
112856 /*
112857 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
112858 ** array. Return the error code for the first error that occurs, or
112859 ** SQLITE_OK if all xSync operations are successful.
112860 **
112861 ** If an error message is available, leave it in p->zErrMsg.
112862 */
112863 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
112864   int i;
112865   int rc = SQLITE_OK;
112866   VTable **aVTrans = db->aVTrans;
112867 
112868   db->aVTrans = 0;
112869   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
112870     int (*x)(sqlite3_vtab *);
112871     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
112872     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
112873       rc = x(pVtab);
112874       sqlite3VtabImportErrmsg(p, pVtab);
112875     }
112876   }
112877   db->aVTrans = aVTrans;
112878   return rc;
112879 }
112880 
112881 /*
112882 ** Invoke the xRollback method of all virtual tables in the
112883 ** sqlite3.aVTrans array. Then clear the array itself.
112884 */
112885 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
112886   callFinaliser(db, offsetof(sqlite3_module,xRollback));
112887   return SQLITE_OK;
112888 }
112889 
112890 /*
112891 ** Invoke the xCommit method of all virtual tables in the
112892 ** sqlite3.aVTrans array. Then clear the array itself.
112893 */
112894 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
112895   callFinaliser(db, offsetof(sqlite3_module,xCommit));
112896   return SQLITE_OK;
112897 }
112898 
112899 /*
112900 ** If the virtual table pVtab supports the transaction interface
112901 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
112902 ** not currently open, invoke the xBegin method now.
112903 **
112904 ** If the xBegin call is successful, place the sqlite3_vtab pointer
112905 ** in the sqlite3.aVTrans array.
112906 */
112907 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
112908   int rc = SQLITE_OK;
112909   const sqlite3_module *pModule;
112910 
112911   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
112912   ** than zero, then this function is being called from within a
112913   ** virtual module xSync() callback. It is illegal to write to
112914   ** virtual module tables in this case, so return SQLITE_LOCKED.
112915   */
112916   if( sqlite3VtabInSync(db) ){
112917     return SQLITE_LOCKED;
112918   }
112919   if( !pVTab ){
112920     return SQLITE_OK;
112921   }
112922   pModule = pVTab->pVtab->pModule;
112923 
112924   if( pModule->xBegin ){
112925     int i;
112926 
112927     /* If pVtab is already in the aVTrans array, return early */
112928     for(i=0; i<db->nVTrans; i++){
112929       if( db->aVTrans[i]==pVTab ){
112930         return SQLITE_OK;
112931       }
112932     }
112933 
112934     /* Invoke the xBegin method. If successful, add the vtab to the
112935     ** sqlite3.aVTrans[] array. */
112936     rc = growVTrans(db);
112937     if( rc==SQLITE_OK ){
112938       rc = pModule->xBegin(pVTab->pVtab);
112939       if( rc==SQLITE_OK ){
112940         addToVTrans(db, pVTab);
112941       }
112942     }
112943   }
112944   return rc;
112945 }
112946 
112947 /*
112948 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
112949 ** virtual tables that currently have an open transaction. Pass iSavepoint
112950 ** as the second argument to the virtual table method invoked.
112951 **
112952 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
112953 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
112954 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
112955 ** an open transaction is invoked.
112956 **
112957 ** If any virtual table method returns an error code other than SQLITE_OK,
112958 ** processing is abandoned and the error returned to the caller of this
112959 ** function immediately. If all calls to virtual table methods are successful,
112960 ** SQLITE_OK is returned.
112961 */
112962 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
112963   int rc = SQLITE_OK;
112964 
112965   assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
112966   assert( iSavepoint>=0 );
112967   if( db->aVTrans ){
112968     int i;
112969     for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
112970       VTable *pVTab = db->aVTrans[i];
112971       const sqlite3_module *pMod = pVTab->pMod->pModule;
112972       if( pVTab->pVtab && pMod->iVersion>=2 ){
112973         int (*xMethod)(sqlite3_vtab *, int);
112974         switch( op ){
112975           case SAVEPOINT_BEGIN:
112976             xMethod = pMod->xSavepoint;
112977             pVTab->iSavepoint = iSavepoint+1;
112978             break;
112979           case SAVEPOINT_ROLLBACK:
112980             xMethod = pMod->xRollbackTo;
112981             break;
112982           default:
112983             xMethod = pMod->xRelease;
112984             break;
112985         }
112986         if( xMethod && pVTab->iSavepoint>iSavepoint ){
112987           rc = xMethod(pVTab->pVtab, iSavepoint);
112988         }
112989       }
112990     }
112991   }
112992   return rc;
112993 }
112994 
112995 /*
112996 ** The first parameter (pDef) is a function implementation.  The
112997 ** second parameter (pExpr) is the first argument to this function.
112998 ** If pExpr is a column in a virtual table, then let the virtual
112999 ** table implementation have an opportunity to overload the function.
113000 **
113001 ** This routine is used to allow virtual table implementations to
113002 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
113003 **
113004 ** Return either the pDef argument (indicating no change) or a
113005 ** new FuncDef structure that is marked as ephemeral using the
113006 ** SQLITE_FUNC_EPHEM flag.
113007 */
113008 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
113009   sqlite3 *db,    /* Database connection for reporting malloc problems */
113010   FuncDef *pDef,  /* Function to possibly overload */
113011   int nArg,       /* Number of arguments to the function */
113012   Expr *pExpr     /* First argument to the function */
113013 ){
113014   Table *pTab;
113015   sqlite3_vtab *pVtab;
113016   sqlite3_module *pMod;
113017   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
113018   void *pArg = 0;
113019   FuncDef *pNew;
113020   int rc = 0;
113021   char *zLowerName;
113022   unsigned char *z;
113023 
113024 
113025   /* Check to see the left operand is a column in a virtual table */
113026   if( NEVER(pExpr==0) ) return pDef;
113027   if( pExpr->op!=TK_COLUMN ) return pDef;
113028   pTab = pExpr->pTab;
113029   if( NEVER(pTab==0) ) return pDef;
113030   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
113031   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
113032   assert( pVtab!=0 );
113033   assert( pVtab->pModule!=0 );
113034   pMod = (sqlite3_module *)pVtab->pModule;
113035   if( pMod->xFindFunction==0 ) return pDef;
113036 
113037   /* Call the xFindFunction method on the virtual table implementation
113038   ** to see if the implementation wants to overload this function
113039   */
113040   zLowerName = sqlite3DbStrDup(db, pDef->zName);
113041   if( zLowerName ){
113042     for(z=(unsigned char*)zLowerName; *z; z++){
113043       *z = sqlite3UpperToLower[*z];
113044     }
113045     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
113046     sqlite3DbFree(db, zLowerName);
113047   }
113048   if( rc==0 ){
113049     return pDef;
113050   }
113051 
113052   /* Create a new ephemeral function definition for the overloaded
113053   ** function */
113054   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
113055                              + sqlite3Strlen30(pDef->zName) + 1);
113056   if( pNew==0 ){
113057     return pDef;
113058   }
113059   *pNew = *pDef;
113060   pNew->zName = (char *)&pNew[1];
113061   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
113062   pNew->xFunc = xFunc;
113063   pNew->pUserData = pArg;
113064   pNew->funcFlags |= SQLITE_FUNC_EPHEM;
113065   return pNew;
113066 }
113067 
113068 /*
113069 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
113070 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
113071 ** array if it is missing.  If pTab is already in the array, this routine
113072 ** is a no-op.
113073 */
113074 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
113075   Parse *pToplevel = sqlite3ParseToplevel(pParse);
113076   int i, n;
113077   Table **apVtabLock;
113078 
113079   assert( IsVirtual(pTab) );
113080   for(i=0; i<pToplevel->nVtabLock; i++){
113081     if( pTab==pToplevel->apVtabLock[i] ) return;
113082   }
113083   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
113084   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
113085   if( apVtabLock ){
113086     pToplevel->apVtabLock = apVtabLock;
113087     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
113088   }else{
113089     pToplevel->db->mallocFailed = 1;
113090   }
113091 }
113092 
113093 /*
113094 ** Return the ON CONFLICT resolution mode in effect for the virtual
113095 ** table update operation currently in progress.
113096 **
113097 ** The results of this routine are undefined unless it is called from
113098 ** within an xUpdate method.
113099 */
113100 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
113101   static const unsigned char aMap[] = {
113102     SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
113103   };
113104   assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
113105   assert( OE_Ignore==4 && OE_Replace==5 );
113106   assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
113107   return (int)aMap[db->vtabOnConflict-1];
113108 }
113109 
113110 /*
113111 ** Call from within the xCreate() or xConnect() methods to provide
113112 ** the SQLite core with additional information about the behavior
113113 ** of the virtual table being implemented.
113114 */
113115 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
113116   va_list ap;
113117   int rc = SQLITE_OK;
113118 
113119   sqlite3_mutex_enter(db->mutex);
113120 
113121   va_start(ap, op);
113122   switch( op ){
113123     case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
113124       VtabCtx *p = db->pVtabCtx;
113125       if( !p ){
113126         rc = SQLITE_MISUSE_BKPT;
113127       }else{
113128         assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
113129         p->pVTable->bConstraint = (u8)va_arg(ap, int);
113130       }
113131       break;
113132     }
113133     default:
113134       rc = SQLITE_MISUSE_BKPT;
113135       break;
113136   }
113137   va_end(ap);
113138 
113139   if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
113140   sqlite3_mutex_leave(db->mutex);
113141   return rc;
113142 }
113143 
113144 #endif /* SQLITE_OMIT_VIRTUALTABLE */
113145 
113146 /************** End of vtab.c ************************************************/
113147 /************** Begin file where.c *******************************************/
113148 /*
113149 ** 2001 September 15
113150 **
113151 ** The author disclaims copyright to this source code.  In place of
113152 ** a legal notice, here is a blessing:
113153 **
113154 **    May you do good and not evil.
113155 **    May you find forgiveness for yourself and forgive others.
113156 **    May you share freely, never taking more than you give.
113157 **
113158 *************************************************************************
113159 ** This module contains C code that generates VDBE code used to process
113160 ** the WHERE clause of SQL statements.  This module is responsible for
113161 ** generating the code that loops through a table looking for applicable
113162 ** rows.  Indices are selected and used to speed the search when doing
113163 ** so is applicable.  Because this module is responsible for selecting
113164 ** indices, you might also think of this module as the "query optimizer".
113165 */
113166 /************** Include whereInt.h in the middle of where.c ******************/
113167 /************** Begin file whereInt.h ****************************************/
113168 /*
113169 ** 2013-11-12
113170 **
113171 ** The author disclaims copyright to this source code.  In place of
113172 ** a legal notice, here is a blessing:
113173 **
113174 **    May you do good and not evil.
113175 **    May you find forgiveness for yourself and forgive others.
113176 **    May you share freely, never taking more than you give.
113177 **
113178 *************************************************************************
113179 **
113180 ** This file contains structure and macro definitions for the query
113181 ** planner logic in "where.c".  These definitions are broken out into
113182 ** a separate source file for easier editing.
113183 */
113184 
113185 /*
113186 ** Trace output macros
113187 */
113188 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
113189 /***/ int sqlite3WhereTrace = 0;
113190 #endif
113191 #if defined(SQLITE_DEBUG) \
113192     && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
113193 # define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
113194 # define WHERETRACE_ENABLED 1
113195 #else
113196 # define WHERETRACE(K,X)
113197 #endif
113198 
113199 /* Forward references
113200 */
113201 typedef struct WhereClause WhereClause;
113202 typedef struct WhereMaskSet WhereMaskSet;
113203 typedef struct WhereOrInfo WhereOrInfo;
113204 typedef struct WhereAndInfo WhereAndInfo;
113205 typedef struct WhereLevel WhereLevel;
113206 typedef struct WhereLoop WhereLoop;
113207 typedef struct WherePath WherePath;
113208 typedef struct WhereTerm WhereTerm;
113209 typedef struct WhereLoopBuilder WhereLoopBuilder;
113210 typedef struct WhereScan WhereScan;
113211 typedef struct WhereOrCost WhereOrCost;
113212 typedef struct WhereOrSet WhereOrSet;
113213 
113214 /*
113215 ** This object contains information needed to implement a single nested
113216 ** loop in WHERE clause.
113217 **
113218 ** Contrast this object with WhereLoop.  This object describes the
113219 ** implementation of the loop.  WhereLoop describes the algorithm.
113220 ** This object contains a pointer to the WhereLoop algorithm as one of
113221 ** its elements.
113222 **
113223 ** The WhereInfo object contains a single instance of this object for
113224 ** each term in the FROM clause (which is to say, for each of the
113225 ** nested loops as implemented).  The order of WhereLevel objects determines
113226 ** the loop nested order, with WhereInfo.a[0] being the outer loop and
113227 ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
113228 */
113229 struct WhereLevel {
113230   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
113231   int iTabCur;          /* The VDBE cursor used to access the table */
113232   int iIdxCur;          /* The VDBE cursor used to access pIdx */
113233   int addrBrk;          /* Jump here to break out of the loop */
113234   int addrNxt;          /* Jump here to start the next IN combination */
113235   int addrSkip;         /* Jump here for next iteration of skip-scan */
113236   int addrCont;         /* Jump here to continue with the next loop cycle */
113237   int addrFirst;        /* First instruction of interior of the loop */
113238   int addrBody;         /* Beginning of the body of this loop */
113239   u8 iFrom;             /* Which entry in the FROM clause */
113240   u8 op, p3, p5;        /* Opcode, P3 & P5 of the opcode that ends the loop */
113241   int p1, p2;           /* Operands of the opcode used to ends the loop */
113242   union {               /* Information that depends on pWLoop->wsFlags */
113243     struct {
113244       int nIn;              /* Number of entries in aInLoop[] */
113245       struct InLoop {
113246         int iCur;              /* The VDBE cursor used by this IN operator */
113247         int addrInTop;         /* Top of the IN loop */
113248         u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */
113249       } *aInLoop;           /* Information about each nested IN operator */
113250     } in;                 /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
113251     Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
113252   } u;
113253   struct WhereLoop *pWLoop;  /* The selected WhereLoop object */
113254   Bitmask notReady;          /* FROM entries not usable at this level */
113255 };
113256 
113257 /*
113258 ** Each instance of this object represents an algorithm for evaluating one
113259 ** term of a join.  Every term of the FROM clause will have at least
113260 ** one corresponding WhereLoop object (unless INDEXED BY constraints
113261 ** prevent a query solution - which is an error) and many terms of the
113262 ** FROM clause will have multiple WhereLoop objects, each describing a
113263 ** potential way of implementing that FROM-clause term, together with
113264 ** dependencies and cost estimates for using the chosen algorithm.
113265 **
113266 ** Query planning consists of building up a collection of these WhereLoop
113267 ** objects, then computing a particular sequence of WhereLoop objects, with
113268 ** one WhereLoop object per FROM clause term, that satisfy all dependencies
113269 ** and that minimize the overall cost.
113270 */
113271 struct WhereLoop {
113272   Bitmask prereq;       /* Bitmask of other loops that must run first */
113273   Bitmask maskSelf;     /* Bitmask identifying table iTab */
113274 #ifdef SQLITE_DEBUG
113275   char cId;             /* Symbolic ID of this loop for debugging use */
113276 #endif
113277   u8 iTab;              /* Position in FROM clause of table for this loop */
113278   u8 iSortIdx;          /* Sorting index number.  0==None */
113279   LogEst rSetup;        /* One-time setup cost (ex: create transient index) */
113280   LogEst rRun;          /* Cost of running each loop */
113281   LogEst nOut;          /* Estimated number of output rows */
113282   union {
113283     struct {               /* Information for internal btree tables */
113284       u16 nEq;               /* Number of equality constraints */
113285       u16 nSkip;             /* Number of initial index columns to skip */
113286       Index *pIndex;         /* Index used, or NULL */
113287     } btree;
113288     struct {               /* Information for virtual tables */
113289       int idxNum;            /* Index number */
113290       u8 needFree;           /* True if sqlite3_free(idxStr) is needed */
113291       i8 isOrdered;          /* True if satisfies ORDER BY */
113292       u16 omitMask;          /* Terms that may be omitted */
113293       char *idxStr;          /* Index identifier string */
113294     } vtab;
113295   } u;
113296   u32 wsFlags;          /* WHERE_* flags describing the plan */
113297   u16 nLTerm;           /* Number of entries in aLTerm[] */
113298   /**** whereLoopXfer() copies fields above ***********************/
113299 # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
113300   u16 nLSlot;           /* Number of slots allocated for aLTerm[] */
113301   WhereTerm **aLTerm;   /* WhereTerms used */
113302   WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
113303   WhereTerm *aLTermSpace[4];  /* Initial aLTerm[] space */
113304 };
113305 
113306 /* This object holds the prerequisites and the cost of running a
113307 ** subquery on one operand of an OR operator in the WHERE clause.
113308 ** See WhereOrSet for additional information
113309 */
113310 struct WhereOrCost {
113311   Bitmask prereq;     /* Prerequisites */
113312   LogEst rRun;        /* Cost of running this subquery */
113313   LogEst nOut;        /* Number of outputs for this subquery */
113314 };
113315 
113316 /* The WhereOrSet object holds a set of possible WhereOrCosts that
113317 ** correspond to the subquery(s) of OR-clause processing.  Only the
113318 ** best N_OR_COST elements are retained.
113319 */
113320 #define N_OR_COST 3
113321 struct WhereOrSet {
113322   u16 n;                      /* Number of valid a[] entries */
113323   WhereOrCost a[N_OR_COST];   /* Set of best costs */
113324 };
113325 
113326 
113327 /* Forward declaration of methods */
113328 static int whereLoopResize(sqlite3*, WhereLoop*, int);
113329 
113330 /*
113331 ** Each instance of this object holds a sequence of WhereLoop objects
113332 ** that implement some or all of a query plan.
113333 **
113334 ** Think of each WhereLoop object as a node in a graph with arcs
113335 ** showing dependencies and costs for travelling between nodes.  (That is
113336 ** not a completely accurate description because WhereLoop costs are a
113337 ** vector, not a scalar, and because dependencies are many-to-one, not
113338 ** one-to-one as are graph nodes.  But it is a useful visualization aid.)
113339 ** Then a WherePath object is a path through the graph that visits some
113340 ** or all of the WhereLoop objects once.
113341 **
113342 ** The "solver" works by creating the N best WherePath objects of length
113343 ** 1.  Then using those as a basis to compute the N best WherePath objects
113344 ** of length 2.  And so forth until the length of WherePaths equals the
113345 ** number of nodes in the FROM clause.  The best (lowest cost) WherePath
113346 ** at the end is the chosen query plan.
113347 */
113348 struct WherePath {
113349   Bitmask maskLoop;     /* Bitmask of all WhereLoop objects in this path */
113350   Bitmask revLoop;      /* aLoop[]s that should be reversed for ORDER BY */
113351   LogEst nRow;          /* Estimated number of rows generated by this path */
113352   LogEst rCost;         /* Total cost of this path */
113353   LogEst rUnsorted;     /* Total cost of this path ignoring sorting costs */
113354   i8 isOrdered;         /* No. of ORDER BY terms satisfied. -1 for unknown */
113355   WhereLoop **aLoop;    /* Array of WhereLoop objects implementing this path */
113356 };
113357 
113358 /*
113359 ** The query generator uses an array of instances of this structure to
113360 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
113361 ** clause subexpression is separated from the others by AND operators,
113362 ** usually, or sometimes subexpressions separated by OR.
113363 **
113364 ** All WhereTerms are collected into a single WhereClause structure.
113365 ** The following identity holds:
113366 **
113367 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
113368 **
113369 ** When a term is of the form:
113370 **
113371 **              X <op> <expr>
113372 **
113373 ** where X is a column name and <op> is one of certain operators,
113374 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
113375 ** cursor number and column number for X.  WhereTerm.eOperator records
113376 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
113377 ** use of a bitmask encoding for the operator allows us to search
113378 ** quickly for terms that match any of several different operators.
113379 **
113380 ** A WhereTerm might also be two or more subterms connected by OR:
113381 **
113382 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
113383 **
113384 ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
113385 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
113386 ** is collected about the OR clause.
113387 **
113388 ** If a term in the WHERE clause does not match either of the two previous
113389 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
113390 ** to the original subexpression content and wtFlags is set up appropriately
113391 ** but no other fields in the WhereTerm object are meaningful.
113392 **
113393 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
113394 ** but they do so indirectly.  A single WhereMaskSet structure translates
113395 ** cursor number into bits and the translated bit is stored in the prereq
113396 ** fields.  The translation is used in order to maximize the number of
113397 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
113398 ** spread out over the non-negative integers.  For example, the cursor
113399 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
113400 ** translates these sparse cursor numbers into consecutive integers
113401 ** beginning with 0 in order to make the best possible use of the available
113402 ** bits in the Bitmask.  So, in the example above, the cursor numbers
113403 ** would be mapped into integers 0 through 7.
113404 **
113405 ** The number of terms in a join is limited by the number of bits
113406 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
113407 ** is only able to process joins with 64 or fewer tables.
113408 */
113409 struct WhereTerm {
113410   Expr *pExpr;            /* Pointer to the subexpression that is this term */
113411   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
113412   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
113413   union {
113414     int leftColumn;         /* Column number of X in "X <op> <expr>" */
113415     WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
113416     WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
113417   } u;
113418   LogEst truthProb;       /* Probability of truth for this expression */
113419   u16 eOperator;          /* A WO_xx value describing <op> */
113420   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
113421   u8 nChild;              /* Number of children that must disable us */
113422   WhereClause *pWC;       /* The clause this term is part of */
113423   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
113424   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
113425 };
113426 
113427 /*
113428 ** Allowed values of WhereTerm.wtFlags
113429 */
113430 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
113431 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
113432 #define TERM_CODED      0x04   /* This term is already coded */
113433 #define TERM_COPIED     0x08   /* Has a child */
113434 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
113435 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
113436 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
113437 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
113438 #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
113439 #else
113440 #  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
113441 #endif
113442 
113443 /*
113444 ** An instance of the WhereScan object is used as an iterator for locating
113445 ** terms in the WHERE clause that are useful to the query planner.
113446 */
113447 struct WhereScan {
113448   WhereClause *pOrigWC;      /* Original, innermost WhereClause */
113449   WhereClause *pWC;          /* WhereClause currently being scanned */
113450   char *zCollName;           /* Required collating sequence, if not NULL */
113451   char idxaff;               /* Must match this affinity, if zCollName!=NULL */
113452   unsigned char nEquiv;      /* Number of entries in aEquiv[] */
113453   unsigned char iEquiv;      /* Next unused slot in aEquiv[] */
113454   u32 opMask;                /* Acceptable operators */
113455   int k;                     /* Resume scanning at this->pWC->a[this->k] */
113456   int aEquiv[22];            /* Cursor,Column pairs for equivalence classes */
113457 };
113458 
113459 /*
113460 ** An instance of the following structure holds all information about a
113461 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
113462 **
113463 ** Explanation of pOuter:  For a WHERE clause of the form
113464 **
113465 **           a AND ((b AND c) OR (d AND e)) AND f
113466 **
113467 ** There are separate WhereClause objects for the whole clause and for
113468 ** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
113469 ** subclauses points to the WhereClause object for the whole clause.
113470 */
113471 struct WhereClause {
113472   WhereInfo *pWInfo;       /* WHERE clause processing context */
113473   WhereClause *pOuter;     /* Outer conjunction */
113474   u8 op;                   /* Split operator.  TK_AND or TK_OR */
113475   int nTerm;               /* Number of terms */
113476   int nSlot;               /* Number of entries in a[] */
113477   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
113478 #if defined(SQLITE_SMALL_STACK)
113479   WhereTerm aStatic[1];    /* Initial static space for a[] */
113480 #else
113481   WhereTerm aStatic[8];    /* Initial static space for a[] */
113482 #endif
113483 };
113484 
113485 /*
113486 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
113487 ** a dynamically allocated instance of the following structure.
113488 */
113489 struct WhereOrInfo {
113490   WhereClause wc;          /* Decomposition into subterms */
113491   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
113492 };
113493 
113494 /*
113495 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
113496 ** a dynamically allocated instance of the following structure.
113497 */
113498 struct WhereAndInfo {
113499   WhereClause wc;          /* The subexpression broken out */
113500 };
113501 
113502 /*
113503 ** An instance of the following structure keeps track of a mapping
113504 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
113505 **
113506 ** The VDBE cursor numbers are small integers contained in
113507 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
113508 ** clause, the cursor numbers might not begin with 0 and they might
113509 ** contain gaps in the numbering sequence.  But we want to make maximum
113510 ** use of the bits in our bitmasks.  This structure provides a mapping
113511 ** from the sparse cursor numbers into consecutive integers beginning
113512 ** with 0.
113513 **
113514 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
113515 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
113516 **
113517 ** For example, if the WHERE clause expression used these VDBE
113518 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
113519 ** would map those cursor numbers into bits 0 through 5.
113520 **
113521 ** Note that the mapping is not necessarily ordered.  In the example
113522 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
113523 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
113524 ** does not really matter.  What is important is that sparse cursor
113525 ** numbers all get mapped into bit numbers that begin with 0 and contain
113526 ** no gaps.
113527 */
113528 struct WhereMaskSet {
113529   int n;                        /* Number of assigned cursor values */
113530   int ix[BMS];                  /* Cursor assigned to each bit */
113531 };
113532 
113533 /*
113534 ** This object is a convenience wrapper holding all information needed
113535 ** to construct WhereLoop objects for a particular query.
113536 */
113537 struct WhereLoopBuilder {
113538   WhereInfo *pWInfo;        /* Information about this WHERE */
113539   WhereClause *pWC;         /* WHERE clause terms */
113540   ExprList *pOrderBy;       /* ORDER BY clause */
113541   WhereLoop *pNew;          /* Template WhereLoop */
113542   WhereOrSet *pOrSet;       /* Record best loops here, if not NULL */
113543 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
113544   UnpackedRecord *pRec;     /* Probe for stat4 (if required) */
113545   int nRecValid;            /* Number of valid fields currently in pRec */
113546 #endif
113547 };
113548 
113549 /*
113550 ** The WHERE clause processing routine has two halves.  The
113551 ** first part does the start of the WHERE loop and the second
113552 ** half does the tail of the WHERE loop.  An instance of
113553 ** this structure is returned by the first half and passed
113554 ** into the second half to give some continuity.
113555 **
113556 ** An instance of this object holds the complete state of the query
113557 ** planner.
113558 */
113559 struct WhereInfo {
113560   Parse *pParse;            /* Parsing and code generating context */
113561   SrcList *pTabList;        /* List of tables in the join */
113562   ExprList *pOrderBy;       /* The ORDER BY clause or NULL */
113563   ExprList *pResultSet;     /* Result set. DISTINCT operates on these */
113564   WhereLoop *pLoops;        /* List of all WhereLoop objects */
113565   Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */
113566   LogEst nRowOut;           /* Estimated number of output rows */
113567   u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
113568   i8 nOBSat;                /* Number of ORDER BY terms satisfied by indices */
113569   u8 sorted;                /* True if really sorted (not just grouped) */
113570   u8 okOnePass;             /* Ok to use one-pass algorithm for UPDATE/DELETE */
113571   u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
113572   u8 eDistinct;             /* One of the WHERE_DISTINCT_* values below */
113573   u8 nLevel;                /* Number of nested loop */
113574   int iTop;                 /* The very beginning of the WHERE loop */
113575   int iContinue;            /* Jump here to continue with next record */
113576   int iBreak;               /* Jump here to break out of the loop */
113577   int savedNQueryLoop;      /* pParse->nQueryLoop outside the WHERE loop */
113578   int aiCurOnePass[2];      /* OP_OpenWrite cursors for the ONEPASS opt */
113579   WhereMaskSet sMaskSet;    /* Map cursor numbers to bitmasks */
113580   WhereClause sWC;          /* Decomposition of the WHERE clause */
113581   WhereLevel a[1];          /* Information about each nest loop in WHERE */
113582 };
113583 
113584 /*
113585 ** Bitmasks for the operators on WhereTerm objects.  These are all
113586 ** operators that are of interest to the query planner.  An
113587 ** OR-ed combination of these values can be used when searching for
113588 ** particular WhereTerms within a WhereClause.
113589 */
113590 #define WO_IN     0x001
113591 #define WO_EQ     0x002
113592 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
113593 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
113594 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
113595 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
113596 #define WO_MATCH  0x040
113597 #define WO_ISNULL 0x080
113598 #define WO_OR     0x100       /* Two or more OR-connected terms */
113599 #define WO_AND    0x200       /* Two or more AND-connected terms */
113600 #define WO_EQUIV  0x400       /* Of the form A==B, both columns */
113601 #define WO_NOOP   0x800       /* This term does not restrict search space */
113602 
113603 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
113604 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
113605 
113606 /*
113607 ** These are definitions of bits in the WhereLoop.wsFlags field.
113608 ** The particular combination of bits in each WhereLoop help to
113609 ** determine the algorithm that WhereLoop represents.
113610 */
113611 #define WHERE_COLUMN_EQ    0x00000001  /* x=EXPR */
113612 #define WHERE_COLUMN_RANGE 0x00000002  /* x<EXPR and/or x>EXPR */
113613 #define WHERE_COLUMN_IN    0x00000004  /* x IN (...) */
113614 #define WHERE_COLUMN_NULL  0x00000008  /* x IS NULL */
113615 #define WHERE_CONSTRAINT   0x0000000f  /* Any of the WHERE_COLUMN_xxx values */
113616 #define WHERE_TOP_LIMIT    0x00000010  /* x<EXPR or x<=EXPR constraint */
113617 #define WHERE_BTM_LIMIT    0x00000020  /* x>EXPR or x>=EXPR constraint */
113618 #define WHERE_BOTH_LIMIT   0x00000030  /* Both x>EXPR and x<EXPR */
113619 #define WHERE_IDX_ONLY     0x00000040  /* Use index only - omit table */
113620 #define WHERE_IPK          0x00000100  /* x is the INTEGER PRIMARY KEY */
113621 #define WHERE_INDEXED      0x00000200  /* WhereLoop.u.btree.pIndex is valid */
113622 #define WHERE_VIRTUALTABLE 0x00000400  /* WhereLoop.u.vtab is valid */
113623 #define WHERE_IN_ABLE      0x00000800  /* Able to support an IN operator */
113624 #define WHERE_ONEROW       0x00001000  /* Selects no more than one row */
113625 #define WHERE_MULTI_OR     0x00002000  /* OR using multiple indices */
113626 #define WHERE_AUTO_INDEX   0x00004000  /* Uses an ephemeral index */
113627 #define WHERE_SKIPSCAN     0x00008000  /* Uses the skip-scan algorithm */
113628 #define WHERE_UNQ_WANTED   0x00010000  /* WHERE_ONEROW would have been helpful*/
113629 
113630 /************** End of whereInt.h ********************************************/
113631 /************** Continuing where we left off in where.c **********************/
113632 
113633 /*
113634 ** Return the estimated number of output rows from a WHERE clause
113635 */
113636 SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
113637   return sqlite3LogEstToInt(pWInfo->nRowOut);
113638 }
113639 
113640 /*
113641 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
113642 ** WHERE clause returns outputs for DISTINCT processing.
113643 */
113644 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
113645   return pWInfo->eDistinct;
113646 }
113647 
113648 /*
113649 ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
113650 ** Return FALSE if the output needs to be sorted.
113651 */
113652 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
113653   return pWInfo->nOBSat;
113654 }
113655 
113656 /*
113657 ** Return the VDBE address or label to jump to in order to continue
113658 ** immediately with the next row of a WHERE clause.
113659 */
113660 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
113661   assert( pWInfo->iContinue!=0 );
113662   return pWInfo->iContinue;
113663 }
113664 
113665 /*
113666 ** Return the VDBE address or label to jump to in order to break
113667 ** out of a WHERE loop.
113668 */
113669 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
113670   return pWInfo->iBreak;
113671 }
113672 
113673 /*
113674 ** Return TRUE if an UPDATE or DELETE statement can operate directly on
113675 ** the rowids returned by a WHERE clause.  Return FALSE if doing an
113676 ** UPDATE or DELETE might change subsequent WHERE clause results.
113677 **
113678 ** If the ONEPASS optimization is used (if this routine returns true)
113679 ** then also write the indices of open cursors used by ONEPASS
113680 ** into aiCur[0] and aiCur[1].  iaCur[0] gets the cursor of the data
113681 ** table and iaCur[1] gets the cursor used by an auxiliary index.
113682 ** Either value may be -1, indicating that cursor is not used.
113683 ** Any cursors returned will have been opened for writing.
113684 **
113685 ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
113686 ** unable to use the ONEPASS optimization.
113687 */
113688 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
113689   memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
113690   return pWInfo->okOnePass;
113691 }
113692 
113693 /*
113694 ** Move the content of pSrc into pDest
113695 */
113696 static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
113697   pDest->n = pSrc->n;
113698   memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
113699 }
113700 
113701 /*
113702 ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
113703 **
113704 ** The new entry might overwrite an existing entry, or it might be
113705 ** appended, or it might be discarded.  Do whatever is the right thing
113706 ** so that pSet keeps the N_OR_COST best entries seen so far.
113707 */
113708 static int whereOrInsert(
113709   WhereOrSet *pSet,      /* The WhereOrSet to be updated */
113710   Bitmask prereq,        /* Prerequisites of the new entry */
113711   LogEst rRun,           /* Run-cost of the new entry */
113712   LogEst nOut            /* Number of outputs for the new entry */
113713 ){
113714   u16 i;
113715   WhereOrCost *p;
113716   for(i=pSet->n, p=pSet->a; i>0; i--, p++){
113717     if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
113718       goto whereOrInsert_done;
113719     }
113720     if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
113721       return 0;
113722     }
113723   }
113724   if( pSet->n<N_OR_COST ){
113725     p = &pSet->a[pSet->n++];
113726     p->nOut = nOut;
113727   }else{
113728     p = pSet->a;
113729     for(i=1; i<pSet->n; i++){
113730       if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
113731     }
113732     if( p->rRun<=rRun ) return 0;
113733   }
113734 whereOrInsert_done:
113735   p->prereq = prereq;
113736   p->rRun = rRun;
113737   if( p->nOut>nOut ) p->nOut = nOut;
113738   return 1;
113739 }
113740 
113741 /*
113742 ** Initialize a preallocated WhereClause structure.
113743 */
113744 static void whereClauseInit(
113745   WhereClause *pWC,        /* The WhereClause to be initialized */
113746   WhereInfo *pWInfo        /* The WHERE processing context */
113747 ){
113748   pWC->pWInfo = pWInfo;
113749   pWC->pOuter = 0;
113750   pWC->nTerm = 0;
113751   pWC->nSlot = ArraySize(pWC->aStatic);
113752   pWC->a = pWC->aStatic;
113753 }
113754 
113755 /* Forward reference */
113756 static void whereClauseClear(WhereClause*);
113757 
113758 /*
113759 ** Deallocate all memory associated with a WhereOrInfo object.
113760 */
113761 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
113762   whereClauseClear(&p->wc);
113763   sqlite3DbFree(db, p);
113764 }
113765 
113766 /*
113767 ** Deallocate all memory associated with a WhereAndInfo object.
113768 */
113769 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
113770   whereClauseClear(&p->wc);
113771   sqlite3DbFree(db, p);
113772 }
113773 
113774 /*
113775 ** Deallocate a WhereClause structure.  The WhereClause structure
113776 ** itself is not freed.  This routine is the inverse of whereClauseInit().
113777 */
113778 static void whereClauseClear(WhereClause *pWC){
113779   int i;
113780   WhereTerm *a;
113781   sqlite3 *db = pWC->pWInfo->pParse->db;
113782   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
113783     if( a->wtFlags & TERM_DYNAMIC ){
113784       sqlite3ExprDelete(db, a->pExpr);
113785     }
113786     if( a->wtFlags & TERM_ORINFO ){
113787       whereOrInfoDelete(db, a->u.pOrInfo);
113788     }else if( a->wtFlags & TERM_ANDINFO ){
113789       whereAndInfoDelete(db, a->u.pAndInfo);
113790     }
113791   }
113792   if( pWC->a!=pWC->aStatic ){
113793     sqlite3DbFree(db, pWC->a);
113794   }
113795 }
113796 
113797 /*
113798 ** Add a single new WhereTerm entry to the WhereClause object pWC.
113799 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
113800 ** The index in pWC->a[] of the new WhereTerm is returned on success.
113801 ** 0 is returned if the new WhereTerm could not be added due to a memory
113802 ** allocation error.  The memory allocation failure will be recorded in
113803 ** the db->mallocFailed flag so that higher-level functions can detect it.
113804 **
113805 ** This routine will increase the size of the pWC->a[] array as necessary.
113806 **
113807 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
113808 ** for freeing the expression p is assumed by the WhereClause object pWC.
113809 ** This is true even if this routine fails to allocate a new WhereTerm.
113810 **
113811 ** WARNING:  This routine might reallocate the space used to store
113812 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
113813 ** calling this routine.  Such pointers may be reinitialized by referencing
113814 ** the pWC->a[] array.
113815 */
113816 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
113817   WhereTerm *pTerm;
113818   int idx;
113819   testcase( wtFlags & TERM_VIRTUAL );
113820   if( pWC->nTerm>=pWC->nSlot ){
113821     WhereTerm *pOld = pWC->a;
113822     sqlite3 *db = pWC->pWInfo->pParse->db;
113823     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
113824     if( pWC->a==0 ){
113825       if( wtFlags & TERM_DYNAMIC ){
113826         sqlite3ExprDelete(db, p);
113827       }
113828       pWC->a = pOld;
113829       return 0;
113830     }
113831     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
113832     if( pOld!=pWC->aStatic ){
113833       sqlite3DbFree(db, pOld);
113834     }
113835     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
113836   }
113837   pTerm = &pWC->a[idx = pWC->nTerm++];
113838   if( p && ExprHasProperty(p, EP_Unlikely) ){
113839     pTerm->truthProb = sqlite3LogEst(p->iTable) - 99;
113840   }else{
113841     pTerm->truthProb = 1;
113842   }
113843   pTerm->pExpr = sqlite3ExprSkipCollate(p);
113844   pTerm->wtFlags = wtFlags;
113845   pTerm->pWC = pWC;
113846   pTerm->iParent = -1;
113847   return idx;
113848 }
113849 
113850 /*
113851 ** This routine identifies subexpressions in the WHERE clause where
113852 ** each subexpression is separated by the AND operator or some other
113853 ** operator specified in the op parameter.  The WhereClause structure
113854 ** is filled with pointers to subexpressions.  For example:
113855 **
113856 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
113857 **           \________/     \_______________/     \________________/
113858 **            slot[0]            slot[1]               slot[2]
113859 **
113860 ** The original WHERE clause in pExpr is unaltered.  All this routine
113861 ** does is make slot[] entries point to substructure within pExpr.
113862 **
113863 ** In the previous sentence and in the diagram, "slot[]" refers to
113864 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
113865 ** all terms of the WHERE clause.
113866 */
113867 static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
113868   pWC->op = op;
113869   if( pExpr==0 ) return;
113870   if( pExpr->op!=op ){
113871     whereClauseInsert(pWC, pExpr, 0);
113872   }else{
113873     whereSplit(pWC, pExpr->pLeft, op);
113874     whereSplit(pWC, pExpr->pRight, op);
113875   }
113876 }
113877 
113878 /*
113879 ** Initialize a WhereMaskSet object
113880 */
113881 #define initMaskSet(P)  (P)->n=0
113882 
113883 /*
113884 ** Return the bitmask for the given cursor number.  Return 0 if
113885 ** iCursor is not in the set.
113886 */
113887 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
113888   int i;
113889   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
113890   for(i=0; i<pMaskSet->n; i++){
113891     if( pMaskSet->ix[i]==iCursor ){
113892       return MASKBIT(i);
113893     }
113894   }
113895   return 0;
113896 }
113897 
113898 /*
113899 ** Create a new mask for cursor iCursor.
113900 **
113901 ** There is one cursor per table in the FROM clause.  The number of
113902 ** tables in the FROM clause is limited by a test early in the
113903 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
113904 ** array will never overflow.
113905 */
113906 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
113907   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
113908   pMaskSet->ix[pMaskSet->n++] = iCursor;
113909 }
113910 
113911 /*
113912 ** These routines walk (recursively) an expression tree and generate
113913 ** a bitmask indicating which tables are used in that expression
113914 ** tree.
113915 */
113916 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
113917 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
113918 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
113919   Bitmask mask = 0;
113920   if( p==0 ) return 0;
113921   if( p->op==TK_COLUMN ){
113922     mask = getMask(pMaskSet, p->iTable);
113923     return mask;
113924   }
113925   mask = exprTableUsage(pMaskSet, p->pRight);
113926   mask |= exprTableUsage(pMaskSet, p->pLeft);
113927   if( ExprHasProperty(p, EP_xIsSelect) ){
113928     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
113929   }else{
113930     mask |= exprListTableUsage(pMaskSet, p->x.pList);
113931   }
113932   return mask;
113933 }
113934 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
113935   int i;
113936   Bitmask mask = 0;
113937   if( pList ){
113938     for(i=0; i<pList->nExpr; i++){
113939       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
113940     }
113941   }
113942   return mask;
113943 }
113944 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
113945   Bitmask mask = 0;
113946   while( pS ){
113947     SrcList *pSrc = pS->pSrc;
113948     mask |= exprListTableUsage(pMaskSet, pS->pEList);
113949     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
113950     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
113951     mask |= exprTableUsage(pMaskSet, pS->pWhere);
113952     mask |= exprTableUsage(pMaskSet, pS->pHaving);
113953     if( ALWAYS(pSrc!=0) ){
113954       int i;
113955       for(i=0; i<pSrc->nSrc; i++){
113956         mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
113957         mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
113958       }
113959     }
113960     pS = pS->pPrior;
113961   }
113962   return mask;
113963 }
113964 
113965 /*
113966 ** Return TRUE if the given operator is one of the operators that is
113967 ** allowed for an indexable WHERE clause term.  The allowed operators are
113968 ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
113969 */
113970 static int allowedOp(int op){
113971   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
113972   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
113973   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
113974   assert( TK_GE==TK_EQ+4 );
113975   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
113976 }
113977 
113978 /*
113979 ** Commute a comparison operator.  Expressions of the form "X op Y"
113980 ** are converted into "Y op X".
113981 **
113982 ** If left/right precedence rules come into play when determining the
113983 ** collating sequence, then COLLATE operators are adjusted to ensure
113984 ** that the collating sequence does not change.  For example:
113985 ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
113986 ** the left hand side of a comparison overrides any collation sequence
113987 ** attached to the right. For the same reason the EP_Collate flag
113988 ** is not commuted.
113989 */
113990 static void exprCommute(Parse *pParse, Expr *pExpr){
113991   u16 expRight = (pExpr->pRight->flags & EP_Collate);
113992   u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
113993   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
113994   if( expRight==expLeft ){
113995     /* Either X and Y both have COLLATE operator or neither do */
113996     if( expRight ){
113997       /* Both X and Y have COLLATE operators.  Make sure X is always
113998       ** used by clearing the EP_Collate flag from Y. */
113999       pExpr->pRight->flags &= ~EP_Collate;
114000     }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
114001       /* Neither X nor Y have COLLATE operators, but X has a non-default
114002       ** collating sequence.  So add the EP_Collate marker on X to cause
114003       ** it to be searched first. */
114004       pExpr->pLeft->flags |= EP_Collate;
114005     }
114006   }
114007   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
114008   if( pExpr->op>=TK_GT ){
114009     assert( TK_LT==TK_GT+2 );
114010     assert( TK_GE==TK_LE+2 );
114011     assert( TK_GT>TK_EQ );
114012     assert( TK_GT<TK_LE );
114013     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
114014     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
114015   }
114016 }
114017 
114018 /*
114019 ** Translate from TK_xx operator to WO_xx bitmask.
114020 */
114021 static u16 operatorMask(int op){
114022   u16 c;
114023   assert( allowedOp(op) );
114024   if( op==TK_IN ){
114025     c = WO_IN;
114026   }else if( op==TK_ISNULL ){
114027     c = WO_ISNULL;
114028   }else{
114029     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
114030     c = (u16)(WO_EQ<<(op-TK_EQ));
114031   }
114032   assert( op!=TK_ISNULL || c==WO_ISNULL );
114033   assert( op!=TK_IN || c==WO_IN );
114034   assert( op!=TK_EQ || c==WO_EQ );
114035   assert( op!=TK_LT || c==WO_LT );
114036   assert( op!=TK_LE || c==WO_LE );
114037   assert( op!=TK_GT || c==WO_GT );
114038   assert( op!=TK_GE || c==WO_GE );
114039   return c;
114040 }
114041 
114042 /*
114043 ** Advance to the next WhereTerm that matches according to the criteria
114044 ** established when the pScan object was initialized by whereScanInit().
114045 ** Return NULL if there are no more matching WhereTerms.
114046 */
114047 static WhereTerm *whereScanNext(WhereScan *pScan){
114048   int iCur;            /* The cursor on the LHS of the term */
114049   int iColumn;         /* The column on the LHS of the term.  -1 for IPK */
114050   Expr *pX;            /* An expression being tested */
114051   WhereClause *pWC;    /* Shorthand for pScan->pWC */
114052   WhereTerm *pTerm;    /* The term being tested */
114053   int k = pScan->k;    /* Where to start scanning */
114054 
114055   while( pScan->iEquiv<=pScan->nEquiv ){
114056     iCur = pScan->aEquiv[pScan->iEquiv-2];
114057     iColumn = pScan->aEquiv[pScan->iEquiv-1];
114058     while( (pWC = pScan->pWC)!=0 ){
114059       for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
114060         if( pTerm->leftCursor==iCur
114061          && pTerm->u.leftColumn==iColumn
114062          && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
114063         ){
114064           if( (pTerm->eOperator & WO_EQUIV)!=0
114065            && pScan->nEquiv<ArraySize(pScan->aEquiv)
114066           ){
114067             int j;
114068             pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
114069             assert( pX->op==TK_COLUMN );
114070             for(j=0; j<pScan->nEquiv; j+=2){
114071               if( pScan->aEquiv[j]==pX->iTable
114072                && pScan->aEquiv[j+1]==pX->iColumn ){
114073                   break;
114074               }
114075             }
114076             if( j==pScan->nEquiv ){
114077               pScan->aEquiv[j] = pX->iTable;
114078               pScan->aEquiv[j+1] = pX->iColumn;
114079               pScan->nEquiv += 2;
114080             }
114081           }
114082           if( (pTerm->eOperator & pScan->opMask)!=0 ){
114083             /* Verify the affinity and collating sequence match */
114084             if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
114085               CollSeq *pColl;
114086               Parse *pParse = pWC->pWInfo->pParse;
114087               pX = pTerm->pExpr;
114088               if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
114089                 continue;
114090               }
114091               assert(pX->pLeft);
114092               pColl = sqlite3BinaryCompareCollSeq(pParse,
114093                                                   pX->pLeft, pX->pRight);
114094               if( pColl==0 ) pColl = pParse->db->pDfltColl;
114095               if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
114096                 continue;
114097               }
114098             }
114099             if( (pTerm->eOperator & WO_EQ)!=0
114100              && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
114101              && pX->iTable==pScan->aEquiv[0]
114102              && pX->iColumn==pScan->aEquiv[1]
114103             ){
114104               continue;
114105             }
114106             pScan->k = k+1;
114107             return pTerm;
114108           }
114109         }
114110       }
114111       pScan->pWC = pScan->pWC->pOuter;
114112       k = 0;
114113     }
114114     pScan->pWC = pScan->pOrigWC;
114115     k = 0;
114116     pScan->iEquiv += 2;
114117   }
114118   return 0;
114119 }
114120 
114121 /*
114122 ** Initialize a WHERE clause scanner object.  Return a pointer to the
114123 ** first match.  Return NULL if there are no matches.
114124 **
114125 ** The scanner will be searching the WHERE clause pWC.  It will look
114126 ** for terms of the form "X <op> <expr>" where X is column iColumn of table
114127 ** iCur.  The <op> must be one of the operators described by opMask.
114128 **
114129 ** If the search is for X and the WHERE clause contains terms of the
114130 ** form X=Y then this routine might also return terms of the form
114131 ** "Y <op> <expr>".  The number of levels of transitivity is limited,
114132 ** but is enough to handle most commonly occurring SQL statements.
114133 **
114134 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
114135 ** index pIdx.
114136 */
114137 static WhereTerm *whereScanInit(
114138   WhereScan *pScan,       /* The WhereScan object being initialized */
114139   WhereClause *pWC,       /* The WHERE clause to be scanned */
114140   int iCur,               /* Cursor to scan for */
114141   int iColumn,            /* Column to scan for */
114142   u32 opMask,             /* Operator(s) to scan for */
114143   Index *pIdx             /* Must be compatible with this index */
114144 ){
114145   int j;
114146 
114147   /* memset(pScan, 0, sizeof(*pScan)); */
114148   pScan->pOrigWC = pWC;
114149   pScan->pWC = pWC;
114150   if( pIdx && iColumn>=0 ){
114151     pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
114152     for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
114153       if( NEVER(j>pIdx->nColumn) ) return 0;
114154     }
114155     pScan->zCollName = pIdx->azColl[j];
114156   }else{
114157     pScan->idxaff = 0;
114158     pScan->zCollName = 0;
114159   }
114160   pScan->opMask = opMask;
114161   pScan->k = 0;
114162   pScan->aEquiv[0] = iCur;
114163   pScan->aEquiv[1] = iColumn;
114164   pScan->nEquiv = 2;
114165   pScan->iEquiv = 2;
114166   return whereScanNext(pScan);
114167 }
114168 
114169 /*
114170 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
114171 ** where X is a reference to the iColumn of table iCur and <op> is one of
114172 ** the WO_xx operator codes specified by the op parameter.
114173 ** Return a pointer to the term.  Return 0 if not found.
114174 **
114175 ** The term returned might by Y=<expr> if there is another constraint in
114176 ** the WHERE clause that specifies that X=Y.  Any such constraints will be
114177 ** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
114178 ** aEquiv[] array holds X and all its equivalents, with each SQL variable
114179 ** taking up two slots in aEquiv[].  The first slot is for the cursor number
114180 ** and the second is for the column number.  There are 22 slots in aEquiv[]
114181 ** so that means we can look for X plus up to 10 other equivalent values.
114182 ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
114183 ** and ... and A9=A10 and A10=<expr>.
114184 **
114185 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
114186 ** then try for the one with no dependencies on <expr> - in other words where
114187 ** <expr> is a constant expression of some kind.  Only return entries of
114188 ** the form "X <op> Y" where Y is a column in another table if no terms of
114189 ** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
114190 ** exist, try to return a term that does not use WO_EQUIV.
114191 */
114192 static WhereTerm *findTerm(
114193   WhereClause *pWC,     /* The WHERE clause to be searched */
114194   int iCur,             /* Cursor number of LHS */
114195   int iColumn,          /* Column number of LHS */
114196   Bitmask notReady,     /* RHS must not overlap with this mask */
114197   u32 op,               /* Mask of WO_xx values describing operator */
114198   Index *pIdx           /* Must be compatible with this index, if not NULL */
114199 ){
114200   WhereTerm *pResult = 0;
114201   WhereTerm *p;
114202   WhereScan scan;
114203 
114204   p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
114205   while( p ){
114206     if( (p->prereqRight & notReady)==0 ){
114207       if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
114208         return p;
114209       }
114210       if( pResult==0 ) pResult = p;
114211     }
114212     p = whereScanNext(&scan);
114213   }
114214   return pResult;
114215 }
114216 
114217 /* Forward reference */
114218 static void exprAnalyze(SrcList*, WhereClause*, int);
114219 
114220 /*
114221 ** Call exprAnalyze on all terms in a WHERE clause.
114222 */
114223 static void exprAnalyzeAll(
114224   SrcList *pTabList,       /* the FROM clause */
114225   WhereClause *pWC         /* the WHERE clause to be analyzed */
114226 ){
114227   int i;
114228   for(i=pWC->nTerm-1; i>=0; i--){
114229     exprAnalyze(pTabList, pWC, i);
114230   }
114231 }
114232 
114233 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
114234 /*
114235 ** Check to see if the given expression is a LIKE or GLOB operator that
114236 ** can be optimized using inequality constraints.  Return TRUE if it is
114237 ** so and false if not.
114238 **
114239 ** In order for the operator to be optimizible, the RHS must be a string
114240 ** literal that does not begin with a wildcard.
114241 */
114242 static int isLikeOrGlob(
114243   Parse *pParse,    /* Parsing and code generating context */
114244   Expr *pExpr,      /* Test this expression */
114245   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
114246   int *pisComplete, /* True if the only wildcard is % in the last character */
114247   int *pnoCase      /* True if uppercase is equivalent to lowercase */
114248 ){
114249   const char *z = 0;         /* String on RHS of LIKE operator */
114250   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
114251   ExprList *pList;           /* List of operands to the LIKE operator */
114252   int c;                     /* One character in z[] */
114253   int cnt;                   /* Number of non-wildcard prefix characters */
114254   char wc[3];                /* Wildcard characters */
114255   sqlite3 *db = pParse->db;  /* Database connection */
114256   sqlite3_value *pVal = 0;
114257   int op;                    /* Opcode of pRight */
114258 
114259   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
114260     return 0;
114261   }
114262 #ifdef SQLITE_EBCDIC
114263   if( *pnoCase ) return 0;
114264 #endif
114265   pList = pExpr->x.pList;
114266   pLeft = pList->a[1].pExpr;
114267   if( pLeft->op!=TK_COLUMN
114268    || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
114269    || IsVirtual(pLeft->pTab)
114270   ){
114271     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
114272     ** be the name of an indexed column with TEXT affinity. */
114273     return 0;
114274   }
114275   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
114276 
114277   pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
114278   op = pRight->op;
114279   if( op==TK_VARIABLE ){
114280     Vdbe *pReprepare = pParse->pReprepare;
114281     int iCol = pRight->iColumn;
114282     pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
114283     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
114284       z = (char *)sqlite3_value_text(pVal);
114285     }
114286     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
114287     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
114288   }else if( op==TK_STRING ){
114289     z = pRight->u.zToken;
114290   }
114291   if( z ){
114292     cnt = 0;
114293     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
114294       cnt++;
114295     }
114296     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
114297       Expr *pPrefix;
114298       *pisComplete = c==wc[0] && z[cnt+1]==0;
114299       pPrefix = sqlite3Expr(db, TK_STRING, z);
114300       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
114301       *ppPrefix = pPrefix;
114302       if( op==TK_VARIABLE ){
114303         Vdbe *v = pParse->pVdbe;
114304         sqlite3VdbeSetVarmask(v, pRight->iColumn);
114305         if( *pisComplete && pRight->u.zToken[1] ){
114306           /* If the rhs of the LIKE expression is a variable, and the current
114307           ** value of the variable means there is no need to invoke the LIKE
114308           ** function, then no OP_Variable will be added to the program.
114309           ** This causes problems for the sqlite3_bind_parameter_name()
114310           ** API. To work around them, add a dummy OP_Variable here.
114311           */
114312           int r1 = sqlite3GetTempReg(pParse);
114313           sqlite3ExprCodeTarget(pParse, pRight, r1);
114314           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
114315           sqlite3ReleaseTempReg(pParse, r1);
114316         }
114317       }
114318     }else{
114319       z = 0;
114320     }
114321   }
114322 
114323   sqlite3ValueFree(pVal);
114324   return (z!=0);
114325 }
114326 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
114327 
114328 
114329 #ifndef SQLITE_OMIT_VIRTUALTABLE
114330 /*
114331 ** Check to see if the given expression is of the form
114332 **
114333 **         column MATCH expr
114334 **
114335 ** If it is then return TRUE.  If not, return FALSE.
114336 */
114337 static int isMatchOfColumn(
114338   Expr *pExpr      /* Test this expression */
114339 ){
114340   ExprList *pList;
114341 
114342   if( pExpr->op!=TK_FUNCTION ){
114343     return 0;
114344   }
114345   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
114346     return 0;
114347   }
114348   pList = pExpr->x.pList;
114349   if( pList->nExpr!=2 ){
114350     return 0;
114351   }
114352   if( pList->a[1].pExpr->op != TK_COLUMN ){
114353     return 0;
114354   }
114355   return 1;
114356 }
114357 #endif /* SQLITE_OMIT_VIRTUALTABLE */
114358 
114359 /*
114360 ** If the pBase expression originated in the ON or USING clause of
114361 ** a join, then transfer the appropriate markings over to derived.
114362 */
114363 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
114364   if( pDerived ){
114365     pDerived->flags |= pBase->flags & EP_FromJoin;
114366     pDerived->iRightJoinTable = pBase->iRightJoinTable;
114367   }
114368 }
114369 
114370 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
114371 /*
114372 ** Analyze a term that consists of two or more OR-connected
114373 ** subterms.  So in:
114374 **
114375 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
114376 **                          ^^^^^^^^^^^^^^^^^^^^
114377 **
114378 ** This routine analyzes terms such as the middle term in the above example.
114379 ** A WhereOrTerm object is computed and attached to the term under
114380 ** analysis, regardless of the outcome of the analysis.  Hence:
114381 **
114382 **     WhereTerm.wtFlags   |=  TERM_ORINFO
114383 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
114384 **
114385 ** The term being analyzed must have two or more of OR-connected subterms.
114386 ** A single subterm might be a set of AND-connected sub-subterms.
114387 ** Examples of terms under analysis:
114388 **
114389 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
114390 **     (B)     x=expr1 OR expr2=x OR x=expr3
114391 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
114392 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
114393 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
114394 **
114395 ** CASE 1:
114396 **
114397 ** If all subterms are of the form T.C=expr for some single column of C and
114398 ** a single table T (as shown in example B above) then create a new virtual
114399 ** term that is an equivalent IN expression.  In other words, if the term
114400 ** being analyzed is:
114401 **
114402 **      x = expr1  OR  expr2 = x  OR  x = expr3
114403 **
114404 ** then create a new virtual term like this:
114405 **
114406 **      x IN (expr1,expr2,expr3)
114407 **
114408 ** CASE 2:
114409 **
114410 ** If all subterms are indexable by a single table T, then set
114411 **
114412 **     WhereTerm.eOperator              =  WO_OR
114413 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
114414 **
114415 ** A subterm is "indexable" if it is of the form
114416 ** "T.C <op> <expr>" where C is any column of table T and
114417 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
114418 ** A subterm is also indexable if it is an AND of two or more
114419 ** subsubterms at least one of which is indexable.  Indexable AND
114420 ** subterms have their eOperator set to WO_AND and they have
114421 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
114422 **
114423 ** From another point of view, "indexable" means that the subterm could
114424 ** potentially be used with an index if an appropriate index exists.
114425 ** This analysis does not consider whether or not the index exists; that
114426 ** is decided elsewhere.  This analysis only looks at whether subterms
114427 ** appropriate for indexing exist.
114428 **
114429 ** All examples A through E above satisfy case 2.  But if a term
114430 ** also satisfies case 1 (such as B) we know that the optimizer will
114431 ** always prefer case 1, so in that case we pretend that case 2 is not
114432 ** satisfied.
114433 **
114434 ** It might be the case that multiple tables are indexable.  For example,
114435 ** (E) above is indexable on tables P, Q, and R.
114436 **
114437 ** Terms that satisfy case 2 are candidates for lookup by using
114438 ** separate indices to find rowids for each subterm and composing
114439 ** the union of all rowids using a RowSet object.  This is similar
114440 ** to "bitmap indices" in other database engines.
114441 **
114442 ** OTHERWISE:
114443 **
114444 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
114445 ** zero.  This term is not useful for search.
114446 */
114447 static void exprAnalyzeOrTerm(
114448   SrcList *pSrc,            /* the FROM clause */
114449   WhereClause *pWC,         /* the complete WHERE clause */
114450   int idxTerm               /* Index of the OR-term to be analyzed */
114451 ){
114452   WhereInfo *pWInfo = pWC->pWInfo;        /* WHERE clause processing context */
114453   Parse *pParse = pWInfo->pParse;         /* Parser context */
114454   sqlite3 *db = pParse->db;               /* Database connection */
114455   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
114456   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
114457   int i;                                  /* Loop counters */
114458   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
114459   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
114460   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
114461   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
114462   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
114463 
114464   /*
114465   ** Break the OR clause into its separate subterms.  The subterms are
114466   ** stored in a WhereClause structure containing within the WhereOrInfo
114467   ** object that is attached to the original OR clause term.
114468   */
114469   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
114470   assert( pExpr->op==TK_OR );
114471   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
114472   if( pOrInfo==0 ) return;
114473   pTerm->wtFlags |= TERM_ORINFO;
114474   pOrWc = &pOrInfo->wc;
114475   whereClauseInit(pOrWc, pWInfo);
114476   whereSplit(pOrWc, pExpr, TK_OR);
114477   exprAnalyzeAll(pSrc, pOrWc);
114478   if( db->mallocFailed ) return;
114479   assert( pOrWc->nTerm>=2 );
114480 
114481   /*
114482   ** Compute the set of tables that might satisfy cases 1 or 2.
114483   */
114484   indexable = ~(Bitmask)0;
114485   chngToIN = ~(Bitmask)0;
114486   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
114487     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
114488       WhereAndInfo *pAndInfo;
114489       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
114490       chngToIN = 0;
114491       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
114492       if( pAndInfo ){
114493         WhereClause *pAndWC;
114494         WhereTerm *pAndTerm;
114495         int j;
114496         Bitmask b = 0;
114497         pOrTerm->u.pAndInfo = pAndInfo;
114498         pOrTerm->wtFlags |= TERM_ANDINFO;
114499         pOrTerm->eOperator = WO_AND;
114500         pAndWC = &pAndInfo->wc;
114501         whereClauseInit(pAndWC, pWC->pWInfo);
114502         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
114503         exprAnalyzeAll(pSrc, pAndWC);
114504         pAndWC->pOuter = pWC;
114505         testcase( db->mallocFailed );
114506         if( !db->mallocFailed ){
114507           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
114508             assert( pAndTerm->pExpr );
114509             if( allowedOp(pAndTerm->pExpr->op) ){
114510               b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
114511             }
114512           }
114513         }
114514         indexable &= b;
114515       }
114516     }else if( pOrTerm->wtFlags & TERM_COPIED ){
114517       /* Skip this term for now.  We revisit it when we process the
114518       ** corresponding TERM_VIRTUAL term */
114519     }else{
114520       Bitmask b;
114521       b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
114522       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
114523         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
114524         b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
114525       }
114526       indexable &= b;
114527       if( (pOrTerm->eOperator & WO_EQ)==0 ){
114528         chngToIN = 0;
114529       }else{
114530         chngToIN &= b;
114531       }
114532     }
114533   }
114534 
114535   /*
114536   ** Record the set of tables that satisfy case 2.  The set might be
114537   ** empty.
114538   */
114539   pOrInfo->indexable = indexable;
114540   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
114541 
114542   /*
114543   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
114544   ** we have to do some additional checking to see if case 1 really
114545   ** is satisfied.
114546   **
114547   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
114548   ** that there is no possibility of transforming the OR clause into an
114549   ** IN operator because one or more terms in the OR clause contain
114550   ** something other than == on a column in the single table.  The 1-bit
114551   ** case means that every term of the OR clause is of the form
114552   ** "table.column=expr" for some single table.  The one bit that is set
114553   ** will correspond to the common table.  We still need to check to make
114554   ** sure the same column is used on all terms.  The 2-bit case is when
114555   ** the all terms are of the form "table1.column=table2.column".  It
114556   ** might be possible to form an IN operator with either table1.column
114557   ** or table2.column as the LHS if either is common to every term of
114558   ** the OR clause.
114559   **
114560   ** Note that terms of the form "table.column1=table.column2" (the
114561   ** same table on both sizes of the ==) cannot be optimized.
114562   */
114563   if( chngToIN ){
114564     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
114565     int iColumn = -1;         /* Column index on lhs of IN operator */
114566     int iCursor = -1;         /* Table cursor common to all terms */
114567     int j = 0;                /* Loop counter */
114568 
114569     /* Search for a table and column that appears on one side or the
114570     ** other of the == operator in every subterm.  That table and column
114571     ** will be recorded in iCursor and iColumn.  There might not be any
114572     ** such table and column.  Set okToChngToIN if an appropriate table
114573     ** and column is found but leave okToChngToIN false if not found.
114574     */
114575     for(j=0; j<2 && !okToChngToIN; j++){
114576       pOrTerm = pOrWc->a;
114577       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
114578         assert( pOrTerm->eOperator & WO_EQ );
114579         pOrTerm->wtFlags &= ~TERM_OR_OK;
114580         if( pOrTerm->leftCursor==iCursor ){
114581           /* This is the 2-bit case and we are on the second iteration and
114582           ** current term is from the first iteration.  So skip this term. */
114583           assert( j==1 );
114584           continue;
114585         }
114586         if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
114587           /* This term must be of the form t1.a==t2.b where t2 is in the
114588           ** chngToIN set but t1 is not.  This term will be either preceded
114589           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
114590           ** and use its inversion. */
114591           testcase( pOrTerm->wtFlags & TERM_COPIED );
114592           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
114593           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
114594           continue;
114595         }
114596         iColumn = pOrTerm->u.leftColumn;
114597         iCursor = pOrTerm->leftCursor;
114598         break;
114599       }
114600       if( i<0 ){
114601         /* No candidate table+column was found.  This can only occur
114602         ** on the second iteration */
114603         assert( j==1 );
114604         assert( IsPowerOfTwo(chngToIN) );
114605         assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
114606         break;
114607       }
114608       testcase( j==1 );
114609 
114610       /* We have found a candidate table and column.  Check to see if that
114611       ** table and column is common to every term in the OR clause */
114612       okToChngToIN = 1;
114613       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
114614         assert( pOrTerm->eOperator & WO_EQ );
114615         if( pOrTerm->leftCursor!=iCursor ){
114616           pOrTerm->wtFlags &= ~TERM_OR_OK;
114617         }else if( pOrTerm->u.leftColumn!=iColumn ){
114618           okToChngToIN = 0;
114619         }else{
114620           int affLeft, affRight;
114621           /* If the right-hand side is also a column, then the affinities
114622           ** of both right and left sides must be such that no type
114623           ** conversions are required on the right.  (Ticket #2249)
114624           */
114625           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
114626           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
114627           if( affRight!=0 && affRight!=affLeft ){
114628             okToChngToIN = 0;
114629           }else{
114630             pOrTerm->wtFlags |= TERM_OR_OK;
114631           }
114632         }
114633       }
114634     }
114635 
114636     /* At this point, okToChngToIN is true if original pTerm satisfies
114637     ** case 1.  In that case, construct a new virtual term that is
114638     ** pTerm converted into an IN operator.
114639     */
114640     if( okToChngToIN ){
114641       Expr *pDup;            /* A transient duplicate expression */
114642       ExprList *pList = 0;   /* The RHS of the IN operator */
114643       Expr *pLeft = 0;       /* The LHS of the IN operator */
114644       Expr *pNew;            /* The complete IN operator */
114645 
114646       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
114647         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
114648         assert( pOrTerm->eOperator & WO_EQ );
114649         assert( pOrTerm->leftCursor==iCursor );
114650         assert( pOrTerm->u.leftColumn==iColumn );
114651         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
114652         pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
114653         pLeft = pOrTerm->pExpr->pLeft;
114654       }
114655       assert( pLeft!=0 );
114656       pDup = sqlite3ExprDup(db, pLeft, 0);
114657       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
114658       if( pNew ){
114659         int idxNew;
114660         transferJoinMarkings(pNew, pExpr);
114661         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
114662         pNew->x.pList = pList;
114663         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
114664         testcase( idxNew==0 );
114665         exprAnalyze(pSrc, pWC, idxNew);
114666         pTerm = &pWC->a[idxTerm];
114667         pWC->a[idxNew].iParent = idxTerm;
114668         pTerm->nChild = 1;
114669       }else{
114670         sqlite3ExprListDelete(db, pList);
114671       }
114672       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
114673     }
114674   }
114675 }
114676 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
114677 
114678 /*
114679 ** The input to this routine is an WhereTerm structure with only the
114680 ** "pExpr" field filled in.  The job of this routine is to analyze the
114681 ** subexpression and populate all the other fields of the WhereTerm
114682 ** structure.
114683 **
114684 ** If the expression is of the form "<expr> <op> X" it gets commuted
114685 ** to the standard form of "X <op> <expr>".
114686 **
114687 ** If the expression is of the form "X <op> Y" where both X and Y are
114688 ** columns, then the original expression is unchanged and a new virtual
114689 ** term of the form "Y <op> X" is added to the WHERE clause and
114690 ** analyzed separately.  The original term is marked with TERM_COPIED
114691 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
114692 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
114693 ** is a commuted copy of a prior term.)  The original term has nChild=1
114694 ** and the copy has idxParent set to the index of the original term.
114695 */
114696 static void exprAnalyze(
114697   SrcList *pSrc,            /* the FROM clause */
114698   WhereClause *pWC,         /* the WHERE clause */
114699   int idxTerm               /* Index of the term to be analyzed */
114700 ){
114701   WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
114702   WhereTerm *pTerm;                /* The term to be analyzed */
114703   WhereMaskSet *pMaskSet;          /* Set of table index masks */
114704   Expr *pExpr;                     /* The expression to be analyzed */
114705   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
114706   Bitmask prereqAll;               /* Prerequesites of pExpr */
114707   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
114708   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
114709   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
114710   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
114711   int op;                          /* Top-level operator.  pExpr->op */
114712   Parse *pParse = pWInfo->pParse;  /* Parsing context */
114713   sqlite3 *db = pParse->db;        /* Database connection */
114714 
114715   if( db->mallocFailed ){
114716     return;
114717   }
114718   pTerm = &pWC->a[idxTerm];
114719   pMaskSet = &pWInfo->sMaskSet;
114720   pExpr = pTerm->pExpr;
114721   assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
114722   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
114723   op = pExpr->op;
114724   if( op==TK_IN ){
114725     assert( pExpr->pRight==0 );
114726     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
114727       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
114728     }else{
114729       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
114730     }
114731   }else if( op==TK_ISNULL ){
114732     pTerm->prereqRight = 0;
114733   }else{
114734     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
114735   }
114736   prereqAll = exprTableUsage(pMaskSet, pExpr);
114737   if( ExprHasProperty(pExpr, EP_FromJoin) ){
114738     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
114739     prereqAll |= x;
114740     extraRight = x-1;  /* ON clause terms may not be used with an index
114741                        ** on left table of a LEFT JOIN.  Ticket #3015 */
114742   }
114743   pTerm->prereqAll = prereqAll;
114744   pTerm->leftCursor = -1;
114745   pTerm->iParent = -1;
114746   pTerm->eOperator = 0;
114747   if( allowedOp(op) ){
114748     Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
114749     Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
114750     u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
114751     if( pLeft->op==TK_COLUMN ){
114752       pTerm->leftCursor = pLeft->iTable;
114753       pTerm->u.leftColumn = pLeft->iColumn;
114754       pTerm->eOperator = operatorMask(op) & opMask;
114755     }
114756     if( pRight && pRight->op==TK_COLUMN ){
114757       WhereTerm *pNew;
114758       Expr *pDup;
114759       u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
114760       if( pTerm->leftCursor>=0 ){
114761         int idxNew;
114762         pDup = sqlite3ExprDup(db, pExpr, 0);
114763         if( db->mallocFailed ){
114764           sqlite3ExprDelete(db, pDup);
114765           return;
114766         }
114767         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
114768         if( idxNew==0 ) return;
114769         pNew = &pWC->a[idxNew];
114770         pNew->iParent = idxTerm;
114771         pTerm = &pWC->a[idxTerm];
114772         pTerm->nChild = 1;
114773         pTerm->wtFlags |= TERM_COPIED;
114774         if( pExpr->op==TK_EQ
114775          && !ExprHasProperty(pExpr, EP_FromJoin)
114776          && OptimizationEnabled(db, SQLITE_Transitive)
114777         ){
114778           pTerm->eOperator |= WO_EQUIV;
114779           eExtraOp = WO_EQUIV;
114780         }
114781       }else{
114782         pDup = pExpr;
114783         pNew = pTerm;
114784       }
114785       exprCommute(pParse, pDup);
114786       pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
114787       pNew->leftCursor = pLeft->iTable;
114788       pNew->u.leftColumn = pLeft->iColumn;
114789       testcase( (prereqLeft | extraRight) != prereqLeft );
114790       pNew->prereqRight = prereqLeft | extraRight;
114791       pNew->prereqAll = prereqAll;
114792       pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
114793     }
114794   }
114795 
114796 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
114797   /* If a term is the BETWEEN operator, create two new virtual terms
114798   ** that define the range that the BETWEEN implements.  For example:
114799   **
114800   **      a BETWEEN b AND c
114801   **
114802   ** is converted into:
114803   **
114804   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
114805   **
114806   ** The two new terms are added onto the end of the WhereClause object.
114807   ** The new terms are "dynamic" and are children of the original BETWEEN
114808   ** term.  That means that if the BETWEEN term is coded, the children are
114809   ** skipped.  Or, if the children are satisfied by an index, the original
114810   ** BETWEEN term is skipped.
114811   */
114812   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
114813     ExprList *pList = pExpr->x.pList;
114814     int i;
114815     static const u8 ops[] = {TK_GE, TK_LE};
114816     assert( pList!=0 );
114817     assert( pList->nExpr==2 );
114818     for(i=0; i<2; i++){
114819       Expr *pNewExpr;
114820       int idxNew;
114821       pNewExpr = sqlite3PExpr(pParse, ops[i],
114822                              sqlite3ExprDup(db, pExpr->pLeft, 0),
114823                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
114824       transferJoinMarkings(pNewExpr, pExpr);
114825       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
114826       testcase( idxNew==0 );
114827       exprAnalyze(pSrc, pWC, idxNew);
114828       pTerm = &pWC->a[idxTerm];
114829       pWC->a[idxNew].iParent = idxTerm;
114830     }
114831     pTerm->nChild = 2;
114832   }
114833 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
114834 
114835 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
114836   /* Analyze a term that is composed of two or more subterms connected by
114837   ** an OR operator.
114838   */
114839   else if( pExpr->op==TK_OR ){
114840     assert( pWC->op==TK_AND );
114841     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
114842     pTerm = &pWC->a[idxTerm];
114843   }
114844 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
114845 
114846 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
114847   /* Add constraints to reduce the search space on a LIKE or GLOB
114848   ** operator.
114849   **
114850   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
114851   **
114852   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
114853   **
114854   ** The last character of the prefix "abc" is incremented to form the
114855   ** termination condition "abd".
114856   */
114857   if( pWC->op==TK_AND
114858    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
114859   ){
114860     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
114861     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
114862     Expr *pNewExpr1;
114863     Expr *pNewExpr2;
114864     int idxNew1;
114865     int idxNew2;
114866     Token sCollSeqName;  /* Name of collating sequence */
114867 
114868     pLeft = pExpr->x.pList->a[1].pExpr;
114869     pStr2 = sqlite3ExprDup(db, pStr1, 0);
114870     if( !db->mallocFailed ){
114871       u8 c, *pC;       /* Last character before the first wildcard */
114872       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
114873       c = *pC;
114874       if( noCase ){
114875         /* The point is to increment the last character before the first
114876         ** wildcard.  But if we increment '@', that will push it into the
114877         ** alphabetic range where case conversions will mess up the
114878         ** inequality.  To avoid this, make sure to also run the full
114879         ** LIKE on all candidate expressions by clearing the isComplete flag
114880         */
114881         if( c=='A'-1 ) isComplete = 0;
114882         c = sqlite3UpperToLower[c];
114883       }
114884       *pC = c + 1;
114885     }
114886     sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
114887     sCollSeqName.n = 6;
114888     pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
114889     pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
114890            sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
114891            pStr1, 0);
114892     transferJoinMarkings(pNewExpr1, pExpr);
114893     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
114894     testcase( idxNew1==0 );
114895     exprAnalyze(pSrc, pWC, idxNew1);
114896     pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
114897     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
114898            sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
114899            pStr2, 0);
114900     transferJoinMarkings(pNewExpr2, pExpr);
114901     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
114902     testcase( idxNew2==0 );
114903     exprAnalyze(pSrc, pWC, idxNew2);
114904     pTerm = &pWC->a[idxTerm];
114905     if( isComplete ){
114906       pWC->a[idxNew1].iParent = idxTerm;
114907       pWC->a[idxNew2].iParent = idxTerm;
114908       pTerm->nChild = 2;
114909     }
114910   }
114911 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
114912 
114913 #ifndef SQLITE_OMIT_VIRTUALTABLE
114914   /* Add a WO_MATCH auxiliary term to the constraint set if the
114915   ** current expression is of the form:  column MATCH expr.
114916   ** This information is used by the xBestIndex methods of
114917   ** virtual tables.  The native query optimizer does not attempt
114918   ** to do anything with MATCH functions.
114919   */
114920   if( isMatchOfColumn(pExpr) ){
114921     int idxNew;
114922     Expr *pRight, *pLeft;
114923     WhereTerm *pNewTerm;
114924     Bitmask prereqColumn, prereqExpr;
114925 
114926     pRight = pExpr->x.pList->a[0].pExpr;
114927     pLeft = pExpr->x.pList->a[1].pExpr;
114928     prereqExpr = exprTableUsage(pMaskSet, pRight);
114929     prereqColumn = exprTableUsage(pMaskSet, pLeft);
114930     if( (prereqExpr & prereqColumn)==0 ){
114931       Expr *pNewExpr;
114932       pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
114933                               0, sqlite3ExprDup(db, pRight, 0), 0);
114934       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
114935       testcase( idxNew==0 );
114936       pNewTerm = &pWC->a[idxNew];
114937       pNewTerm->prereqRight = prereqExpr;
114938       pNewTerm->leftCursor = pLeft->iTable;
114939       pNewTerm->u.leftColumn = pLeft->iColumn;
114940       pNewTerm->eOperator = WO_MATCH;
114941       pNewTerm->iParent = idxTerm;
114942       pTerm = &pWC->a[idxTerm];
114943       pTerm->nChild = 1;
114944       pTerm->wtFlags |= TERM_COPIED;
114945       pNewTerm->prereqAll = pTerm->prereqAll;
114946     }
114947   }
114948 #endif /* SQLITE_OMIT_VIRTUALTABLE */
114949 
114950 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
114951   /* When sqlite_stat3 histogram data is available an operator of the
114952   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
114953   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
114954   ** virtual term of that form.
114955   **
114956   ** Note that the virtual term must be tagged with TERM_VNULL.  This
114957   ** TERM_VNULL tag will suppress the not-null check at the beginning
114958   ** of the loop.  Without the TERM_VNULL flag, the not-null check at
114959   ** the start of the loop will prevent any results from being returned.
114960   */
114961   if( pExpr->op==TK_NOTNULL
114962    && pExpr->pLeft->op==TK_COLUMN
114963    && pExpr->pLeft->iColumn>=0
114964    && OptimizationEnabled(db, SQLITE_Stat3)
114965   ){
114966     Expr *pNewExpr;
114967     Expr *pLeft = pExpr->pLeft;
114968     int idxNew;
114969     WhereTerm *pNewTerm;
114970 
114971     pNewExpr = sqlite3PExpr(pParse, TK_GT,
114972                             sqlite3ExprDup(db, pLeft, 0),
114973                             sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
114974 
114975     idxNew = whereClauseInsert(pWC, pNewExpr,
114976                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
114977     if( idxNew ){
114978       pNewTerm = &pWC->a[idxNew];
114979       pNewTerm->prereqRight = 0;
114980       pNewTerm->leftCursor = pLeft->iTable;
114981       pNewTerm->u.leftColumn = pLeft->iColumn;
114982       pNewTerm->eOperator = WO_GT;
114983       pNewTerm->iParent = idxTerm;
114984       pTerm = &pWC->a[idxTerm];
114985       pTerm->nChild = 1;
114986       pTerm->wtFlags |= TERM_COPIED;
114987       pNewTerm->prereqAll = pTerm->prereqAll;
114988     }
114989   }
114990 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
114991 
114992   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
114993   ** an index for tables to the left of the join.
114994   */
114995   pTerm->prereqRight |= extraRight;
114996 }
114997 
114998 /*
114999 ** This function searches pList for an entry that matches the iCol-th column
115000 ** of index pIdx.
115001 **
115002 ** If such an expression is found, its index in pList->a[] is returned. If
115003 ** no expression is found, -1 is returned.
115004 */
115005 static int findIndexCol(
115006   Parse *pParse,                  /* Parse context */
115007   ExprList *pList,                /* Expression list to search */
115008   int iBase,                      /* Cursor for table associated with pIdx */
115009   Index *pIdx,                    /* Index to match column of */
115010   int iCol                        /* Column of index to match */
115011 ){
115012   int i;
115013   const char *zColl = pIdx->azColl[iCol];
115014 
115015   for(i=0; i<pList->nExpr; i++){
115016     Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
115017     if( p->op==TK_COLUMN
115018      && p->iColumn==pIdx->aiColumn[iCol]
115019      && p->iTable==iBase
115020     ){
115021       CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
115022       if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
115023         return i;
115024       }
115025     }
115026   }
115027 
115028   return -1;
115029 }
115030 
115031 /*
115032 ** Return true if the DISTINCT expression-list passed as the third argument
115033 ** is redundant.
115034 **
115035 ** A DISTINCT list is redundant if the database contains some subset of
115036 ** columns that are unique and non-null.
115037 */
115038 static int isDistinctRedundant(
115039   Parse *pParse,            /* Parsing context */
115040   SrcList *pTabList,        /* The FROM clause */
115041   WhereClause *pWC,         /* The WHERE clause */
115042   ExprList *pDistinct       /* The result set that needs to be DISTINCT */
115043 ){
115044   Table *pTab;
115045   Index *pIdx;
115046   int i;
115047   int iBase;
115048 
115049   /* If there is more than one table or sub-select in the FROM clause of
115050   ** this query, then it will not be possible to show that the DISTINCT
115051   ** clause is redundant. */
115052   if( pTabList->nSrc!=1 ) return 0;
115053   iBase = pTabList->a[0].iCursor;
115054   pTab = pTabList->a[0].pTab;
115055 
115056   /* If any of the expressions is an IPK column on table iBase, then return
115057   ** true. Note: The (p->iTable==iBase) part of this test may be false if the
115058   ** current SELECT is a correlated sub-query.
115059   */
115060   for(i=0; i<pDistinct->nExpr; i++){
115061     Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
115062     if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
115063   }
115064 
115065   /* Loop through all indices on the table, checking each to see if it makes
115066   ** the DISTINCT qualifier redundant. It does so if:
115067   **
115068   **   1. The index is itself UNIQUE, and
115069   **
115070   **   2. All of the columns in the index are either part of the pDistinct
115071   **      list, or else the WHERE clause contains a term of the form "col=X",
115072   **      where X is a constant value. The collation sequences of the
115073   **      comparison and select-list expressions must match those of the index.
115074   **
115075   **   3. All of those index columns for which the WHERE clause does not
115076   **      contain a "col=X" term are subject to a NOT NULL constraint.
115077   */
115078   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
115079     if( !IsUniqueIndex(pIdx) ) continue;
115080     for(i=0; i<pIdx->nKeyCol; i++){
115081       i16 iCol = pIdx->aiColumn[i];
115082       if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
115083         int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
115084         if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
115085           break;
115086         }
115087       }
115088     }
115089     if( i==pIdx->nKeyCol ){
115090       /* This index implies that the DISTINCT qualifier is redundant. */
115091       return 1;
115092     }
115093   }
115094 
115095   return 0;
115096 }
115097 
115098 
115099 /*
115100 ** Estimate the logarithm of the input value to base 2.
115101 */
115102 static LogEst estLog(LogEst N){
115103   return N<=10 ? 0 : sqlite3LogEst(N) - 33;
115104 }
115105 
115106 /*
115107 ** Two routines for printing the content of an sqlite3_index_info
115108 ** structure.  Used for testing and debugging only.  If neither
115109 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
115110 ** are no-ops.
115111 */
115112 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
115113 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
115114   int i;
115115   if( !sqlite3WhereTrace ) return;
115116   for(i=0; i<p->nConstraint; i++){
115117     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
115118        i,
115119        p->aConstraint[i].iColumn,
115120        p->aConstraint[i].iTermOffset,
115121        p->aConstraint[i].op,
115122        p->aConstraint[i].usable);
115123   }
115124   for(i=0; i<p->nOrderBy; i++){
115125     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
115126        i,
115127        p->aOrderBy[i].iColumn,
115128        p->aOrderBy[i].desc);
115129   }
115130 }
115131 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
115132   int i;
115133   if( !sqlite3WhereTrace ) return;
115134   for(i=0; i<p->nConstraint; i++){
115135     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
115136        i,
115137        p->aConstraintUsage[i].argvIndex,
115138        p->aConstraintUsage[i].omit);
115139   }
115140   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
115141   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
115142   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
115143   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
115144   sqlite3DebugPrintf("  estimatedRows=%lld\n", p->estimatedRows);
115145 }
115146 #else
115147 #define TRACE_IDX_INPUTS(A)
115148 #define TRACE_IDX_OUTPUTS(A)
115149 #endif
115150 
115151 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
115152 /*
115153 ** Return TRUE if the WHERE clause term pTerm is of a form where it
115154 ** could be used with an index to access pSrc, assuming an appropriate
115155 ** index existed.
115156 */
115157 static int termCanDriveIndex(
115158   WhereTerm *pTerm,              /* WHERE clause term to check */
115159   struct SrcList_item *pSrc,     /* Table we are trying to access */
115160   Bitmask notReady               /* Tables in outer loops of the join */
115161 ){
115162   char aff;
115163   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
115164   if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
115165   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
115166   if( pTerm->u.leftColumn<0 ) return 0;
115167   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
115168   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
115169   return 1;
115170 }
115171 #endif
115172 
115173 
115174 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
115175 /*
115176 ** Generate code to construct the Index object for an automatic index
115177 ** and to set up the WhereLevel object pLevel so that the code generator
115178 ** makes use of the automatic index.
115179 */
115180 static void constructAutomaticIndex(
115181   Parse *pParse,              /* The parsing context */
115182   WhereClause *pWC,           /* The WHERE clause */
115183   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
115184   Bitmask notReady,           /* Mask of cursors that are not available */
115185   WhereLevel *pLevel          /* Write new index here */
115186 ){
115187   int nKeyCol;                /* Number of columns in the constructed index */
115188   WhereTerm *pTerm;           /* A single term of the WHERE clause */
115189   WhereTerm *pWCEnd;          /* End of pWC->a[] */
115190   Index *pIdx;                /* Object describing the transient index */
115191   Vdbe *v;                    /* Prepared statement under construction */
115192   int addrInit;               /* Address of the initialization bypass jump */
115193   Table *pTable;              /* The table being indexed */
115194   int addrTop;                /* Top of the index fill loop */
115195   int regRecord;              /* Register holding an index record */
115196   int n;                      /* Column counter */
115197   int i;                      /* Loop counter */
115198   int mxBitCol;               /* Maximum column in pSrc->colUsed */
115199   CollSeq *pColl;             /* Collating sequence to on a column */
115200   WhereLoop *pLoop;           /* The Loop object */
115201   char *zNotUsed;             /* Extra space on the end of pIdx */
115202   Bitmask idxCols;            /* Bitmap of columns used for indexing */
115203   Bitmask extraCols;          /* Bitmap of additional columns */
115204   u8 sentWarning = 0;         /* True if a warnning has been issued */
115205 
115206   /* Generate code to skip over the creation and initialization of the
115207   ** transient index on 2nd and subsequent iterations of the loop. */
115208   v = pParse->pVdbe;
115209   assert( v!=0 );
115210   addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
115211 
115212   /* Count the number of columns that will be added to the index
115213   ** and used to match WHERE clause constraints */
115214   nKeyCol = 0;
115215   pTable = pSrc->pTab;
115216   pWCEnd = &pWC->a[pWC->nTerm];
115217   pLoop = pLevel->pWLoop;
115218   idxCols = 0;
115219   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
115220     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
115221       int iCol = pTerm->u.leftColumn;
115222       Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
115223       testcase( iCol==BMS );
115224       testcase( iCol==BMS-1 );
115225       if( !sentWarning ){
115226         sqlite3_log(SQLITE_WARNING_AUTOINDEX,
115227             "automatic index on %s(%s)", pTable->zName,
115228             pTable->aCol[iCol].zName);
115229         sentWarning = 1;
115230       }
115231       if( (idxCols & cMask)==0 ){
115232         if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ) return;
115233         pLoop->aLTerm[nKeyCol++] = pTerm;
115234         idxCols |= cMask;
115235       }
115236     }
115237   }
115238   assert( nKeyCol>0 );
115239   pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
115240   pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
115241                      | WHERE_AUTO_INDEX;
115242 
115243   /* Count the number of additional columns needed to create a
115244   ** covering index.  A "covering index" is an index that contains all
115245   ** columns that are needed by the query.  With a covering index, the
115246   ** original table never needs to be accessed.  Automatic indices must
115247   ** be a covering index because the index will not be updated if the
115248   ** original table changes and the index and table cannot both be used
115249   ** if they go out of sync.
115250   */
115251   extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
115252   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
115253   testcase( pTable->nCol==BMS-1 );
115254   testcase( pTable->nCol==BMS-2 );
115255   for(i=0; i<mxBitCol; i++){
115256     if( extraCols & MASKBIT(i) ) nKeyCol++;
115257   }
115258   if( pSrc->colUsed & MASKBIT(BMS-1) ){
115259     nKeyCol += pTable->nCol - BMS + 1;
115260   }
115261   pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
115262 
115263   /* Construct the Index object to describe this index */
115264   pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
115265   if( pIdx==0 ) return;
115266   pLoop->u.btree.pIndex = pIdx;
115267   pIdx->zName = "auto-index";
115268   pIdx->pTable = pTable;
115269   n = 0;
115270   idxCols = 0;
115271   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
115272     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
115273       int iCol = pTerm->u.leftColumn;
115274       Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
115275       testcase( iCol==BMS-1 );
115276       testcase( iCol==BMS );
115277       if( (idxCols & cMask)==0 ){
115278         Expr *pX = pTerm->pExpr;
115279         idxCols |= cMask;
115280         pIdx->aiColumn[n] = pTerm->u.leftColumn;
115281         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
115282         pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
115283         n++;
115284       }
115285     }
115286   }
115287   assert( (u32)n==pLoop->u.btree.nEq );
115288 
115289   /* Add additional columns needed to make the automatic index into
115290   ** a covering index */
115291   for(i=0; i<mxBitCol; i++){
115292     if( extraCols & MASKBIT(i) ){
115293       pIdx->aiColumn[n] = i;
115294       pIdx->azColl[n] = "BINARY";
115295       n++;
115296     }
115297   }
115298   if( pSrc->colUsed & MASKBIT(BMS-1) ){
115299     for(i=BMS-1; i<pTable->nCol; i++){
115300       pIdx->aiColumn[n] = i;
115301       pIdx->azColl[n] = "BINARY";
115302       n++;
115303     }
115304   }
115305   assert( n==nKeyCol );
115306   pIdx->aiColumn[n] = -1;
115307   pIdx->azColl[n] = "BINARY";
115308 
115309   /* Create the automatic index */
115310   assert( pLevel->iIdxCur>=0 );
115311   pLevel->iIdxCur = pParse->nTab++;
115312   sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
115313   sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
115314   VdbeComment((v, "for %s", pTable->zName));
115315 
115316   /* Fill the automatic index with content */
115317   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
115318   regRecord = sqlite3GetTempReg(pParse);
115319   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
115320   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
115321   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
115322   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
115323   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
115324   sqlite3VdbeJumpHere(v, addrTop);
115325   sqlite3ReleaseTempReg(pParse, regRecord);
115326 
115327   /* Jump here when skipping the initialization */
115328   sqlite3VdbeJumpHere(v, addrInit);
115329 }
115330 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
115331 
115332 #ifndef SQLITE_OMIT_VIRTUALTABLE
115333 /*
115334 ** Allocate and populate an sqlite3_index_info structure. It is the
115335 ** responsibility of the caller to eventually release the structure
115336 ** by passing the pointer returned by this function to sqlite3_free().
115337 */
115338 static sqlite3_index_info *allocateIndexInfo(
115339   Parse *pParse,
115340   WhereClause *pWC,
115341   struct SrcList_item *pSrc,
115342   ExprList *pOrderBy
115343 ){
115344   int i, j;
115345   int nTerm;
115346   struct sqlite3_index_constraint *pIdxCons;
115347   struct sqlite3_index_orderby *pIdxOrderBy;
115348   struct sqlite3_index_constraint_usage *pUsage;
115349   WhereTerm *pTerm;
115350   int nOrderBy;
115351   sqlite3_index_info *pIdxInfo;
115352 
115353   /* Count the number of possible WHERE clause constraints referring
115354   ** to this virtual table */
115355   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
115356     if( pTerm->leftCursor != pSrc->iCursor ) continue;
115357     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
115358     testcase( pTerm->eOperator & WO_IN );
115359     testcase( pTerm->eOperator & WO_ISNULL );
115360     testcase( pTerm->eOperator & WO_ALL );
115361     if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
115362     if( pTerm->wtFlags & TERM_VNULL ) continue;
115363     nTerm++;
115364   }
115365 
115366   /* If the ORDER BY clause contains only columns in the current
115367   ** virtual table then allocate space for the aOrderBy part of
115368   ** the sqlite3_index_info structure.
115369   */
115370   nOrderBy = 0;
115371   if( pOrderBy ){
115372     int n = pOrderBy->nExpr;
115373     for(i=0; i<n; i++){
115374       Expr *pExpr = pOrderBy->a[i].pExpr;
115375       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
115376     }
115377     if( i==n){
115378       nOrderBy = n;
115379     }
115380   }
115381 
115382   /* Allocate the sqlite3_index_info structure
115383   */
115384   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
115385                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
115386                            + sizeof(*pIdxOrderBy)*nOrderBy );
115387   if( pIdxInfo==0 ){
115388     sqlite3ErrorMsg(pParse, "out of memory");
115389     return 0;
115390   }
115391 
115392   /* Initialize the structure.  The sqlite3_index_info structure contains
115393   ** many fields that are declared "const" to prevent xBestIndex from
115394   ** changing them.  We have to do some funky casting in order to
115395   ** initialize those fields.
115396   */
115397   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
115398   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
115399   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
115400   *(int*)&pIdxInfo->nConstraint = nTerm;
115401   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
115402   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
115403   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
115404   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
115405                                                                    pUsage;
115406 
115407   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
115408     u8 op;
115409     if( pTerm->leftCursor != pSrc->iCursor ) continue;
115410     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
115411     testcase( pTerm->eOperator & WO_IN );
115412     testcase( pTerm->eOperator & WO_ISNULL );
115413     testcase( pTerm->eOperator & WO_ALL );
115414     if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
115415     if( pTerm->wtFlags & TERM_VNULL ) continue;
115416     pIdxCons[j].iColumn = pTerm->u.leftColumn;
115417     pIdxCons[j].iTermOffset = i;
115418     op = (u8)pTerm->eOperator & WO_ALL;
115419     if( op==WO_IN ) op = WO_EQ;
115420     pIdxCons[j].op = op;
115421     /* The direct assignment in the previous line is possible only because
115422     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
115423     ** following asserts verify this fact. */
115424     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
115425     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
115426     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
115427     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
115428     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
115429     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
115430     assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
115431     j++;
115432   }
115433   for(i=0; i<nOrderBy; i++){
115434     Expr *pExpr = pOrderBy->a[i].pExpr;
115435     pIdxOrderBy[i].iColumn = pExpr->iColumn;
115436     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
115437   }
115438 
115439   return pIdxInfo;
115440 }
115441 
115442 /*
115443 ** The table object reference passed as the second argument to this function
115444 ** must represent a virtual table. This function invokes the xBestIndex()
115445 ** method of the virtual table with the sqlite3_index_info object that
115446 ** comes in as the 3rd argument to this function.
115447 **
115448 ** If an error occurs, pParse is populated with an error message and a
115449 ** non-zero value is returned. Otherwise, 0 is returned and the output
115450 ** part of the sqlite3_index_info structure is left populated.
115451 **
115452 ** Whether or not an error is returned, it is the responsibility of the
115453 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
115454 ** that this is required.
115455 */
115456 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
115457   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
115458   int i;
115459   int rc;
115460 
115461   TRACE_IDX_INPUTS(p);
115462   rc = pVtab->pModule->xBestIndex(pVtab, p);
115463   TRACE_IDX_OUTPUTS(p);
115464 
115465   if( rc!=SQLITE_OK ){
115466     if( rc==SQLITE_NOMEM ){
115467       pParse->db->mallocFailed = 1;
115468     }else if( !pVtab->zErrMsg ){
115469       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
115470     }else{
115471       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
115472     }
115473   }
115474   sqlite3_free(pVtab->zErrMsg);
115475   pVtab->zErrMsg = 0;
115476 
115477   for(i=0; i<p->nConstraint; i++){
115478     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
115479       sqlite3ErrorMsg(pParse,
115480           "table %s: xBestIndex returned an invalid plan", pTab->zName);
115481     }
115482   }
115483 
115484   return pParse->nErr;
115485 }
115486 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
115487 
115488 
115489 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
115490 /*
115491 ** Estimate the location of a particular key among all keys in an
115492 ** index.  Store the results in aStat as follows:
115493 **
115494 **    aStat[0]      Est. number of rows less than pVal
115495 **    aStat[1]      Est. number of rows equal to pVal
115496 **
115497 ** Return SQLITE_OK on success.
115498 */
115499 static void whereKeyStats(
115500   Parse *pParse,              /* Database connection */
115501   Index *pIdx,                /* Index to consider domain of */
115502   UnpackedRecord *pRec,       /* Vector of values to consider */
115503   int roundUp,                /* Round up if true.  Round down if false */
115504   tRowcnt *aStat              /* OUT: stats written here */
115505 ){
115506   IndexSample *aSample = pIdx->aSample;
115507   int iCol;                   /* Index of required stats in anEq[] etc. */
115508   int iMin = 0;               /* Smallest sample not yet tested */
115509   int i = pIdx->nSample;      /* Smallest sample larger than or equal to pRec */
115510   int iTest;                  /* Next sample to test */
115511   int res;                    /* Result of comparison operation */
115512 
115513 #ifndef SQLITE_DEBUG
115514   UNUSED_PARAMETER( pParse );
115515 #endif
115516   assert( pRec!=0 );
115517   iCol = pRec->nField - 1;
115518   assert( pIdx->nSample>0 );
115519   assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
115520   do{
115521     iTest = (iMin+i)/2;
115522     res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec);
115523     if( res<0 ){
115524       iMin = iTest+1;
115525     }else{
115526       i = iTest;
115527     }
115528   }while( res && iMin<i );
115529 
115530 #ifdef SQLITE_DEBUG
115531   /* The following assert statements check that the binary search code
115532   ** above found the right answer. This block serves no purpose other
115533   ** than to invoke the asserts.  */
115534   if( res==0 ){
115535     /* If (res==0) is true, then sample $i must be equal to pRec */
115536     assert( i<pIdx->nSample );
115537     assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
115538          || pParse->db->mallocFailed );
115539   }else{
115540     /* Otherwise, pRec must be smaller than sample $i and larger than
115541     ** sample ($i-1).  */
115542     assert( i==pIdx->nSample
115543          || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
115544          || pParse->db->mallocFailed );
115545     assert( i==0
115546          || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
115547          || pParse->db->mallocFailed );
115548   }
115549 #endif /* ifdef SQLITE_DEBUG */
115550 
115551   /* At this point, aSample[i] is the first sample that is greater than
115552   ** or equal to pVal.  Or if i==pIdx->nSample, then all samples are less
115553   ** than pVal.  If aSample[i]==pVal, then res==0.
115554   */
115555   if( res==0 ){
115556     aStat[0] = aSample[i].anLt[iCol];
115557     aStat[1] = aSample[i].anEq[iCol];
115558   }else{
115559     tRowcnt iLower, iUpper, iGap;
115560     if( i==0 ){
115561       iLower = 0;
115562       iUpper = aSample[0].anLt[iCol];
115563     }else{
115564       i64 nRow0 = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
115565       iUpper = i>=pIdx->nSample ? nRow0 : aSample[i].anLt[iCol];
115566       iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
115567     }
115568     aStat[1] = pIdx->aAvgEq[iCol];
115569     if( iLower>=iUpper ){
115570       iGap = 0;
115571     }else{
115572       iGap = iUpper - iLower;
115573     }
115574     if( roundUp ){
115575       iGap = (iGap*2)/3;
115576     }else{
115577       iGap = iGap/3;
115578     }
115579     aStat[0] = iLower + iGap;
115580   }
115581 }
115582 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
115583 
115584 /*
115585 ** If it is not NULL, pTerm is a term that provides an upper or lower
115586 ** bound on a range scan. Without considering pTerm, it is estimated
115587 ** that the scan will visit nNew rows. This function returns the number
115588 ** estimated to be visited after taking pTerm into account.
115589 **
115590 ** If the user explicitly specified a likelihood() value for this term,
115591 ** then the return value is the likelihood multiplied by the number of
115592 ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
115593 ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
115594 */
115595 static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
115596   LogEst nRet = nNew;
115597   if( pTerm ){
115598     if( pTerm->truthProb<=0 ){
115599       nRet += pTerm->truthProb;
115600     }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
115601       nRet -= 20;        assert( 20==sqlite3LogEst(4) );
115602     }
115603   }
115604   return nRet;
115605 }
115606 
115607 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
115608 /*
115609 ** This function is called to estimate the number of rows visited by a
115610 ** range-scan on a skip-scan index. For example:
115611 **
115612 **   CREATE INDEX i1 ON t1(a, b, c);
115613 **   SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
115614 **
115615 ** Value pLoop->nOut is currently set to the estimated number of rows
115616 ** visited for scanning (a=? AND b=?). This function reduces that estimate
115617 ** by some factor to account for the (c BETWEEN ? AND ?) expression based
115618 ** on the stat4 data for the index. this scan will be peformed multiple
115619 ** times (once for each (a,b) combination that matches a=?) is dealt with
115620 ** by the caller.
115621 **
115622 ** It does this by scanning through all stat4 samples, comparing values
115623 ** extracted from pLower and pUpper with the corresponding column in each
115624 ** sample. If L and U are the number of samples found to be less than or
115625 ** equal to the values extracted from pLower and pUpper respectively, and
115626 ** N is the total number of samples, the pLoop->nOut value is adjusted
115627 ** as follows:
115628 **
115629 **   nOut = nOut * ( min(U - L, 1) / N )
115630 **
115631 ** If pLower is NULL, or a value cannot be extracted from the term, L is
115632 ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
115633 ** U is set to N.
115634 **
115635 ** Normally, this function sets *pbDone to 1 before returning. However,
115636 ** if no value can be extracted from either pLower or pUpper (and so the
115637 ** estimate of the number of rows delivered remains unchanged), *pbDone
115638 ** is left as is.
115639 **
115640 ** If an error occurs, an SQLite error code is returned. Otherwise,
115641 ** SQLITE_OK.
115642 */
115643 static int whereRangeSkipScanEst(
115644   Parse *pParse,       /* Parsing & code generating context */
115645   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
115646   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
115647   WhereLoop *pLoop,    /* Update the .nOut value of this loop */
115648   int *pbDone          /* Set to true if at least one expr. value extracted */
115649 ){
115650   Index *p = pLoop->u.btree.pIndex;
115651   int nEq = pLoop->u.btree.nEq;
115652   sqlite3 *db = pParse->db;
115653   int nLower = -1;
115654   int nUpper = p->nSample+1;
115655   int rc = SQLITE_OK;
115656   int iCol = p->aiColumn[nEq];
115657   u8 aff = iCol>=0 ? p->pTable->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
115658   CollSeq *pColl;
115659 
115660   sqlite3_value *p1 = 0;          /* Value extracted from pLower */
115661   sqlite3_value *p2 = 0;          /* Value extracted from pUpper */
115662   sqlite3_value *pVal = 0;        /* Value extracted from record */
115663 
115664   pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
115665   if( pLower ){
115666     rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
115667     nLower = 0;
115668   }
115669   if( pUpper && rc==SQLITE_OK ){
115670     rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
115671     nUpper = p2 ? 0 : p->nSample;
115672   }
115673 
115674   if( p1 || p2 ){
115675     int i;
115676     int nDiff;
115677     for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
115678       rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
115679       if( rc==SQLITE_OK && p1 ){
115680         int res = sqlite3MemCompare(p1, pVal, pColl);
115681         if( res>=0 ) nLower++;
115682       }
115683       if( rc==SQLITE_OK && p2 ){
115684         int res = sqlite3MemCompare(p2, pVal, pColl);
115685         if( res>=0 ) nUpper++;
115686       }
115687     }
115688     nDiff = (nUpper - nLower);
115689     if( nDiff<=0 ) nDiff = 1;
115690 
115691     /* If there is both an upper and lower bound specified, and the
115692     ** comparisons indicate that they are close together, use the fallback
115693     ** method (assume that the scan visits 1/64 of the rows) for estimating
115694     ** the number of rows visited. Otherwise, estimate the number of rows
115695     ** using the method described in the header comment for this function. */
115696     if( nDiff!=1 || pUpper==0 || pLower==0 ){
115697       int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
115698       pLoop->nOut -= nAdjust;
115699       *pbDone = 1;
115700       WHERETRACE(0x10, ("range skip-scan regions: %u..%u  adjust=%d est=%d\n",
115701                            nLower, nUpper, nAdjust*-1, pLoop->nOut));
115702     }
115703 
115704   }else{
115705     assert( *pbDone==0 );
115706   }
115707 
115708   sqlite3ValueFree(p1);
115709   sqlite3ValueFree(p2);
115710   sqlite3ValueFree(pVal);
115711 
115712   return rc;
115713 }
115714 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
115715 
115716 /*
115717 ** This function is used to estimate the number of rows that will be visited
115718 ** by scanning an index for a range of values. The range may have an upper
115719 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
115720 ** and lower bounds are represented by pLower and pUpper respectively. For
115721 ** example, assuming that index p is on t1(a):
115722 **
115723 **   ... FROM t1 WHERE a > ? AND a < ? ...
115724 **                    |_____|   |_____|
115725 **                       |         |
115726 **                     pLower    pUpper
115727 **
115728 ** If either of the upper or lower bound is not present, then NULL is passed in
115729 ** place of the corresponding WhereTerm.
115730 **
115731 ** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index
115732 ** column subject to the range constraint. Or, equivalently, the number of
115733 ** equality constraints optimized by the proposed index scan. For example,
115734 ** assuming index p is on t1(a, b), and the SQL query is:
115735 **
115736 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
115737 **
115738 ** then nEq is set to 1 (as the range restricted column, b, is the second
115739 ** left-most column of the index). Or, if the query is:
115740 **
115741 **   ... FROM t1 WHERE a > ? AND a < ? ...
115742 **
115743 ** then nEq is set to 0.
115744 **
115745 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
115746 ** number of rows that the index scan is expected to visit without
115747 ** considering the range constraints. If nEq is 0, this is the number of
115748 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
115749 ** to account for the range constraints pLower and pUpper.
115750 **
115751 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
115752 ** used, a single range inequality reduces the search space by a factor of 4.
115753 ** and a pair of constraints (x>? AND x<?) reduces the expected number of
115754 ** rows visited by a factor of 64.
115755 */
115756 static int whereRangeScanEst(
115757   Parse *pParse,       /* Parsing & code generating context */
115758   WhereLoopBuilder *pBuilder,
115759   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
115760   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
115761   WhereLoop *pLoop     /* Modify the .nOut and maybe .rRun fields */
115762 ){
115763   int rc = SQLITE_OK;
115764   int nOut = pLoop->nOut;
115765   LogEst nNew;
115766 
115767 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
115768   Index *p = pLoop->u.btree.pIndex;
115769   int nEq = pLoop->u.btree.nEq;
115770 
115771   if( p->nSample>0
115772    && nEq<p->nSampleCol
115773    && OptimizationEnabled(pParse->db, SQLITE_Stat3)
115774   ){
115775     if( nEq==pBuilder->nRecValid ){
115776       UnpackedRecord *pRec = pBuilder->pRec;
115777       tRowcnt a[2];
115778       u8 aff;
115779 
115780       /* Variable iLower will be set to the estimate of the number of rows in
115781       ** the index that are less than the lower bound of the range query. The
115782       ** lower bound being the concatenation of $P and $L, where $P is the
115783       ** key-prefix formed by the nEq values matched against the nEq left-most
115784       ** columns of the index, and $L is the value in pLower.
115785       **
115786       ** Or, if pLower is NULL or $L cannot be extracted from it (because it
115787       ** is not a simple variable or literal value), the lower bound of the
115788       ** range is $P. Due to a quirk in the way whereKeyStats() works, even
115789       ** if $L is available, whereKeyStats() is called for both ($P) and
115790       ** ($P:$L) and the larger of the two returned values used.
115791       **
115792       ** Similarly, iUpper is to be set to the estimate of the number of rows
115793       ** less than the upper bound of the range query. Where the upper bound
115794       ** is either ($P) or ($P:$U). Again, even if $U is available, both values
115795       ** of iUpper are requested of whereKeyStats() and the smaller used.
115796       */
115797       tRowcnt iLower;
115798       tRowcnt iUpper;
115799 
115800       if( pRec ){
115801         testcase( pRec->nField!=pBuilder->nRecValid );
115802         pRec->nField = pBuilder->nRecValid;
115803       }
115804       if( nEq==p->nKeyCol ){
115805         aff = SQLITE_AFF_INTEGER;
115806       }else{
115807         aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
115808       }
115809       /* Determine iLower and iUpper using ($P) only. */
115810       if( nEq==0 ){
115811         iLower = 0;
115812         iUpper = sqlite3LogEstToInt(p->aiRowLogEst[0]);
115813       }else{
115814         /* Note: this call could be optimized away - since the same values must
115815         ** have been requested when testing key $P in whereEqualScanEst().  */
115816         whereKeyStats(pParse, p, pRec, 0, a);
115817         iLower = a[0];
115818         iUpper = a[0] + a[1];
115819       }
115820 
115821       assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
115822       assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
115823       assert( p->aSortOrder!=0 );
115824       if( p->aSortOrder[nEq] ){
115825         /* The roles of pLower and pUpper are swapped for a DESC index */
115826         SWAP(WhereTerm*, pLower, pUpper);
115827       }
115828 
115829       /* If possible, improve on the iLower estimate using ($P:$L). */
115830       if( pLower ){
115831         int bOk;                    /* True if value is extracted from pExpr */
115832         Expr *pExpr = pLower->pExpr->pRight;
115833         rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
115834         if( rc==SQLITE_OK && bOk ){
115835           tRowcnt iNew;
115836           whereKeyStats(pParse, p, pRec, 0, a);
115837           iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
115838           if( iNew>iLower ) iLower = iNew;
115839           nOut--;
115840           pLower = 0;
115841         }
115842       }
115843 
115844       /* If possible, improve on the iUpper estimate using ($P:$U). */
115845       if( pUpper ){
115846         int bOk;                    /* True if value is extracted from pExpr */
115847         Expr *pExpr = pUpper->pExpr->pRight;
115848         rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
115849         if( rc==SQLITE_OK && bOk ){
115850           tRowcnt iNew;
115851           whereKeyStats(pParse, p, pRec, 1, a);
115852           iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
115853           if( iNew<iUpper ) iUpper = iNew;
115854           nOut--;
115855           pUpper = 0;
115856         }
115857       }
115858 
115859       pBuilder->pRec = pRec;
115860       if( rc==SQLITE_OK ){
115861         if( iUpper>iLower ){
115862           nNew = sqlite3LogEst(iUpper - iLower);
115863         }else{
115864           nNew = 10;        assert( 10==sqlite3LogEst(2) );
115865         }
115866         if( nNew<nOut ){
115867           nOut = nNew;
115868         }
115869         WHERETRACE(0x10, ("STAT4 range scan: %u..%u  est=%d\n",
115870                            (u32)iLower, (u32)iUpper, nOut));
115871       }
115872     }else{
115873       int bDone = 0;
115874       rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
115875       if( bDone ) return rc;
115876     }
115877   }
115878 #else
115879   UNUSED_PARAMETER(pParse);
115880   UNUSED_PARAMETER(pBuilder);
115881   assert( pLower || pUpper );
115882 #endif
115883   assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
115884   nNew = whereRangeAdjust(pLower, nOut);
115885   nNew = whereRangeAdjust(pUpper, nNew);
115886 
115887   /* TUNING: If there is both an upper and lower limit, assume the range is
115888   ** reduced by an additional 75%. This means that, by default, an open-ended
115889   ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
115890   ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
115891   ** match 1/64 of the index. */
115892   if( pLower && pUpper ) nNew -= 20;
115893 
115894   nOut -= (pLower!=0) + (pUpper!=0);
115895   if( nNew<10 ) nNew = 10;
115896   if( nNew<nOut ) nOut = nNew;
115897 #if defined(WHERETRACE_ENABLED)
115898   if( pLoop->nOut>nOut ){
115899     WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
115900                     pLoop->nOut, nOut));
115901   }
115902 #endif
115903   pLoop->nOut = (LogEst)nOut;
115904   return rc;
115905 }
115906 
115907 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
115908 /*
115909 ** Estimate the number of rows that will be returned based on
115910 ** an equality constraint x=VALUE and where that VALUE occurs in
115911 ** the histogram data.  This only works when x is the left-most
115912 ** column of an index and sqlite_stat3 histogram data is available
115913 ** for that index.  When pExpr==NULL that means the constraint is
115914 ** "x IS NULL" instead of "x=VALUE".
115915 **
115916 ** Write the estimated row count into *pnRow and return SQLITE_OK.
115917 ** If unable to make an estimate, leave *pnRow unchanged and return
115918 ** non-zero.
115919 **
115920 ** This routine can fail if it is unable to load a collating sequence
115921 ** required for string comparison, or if unable to allocate memory
115922 ** for a UTF conversion required for comparison.  The error is stored
115923 ** in the pParse structure.
115924 */
115925 static int whereEqualScanEst(
115926   Parse *pParse,       /* Parsing & code generating context */
115927   WhereLoopBuilder *pBuilder,
115928   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
115929   tRowcnt *pnRow       /* Write the revised row estimate here */
115930 ){
115931   Index *p = pBuilder->pNew->u.btree.pIndex;
115932   int nEq = pBuilder->pNew->u.btree.nEq;
115933   UnpackedRecord *pRec = pBuilder->pRec;
115934   u8 aff;                   /* Column affinity */
115935   int rc;                   /* Subfunction return code */
115936   tRowcnt a[2];             /* Statistics */
115937   int bOk;
115938 
115939   assert( nEq>=1 );
115940   assert( nEq<=p->nColumn );
115941   assert( p->aSample!=0 );
115942   assert( p->nSample>0 );
115943   assert( pBuilder->nRecValid<nEq );
115944 
115945   /* If values are not available for all fields of the index to the left
115946   ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
115947   if( pBuilder->nRecValid<(nEq-1) ){
115948     return SQLITE_NOTFOUND;
115949   }
115950 
115951   /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
115952   ** below would return the same value.  */
115953   if( nEq>=p->nColumn ){
115954     *pnRow = 1;
115955     return SQLITE_OK;
115956   }
115957 
115958   aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
115959   rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
115960   pBuilder->pRec = pRec;
115961   if( rc!=SQLITE_OK ) return rc;
115962   if( bOk==0 ) return SQLITE_NOTFOUND;
115963   pBuilder->nRecValid = nEq;
115964 
115965   whereKeyStats(pParse, p, pRec, 0, a);
115966   WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
115967   *pnRow = a[1];
115968 
115969   return rc;
115970 }
115971 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
115972 
115973 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
115974 /*
115975 ** Estimate the number of rows that will be returned based on
115976 ** an IN constraint where the right-hand side of the IN operator
115977 ** is a list of values.  Example:
115978 **
115979 **        WHERE x IN (1,2,3,4)
115980 **
115981 ** Write the estimated row count into *pnRow and return SQLITE_OK.
115982 ** If unable to make an estimate, leave *pnRow unchanged and return
115983 ** non-zero.
115984 **
115985 ** This routine can fail if it is unable to load a collating sequence
115986 ** required for string comparison, or if unable to allocate memory
115987 ** for a UTF conversion required for comparison.  The error is stored
115988 ** in the pParse structure.
115989 */
115990 static int whereInScanEst(
115991   Parse *pParse,       /* Parsing & code generating context */
115992   WhereLoopBuilder *pBuilder,
115993   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
115994   tRowcnt *pnRow       /* Write the revised row estimate here */
115995 ){
115996   Index *p = pBuilder->pNew->u.btree.pIndex;
115997   i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
115998   int nRecValid = pBuilder->nRecValid;
115999   int rc = SQLITE_OK;     /* Subfunction return code */
116000   tRowcnt nEst;           /* Number of rows for a single term */
116001   tRowcnt nRowEst = 0;    /* New estimate of the number of rows */
116002   int i;                  /* Loop counter */
116003 
116004   assert( p->aSample!=0 );
116005   for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
116006     nEst = nRow0;
116007     rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
116008     nRowEst += nEst;
116009     pBuilder->nRecValid = nRecValid;
116010   }
116011 
116012   if( rc==SQLITE_OK ){
116013     if( nRowEst > nRow0 ) nRowEst = nRow0;
116014     *pnRow = nRowEst;
116015     WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
116016   }
116017   assert( pBuilder->nRecValid==nRecValid );
116018   return rc;
116019 }
116020 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
116021 
116022 /*
116023 ** Disable a term in the WHERE clause.  Except, do not disable the term
116024 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
116025 ** or USING clause of that join.
116026 **
116027 ** Consider the term t2.z='ok' in the following queries:
116028 **
116029 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
116030 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
116031 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
116032 **
116033 ** The t2.z='ok' is disabled in the in (2) because it originates
116034 ** in the ON clause.  The term is disabled in (3) because it is not part
116035 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
116036 **
116037 ** Disabling a term causes that term to not be tested in the inner loop
116038 ** of the join.  Disabling is an optimization.  When terms are satisfied
116039 ** by indices, we disable them to prevent redundant tests in the inner
116040 ** loop.  We would get the correct results if nothing were ever disabled,
116041 ** but joins might run a little slower.  The trick is to disable as much
116042 ** as we can without disabling too much.  If we disabled in (1), we'd get
116043 ** the wrong answer.  See ticket #813.
116044 */
116045 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
116046   if( pTerm
116047       && (pTerm->wtFlags & TERM_CODED)==0
116048       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
116049       && (pLevel->notReady & pTerm->prereqAll)==0
116050   ){
116051     pTerm->wtFlags |= TERM_CODED;
116052     if( pTerm->iParent>=0 ){
116053       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
116054       if( (--pOther->nChild)==0 ){
116055         disableTerm(pLevel, pOther);
116056       }
116057     }
116058   }
116059 }
116060 
116061 /*
116062 ** Code an OP_Affinity opcode to apply the column affinity string zAff
116063 ** to the n registers starting at base.
116064 **
116065 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
116066 ** beginning and end of zAff are ignored.  If all entries in zAff are
116067 ** SQLITE_AFF_NONE, then no code gets generated.
116068 **
116069 ** This routine makes its own copy of zAff so that the caller is free
116070 ** to modify zAff after this routine returns.
116071 */
116072 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
116073   Vdbe *v = pParse->pVdbe;
116074   if( zAff==0 ){
116075     assert( pParse->db->mallocFailed );
116076     return;
116077   }
116078   assert( v!=0 );
116079 
116080   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
116081   ** and end of the affinity string.
116082   */
116083   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
116084     n--;
116085     base++;
116086     zAff++;
116087   }
116088   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
116089     n--;
116090   }
116091 
116092   /* Code the OP_Affinity opcode if there is anything left to do. */
116093   if( n>0 ){
116094     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
116095     sqlite3VdbeChangeP4(v, -1, zAff, n);
116096     sqlite3ExprCacheAffinityChange(pParse, base, n);
116097   }
116098 }
116099 
116100 
116101 /*
116102 ** Generate code for a single equality term of the WHERE clause.  An equality
116103 ** term can be either X=expr or X IN (...).   pTerm is the term to be
116104 ** coded.
116105 **
116106 ** The current value for the constraint is left in register iReg.
116107 **
116108 ** For a constraint of the form X=expr, the expression is evaluated and its
116109 ** result is left on the stack.  For constraints of the form X IN (...)
116110 ** this routine sets up a loop that will iterate over all values of X.
116111 */
116112 static int codeEqualityTerm(
116113   Parse *pParse,      /* The parsing context */
116114   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
116115   WhereLevel *pLevel, /* The level of the FROM clause we are working on */
116116   int iEq,            /* Index of the equality term within this level */
116117   int bRev,           /* True for reverse-order IN operations */
116118   int iTarget         /* Attempt to leave results in this register */
116119 ){
116120   Expr *pX = pTerm->pExpr;
116121   Vdbe *v = pParse->pVdbe;
116122   int iReg;                  /* Register holding results */
116123 
116124   assert( iTarget>0 );
116125   if( pX->op==TK_EQ ){
116126     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
116127   }else if( pX->op==TK_ISNULL ){
116128     iReg = iTarget;
116129     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
116130 #ifndef SQLITE_OMIT_SUBQUERY
116131   }else{
116132     int eType;
116133     int iTab;
116134     struct InLoop *pIn;
116135     WhereLoop *pLoop = pLevel->pWLoop;
116136 
116137     if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
116138       && pLoop->u.btree.pIndex!=0
116139       && pLoop->u.btree.pIndex->aSortOrder[iEq]
116140     ){
116141       testcase( iEq==0 );
116142       testcase( bRev );
116143       bRev = !bRev;
116144     }
116145     assert( pX->op==TK_IN );
116146     iReg = iTarget;
116147     eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
116148     if( eType==IN_INDEX_INDEX_DESC ){
116149       testcase( bRev );
116150       bRev = !bRev;
116151     }
116152     iTab = pX->iTable;
116153     sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
116154     VdbeCoverageIf(v, bRev);
116155     VdbeCoverageIf(v, !bRev);
116156     assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
116157     pLoop->wsFlags |= WHERE_IN_ABLE;
116158     if( pLevel->u.in.nIn==0 ){
116159       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
116160     }
116161     pLevel->u.in.nIn++;
116162     pLevel->u.in.aInLoop =
116163        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
116164                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
116165     pIn = pLevel->u.in.aInLoop;
116166     if( pIn ){
116167       pIn += pLevel->u.in.nIn - 1;
116168       pIn->iCur = iTab;
116169       if( eType==IN_INDEX_ROWID ){
116170         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
116171       }else{
116172         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
116173       }
116174       pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
116175       sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
116176     }else{
116177       pLevel->u.in.nIn = 0;
116178     }
116179 #endif
116180   }
116181   disableTerm(pLevel, pTerm);
116182   return iReg;
116183 }
116184 
116185 /*
116186 ** Generate code that will evaluate all == and IN constraints for an
116187 ** index scan.
116188 **
116189 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
116190 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
116191 ** The index has as many as three equality constraints, but in this
116192 ** example, the third "c" value is an inequality.  So only two
116193 ** constraints are coded.  This routine will generate code to evaluate
116194 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
116195 ** in consecutive registers and the index of the first register is returned.
116196 **
116197 ** In the example above nEq==2.  But this subroutine works for any value
116198 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
116199 ** The only thing it does is allocate the pLevel->iMem memory cell and
116200 ** compute the affinity string.
116201 **
116202 ** The nExtraReg parameter is 0 or 1.  It is 0 if all WHERE clause constraints
116203 ** are == or IN and are covered by the nEq.  nExtraReg is 1 if there is
116204 ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
116205 ** occurs after the nEq quality constraints.
116206 **
116207 ** This routine allocates a range of nEq+nExtraReg memory cells and returns
116208 ** the index of the first memory cell in that range. The code that
116209 ** calls this routine will use that memory range to store keys for
116210 ** start and termination conditions of the loop.
116211 ** key value of the loop.  If one or more IN operators appear, then
116212 ** this routine allocates an additional nEq memory cells for internal
116213 ** use.
116214 **
116215 ** Before returning, *pzAff is set to point to a buffer containing a
116216 ** copy of the column affinity string of the index allocated using
116217 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
116218 ** with equality constraints that use NONE affinity are set to
116219 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
116220 **
116221 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
116222 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
116223 **
116224 ** In the example above, the index on t1(a) has TEXT affinity. But since
116225 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
116226 ** no conversion should be attempted before using a t2.b value as part of
116227 ** a key to search the index. Hence the first byte in the returned affinity
116228 ** string in this example would be set to SQLITE_AFF_NONE.
116229 */
116230 static int codeAllEqualityTerms(
116231   Parse *pParse,        /* Parsing context */
116232   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
116233   int bRev,             /* Reverse the order of IN operators */
116234   int nExtraReg,        /* Number of extra registers to allocate */
116235   char **pzAff          /* OUT: Set to point to affinity string */
116236 ){
116237   u16 nEq;                      /* The number of == or IN constraints to code */
116238   u16 nSkip;                    /* Number of left-most columns to skip */
116239   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
116240   Index *pIdx;                  /* The index being used for this loop */
116241   WhereTerm *pTerm;             /* A single constraint term */
116242   WhereLoop *pLoop;             /* The WhereLoop object */
116243   int j;                        /* Loop counter */
116244   int regBase;                  /* Base register */
116245   int nReg;                     /* Number of registers to allocate */
116246   char *zAff;                   /* Affinity string to return */
116247 
116248   /* This module is only called on query plans that use an index. */
116249   pLoop = pLevel->pWLoop;
116250   assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
116251   nEq = pLoop->u.btree.nEq;
116252   nSkip = pLoop->u.btree.nSkip;
116253   pIdx = pLoop->u.btree.pIndex;
116254   assert( pIdx!=0 );
116255 
116256   /* Figure out how many memory cells we will need then allocate them.
116257   */
116258   regBase = pParse->nMem + 1;
116259   nReg = pLoop->u.btree.nEq + nExtraReg;
116260   pParse->nMem += nReg;
116261 
116262   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
116263   if( !zAff ){
116264     pParse->db->mallocFailed = 1;
116265   }
116266 
116267   if( nSkip ){
116268     int iIdxCur = pLevel->iIdxCur;
116269     sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
116270     VdbeCoverageIf(v, bRev==0);
116271     VdbeCoverageIf(v, bRev!=0);
116272     VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
116273     j = sqlite3VdbeAddOp0(v, OP_Goto);
116274     pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
116275                             iIdxCur, 0, regBase, nSkip);
116276     VdbeCoverageIf(v, bRev==0);
116277     VdbeCoverageIf(v, bRev!=0);
116278     sqlite3VdbeJumpHere(v, j);
116279     for(j=0; j<nSkip; j++){
116280       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
116281       assert( pIdx->aiColumn[j]>=0 );
116282       VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
116283     }
116284   }
116285 
116286   /* Evaluate the equality constraints
116287   */
116288   assert( zAff==0 || (int)strlen(zAff)>=nEq );
116289   for(j=nSkip; j<nEq; j++){
116290     int r1;
116291     pTerm = pLoop->aLTerm[j];
116292     assert( pTerm!=0 );
116293     /* The following testcase is true for indices with redundant columns.
116294     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
116295     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
116296     testcase( pTerm->wtFlags & TERM_VIRTUAL );
116297     r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
116298     if( r1!=regBase+j ){
116299       if( nReg==1 ){
116300         sqlite3ReleaseTempReg(pParse, regBase);
116301         regBase = r1;
116302       }else{
116303         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
116304       }
116305     }
116306     testcase( pTerm->eOperator & WO_ISNULL );
116307     testcase( pTerm->eOperator & WO_IN );
116308     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
116309       Expr *pRight = pTerm->pExpr->pRight;
116310       if( sqlite3ExprCanBeNull(pRight) ){
116311         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
116312         VdbeCoverage(v);
116313       }
116314       if( zAff ){
116315         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
116316           zAff[j] = SQLITE_AFF_NONE;
116317         }
116318         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
116319           zAff[j] = SQLITE_AFF_NONE;
116320         }
116321       }
116322     }
116323   }
116324   *pzAff = zAff;
116325   return regBase;
116326 }
116327 
116328 #ifndef SQLITE_OMIT_EXPLAIN
116329 /*
116330 ** This routine is a helper for explainIndexRange() below
116331 **
116332 ** pStr holds the text of an expression that we are building up one term
116333 ** at a time.  This routine adds a new term to the end of the expression.
116334 ** Terms are separated by AND so add the "AND" text for second and subsequent
116335 ** terms only.
116336 */
116337 static void explainAppendTerm(
116338   StrAccum *pStr,             /* The text expression being built */
116339   int iTerm,                  /* Index of this term.  First is zero */
116340   const char *zColumn,        /* Name of the column */
116341   const char *zOp             /* Name of the operator */
116342 ){
116343   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
116344   sqlite3StrAccumAppendAll(pStr, zColumn);
116345   sqlite3StrAccumAppend(pStr, zOp, 1);
116346   sqlite3StrAccumAppend(pStr, "?", 1);
116347 }
116348 
116349 /*
116350 ** Argument pLevel describes a strategy for scanning table pTab. This
116351 ** function appends text to pStr that describes the subset of table
116352 ** rows scanned by the strategy in the form of an SQL expression.
116353 **
116354 ** For example, if the query:
116355 **
116356 **   SELECT * FROM t1 WHERE a=1 AND b>2;
116357 **
116358 ** is run and there is an index on (a, b), then this function returns a
116359 ** string similar to:
116360 **
116361 **   "a=? AND b>?"
116362 */
116363 static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop, Table *pTab){
116364   Index *pIndex = pLoop->u.btree.pIndex;
116365   u16 nEq = pLoop->u.btree.nEq;
116366   u16 nSkip = pLoop->u.btree.nSkip;
116367   int i, j;
116368   Column *aCol = pTab->aCol;
116369   i16 *aiColumn = pIndex->aiColumn;
116370 
116371   if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
116372   sqlite3StrAccumAppend(pStr, " (", 2);
116373   for(i=0; i<nEq; i++){
116374     char *z = aiColumn[i] < 0 ? "rowid" : aCol[aiColumn[i]].zName;
116375     if( i>=nSkip ){
116376       explainAppendTerm(pStr, i, z, "=");
116377     }else{
116378       if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
116379       sqlite3XPrintf(pStr, 0, "ANY(%s)", z);
116380     }
116381   }
116382 
116383   j = i;
116384   if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
116385     char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
116386     explainAppendTerm(pStr, i++, z, ">");
116387   }
116388   if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
116389     char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
116390     explainAppendTerm(pStr, i, z, "<");
116391   }
116392   sqlite3StrAccumAppend(pStr, ")", 1);
116393 }
116394 
116395 /*
116396 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
116397 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
116398 ** record is added to the output to describe the table scan strategy in
116399 ** pLevel.
116400 */
116401 static void explainOneScan(
116402   Parse *pParse,                  /* Parse context */
116403   SrcList *pTabList,              /* Table list this loop refers to */
116404   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
116405   int iLevel,                     /* Value for "level" column of output */
116406   int iFrom,                      /* Value for "from" column of output */
116407   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
116408 ){
116409 #ifndef SQLITE_DEBUG
116410   if( pParse->explain==2 )
116411 #endif
116412   {
116413     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
116414     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
116415     sqlite3 *db = pParse->db;     /* Database handle */
116416     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
116417     int isSearch;                 /* True for a SEARCH. False for SCAN. */
116418     WhereLoop *pLoop;             /* The controlling WhereLoop object */
116419     u32 flags;                    /* Flags that describe this loop */
116420     char *zMsg;                   /* Text to add to EQP output */
116421     StrAccum str;                 /* EQP output string */
116422     char zBuf[100];               /* Initial space for EQP output string */
116423 
116424     pLoop = pLevel->pWLoop;
116425     flags = pLoop->wsFlags;
116426     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
116427 
116428     isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
116429             || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
116430             || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
116431 
116432     sqlite3StrAccumInit(&str, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
116433     str.db = db;
116434     sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
116435     if( pItem->pSelect ){
116436       sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId);
116437     }else{
116438       sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName);
116439     }
116440 
116441     if( pItem->zAlias ){
116442       sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias);
116443     }
116444     if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
116445       const char *zFmt = 0;
116446       Index *pIdx;
116447 
116448       assert( pLoop->u.btree.pIndex!=0 );
116449       pIdx = pLoop->u.btree.pIndex;
116450       assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
116451       if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
116452         if( isSearch ){
116453           zFmt = "PRIMARY KEY";
116454         }
116455       }else if( flags & WHERE_AUTO_INDEX ){
116456         zFmt = "AUTOMATIC COVERING INDEX";
116457       }else if( flags & WHERE_IDX_ONLY ){
116458         zFmt = "COVERING INDEX %s";
116459       }else{
116460         zFmt = "INDEX %s";
116461       }
116462       if( zFmt ){
116463         sqlite3StrAccumAppend(&str, " USING ", 7);
116464         sqlite3XPrintf(&str, 0, zFmt, pIdx->zName);
116465         explainIndexRange(&str, pLoop, pItem->pTab);
116466       }
116467     }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
116468       const char *zRange;
116469       if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
116470         zRange = "(rowid=?)";
116471       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
116472         zRange = "(rowid>? AND rowid<?)";
116473       }else if( flags&WHERE_BTM_LIMIT ){
116474         zRange = "(rowid>?)";
116475       }else{
116476         assert( flags&WHERE_TOP_LIMIT);
116477         zRange = "(rowid<?)";
116478       }
116479       sqlite3StrAccumAppendAll(&str, " USING INTEGER PRIMARY KEY ");
116480       sqlite3StrAccumAppendAll(&str, zRange);
116481     }
116482 #ifndef SQLITE_OMIT_VIRTUALTABLE
116483     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
116484       sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s",
116485                   pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
116486     }
116487 #endif
116488 #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
116489     if( pLoop->nOut>=10 ){
116490       sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
116491     }else{
116492       sqlite3StrAccumAppend(&str, " (~1 row)", 9);
116493     }
116494 #endif
116495     zMsg = sqlite3StrAccumFinish(&str);
116496     sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
116497   }
116498 }
116499 #else
116500 # define explainOneScan(u,v,w,x,y,z)
116501 #endif /* SQLITE_OMIT_EXPLAIN */
116502 
116503 
116504 /*
116505 ** Generate code for the start of the iLevel-th loop in the WHERE clause
116506 ** implementation described by pWInfo.
116507 */
116508 static Bitmask codeOneLoopStart(
116509   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
116510   int iLevel,          /* Which level of pWInfo->a[] should be coded */
116511   Bitmask notReady     /* Which tables are currently available */
116512 ){
116513   int j, k;            /* Loop counters */
116514   int iCur;            /* The VDBE cursor for the table */
116515   int addrNxt;         /* Where to jump to continue with the next IN case */
116516   int omitTable;       /* True if we use the index only */
116517   int bRev;            /* True if we need to scan in reverse order */
116518   WhereLevel *pLevel;  /* The where level to be coded */
116519   WhereLoop *pLoop;    /* The WhereLoop object being coded */
116520   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
116521   WhereTerm *pTerm;               /* A WHERE clause term */
116522   Parse *pParse;                  /* Parsing context */
116523   sqlite3 *db;                    /* Database connection */
116524   Vdbe *v;                        /* The prepared stmt under constructions */
116525   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
116526   int addrBrk;                    /* Jump here to break out of the loop */
116527   int addrCont;                   /* Jump here to continue with next cycle */
116528   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
116529   int iReleaseReg = 0;      /* Temp register to free before returning */
116530 
116531   pParse = pWInfo->pParse;
116532   v = pParse->pVdbe;
116533   pWC = &pWInfo->sWC;
116534   db = pParse->db;
116535   pLevel = &pWInfo->a[iLevel];
116536   pLoop = pLevel->pWLoop;
116537   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
116538   iCur = pTabItem->iCursor;
116539   pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
116540   bRev = (pWInfo->revMask>>iLevel)&1;
116541   omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
116542            && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
116543   VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
116544 
116545   /* Create labels for the "break" and "continue" instructions
116546   ** for the current loop.  Jump to addrBrk to break out of a loop.
116547   ** Jump to cont to go immediately to the next iteration of the
116548   ** loop.
116549   **
116550   ** When there is an IN operator, we also have a "addrNxt" label that
116551   ** means to continue with the next IN value combination.  When
116552   ** there are no IN operators in the constraints, the "addrNxt" label
116553   ** is the same as "addrBrk".
116554   */
116555   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
116556   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
116557 
116558   /* If this is the right table of a LEFT OUTER JOIN, allocate and
116559   ** initialize a memory cell that records if this table matches any
116560   ** row of the left table of the join.
116561   */
116562   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
116563     pLevel->iLeftJoin = ++pParse->nMem;
116564     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
116565     VdbeComment((v, "init LEFT JOIN no-match flag"));
116566   }
116567 
116568   /* Special case of a FROM clause subquery implemented as a co-routine */
116569   if( pTabItem->viaCoroutine ){
116570     int regYield = pTabItem->regReturn;
116571     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
116572     pLevel->p2 =  sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
116573     VdbeCoverage(v);
116574     VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
116575     pLevel->op = OP_Goto;
116576   }else
116577 
116578 #ifndef SQLITE_OMIT_VIRTUALTABLE
116579   if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
116580     /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext
116581     **          to access the data.
116582     */
116583     int iReg;   /* P3 Value for OP_VFilter */
116584     int addrNotFound;
116585     int nConstraint = pLoop->nLTerm;
116586 
116587     sqlite3ExprCachePush(pParse);
116588     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
116589     addrNotFound = pLevel->addrBrk;
116590     for(j=0; j<nConstraint; j++){
116591       int iTarget = iReg+j+2;
116592       pTerm = pLoop->aLTerm[j];
116593       if( pTerm==0 ) continue;
116594       if( pTerm->eOperator & WO_IN ){
116595         codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
116596         addrNotFound = pLevel->addrNxt;
116597       }else{
116598         sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
116599       }
116600     }
116601     sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
116602     sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
116603     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
116604                       pLoop->u.vtab.idxStr,
116605                       pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
116606     VdbeCoverage(v);
116607     pLoop->u.vtab.needFree = 0;
116608     for(j=0; j<nConstraint && j<16; j++){
116609       if( (pLoop->u.vtab.omitMask>>j)&1 ){
116610         disableTerm(pLevel, pLoop->aLTerm[j]);
116611       }
116612     }
116613     pLevel->op = OP_VNext;
116614     pLevel->p1 = iCur;
116615     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
116616     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
116617     sqlite3ExprCachePop(pParse);
116618   }else
116619 #endif /* SQLITE_OMIT_VIRTUALTABLE */
116620 
116621   if( (pLoop->wsFlags & WHERE_IPK)!=0
116622    && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
116623   ){
116624     /* Case 2:  We can directly reference a single row using an
116625     **          equality comparison against the ROWID field.  Or
116626     **          we reference multiple rows using a "rowid IN (...)"
116627     **          construct.
116628     */
116629     assert( pLoop->u.btree.nEq==1 );
116630     pTerm = pLoop->aLTerm[0];
116631     assert( pTerm!=0 );
116632     assert( pTerm->pExpr!=0 );
116633     assert( omitTable==0 );
116634     testcase( pTerm->wtFlags & TERM_VIRTUAL );
116635     iReleaseReg = ++pParse->nMem;
116636     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
116637     if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
116638     addrNxt = pLevel->addrNxt;
116639     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
116640     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
116641     VdbeCoverage(v);
116642     sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
116643     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
116644     VdbeComment((v, "pk"));
116645     pLevel->op = OP_Noop;
116646   }else if( (pLoop->wsFlags & WHERE_IPK)!=0
116647          && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
116648   ){
116649     /* Case 3:  We have an inequality comparison against the ROWID field.
116650     */
116651     int testOp = OP_Noop;
116652     int start;
116653     int memEndValue = 0;
116654     WhereTerm *pStart, *pEnd;
116655 
116656     assert( omitTable==0 );
116657     j = 0;
116658     pStart = pEnd = 0;
116659     if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
116660     if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
116661     assert( pStart!=0 || pEnd!=0 );
116662     if( bRev ){
116663       pTerm = pStart;
116664       pStart = pEnd;
116665       pEnd = pTerm;
116666     }
116667     if( pStart ){
116668       Expr *pX;             /* The expression that defines the start bound */
116669       int r1, rTemp;        /* Registers for holding the start boundary */
116670 
116671       /* The following constant maps TK_xx codes into corresponding
116672       ** seek opcodes.  It depends on a particular ordering of TK_xx
116673       */
116674       const u8 aMoveOp[] = {
116675            /* TK_GT */  OP_SeekGT,
116676            /* TK_LE */  OP_SeekLE,
116677            /* TK_LT */  OP_SeekLT,
116678            /* TK_GE */  OP_SeekGE
116679       };
116680       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
116681       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
116682       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
116683 
116684       assert( (pStart->wtFlags & TERM_VNULL)==0 );
116685       testcase( pStart->wtFlags & TERM_VIRTUAL );
116686       pX = pStart->pExpr;
116687       assert( pX!=0 );
116688       testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
116689       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
116690       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
116691       VdbeComment((v, "pk"));
116692       VdbeCoverageIf(v, pX->op==TK_GT);
116693       VdbeCoverageIf(v, pX->op==TK_LE);
116694       VdbeCoverageIf(v, pX->op==TK_LT);
116695       VdbeCoverageIf(v, pX->op==TK_GE);
116696       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
116697       sqlite3ReleaseTempReg(pParse, rTemp);
116698       disableTerm(pLevel, pStart);
116699     }else{
116700       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
116701       VdbeCoverageIf(v, bRev==0);
116702       VdbeCoverageIf(v, bRev!=0);
116703     }
116704     if( pEnd ){
116705       Expr *pX;
116706       pX = pEnd->pExpr;
116707       assert( pX!=0 );
116708       assert( (pEnd->wtFlags & TERM_VNULL)==0 );
116709       testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
116710       testcase( pEnd->wtFlags & TERM_VIRTUAL );
116711       memEndValue = ++pParse->nMem;
116712       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
116713       if( pX->op==TK_LT || pX->op==TK_GT ){
116714         testOp = bRev ? OP_Le : OP_Ge;
116715       }else{
116716         testOp = bRev ? OP_Lt : OP_Gt;
116717       }
116718       disableTerm(pLevel, pEnd);
116719     }
116720     start = sqlite3VdbeCurrentAddr(v);
116721     pLevel->op = bRev ? OP_Prev : OP_Next;
116722     pLevel->p1 = iCur;
116723     pLevel->p2 = start;
116724     assert( pLevel->p5==0 );
116725     if( testOp!=OP_Noop ){
116726       iRowidReg = ++pParse->nMem;
116727       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
116728       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
116729       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
116730       VdbeCoverageIf(v, testOp==OP_Le);
116731       VdbeCoverageIf(v, testOp==OP_Lt);
116732       VdbeCoverageIf(v, testOp==OP_Ge);
116733       VdbeCoverageIf(v, testOp==OP_Gt);
116734       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
116735     }
116736   }else if( pLoop->wsFlags & WHERE_INDEXED ){
116737     /* Case 4: A scan using an index.
116738     **
116739     **         The WHERE clause may contain zero or more equality
116740     **         terms ("==" or "IN" operators) that refer to the N
116741     **         left-most columns of the index. It may also contain
116742     **         inequality constraints (>, <, >= or <=) on the indexed
116743     **         column that immediately follows the N equalities. Only
116744     **         the right-most column can be an inequality - the rest must
116745     **         use the "==" and "IN" operators. For example, if the
116746     **         index is on (x,y,z), then the following clauses are all
116747     **         optimized:
116748     **
116749     **            x=5
116750     **            x=5 AND y=10
116751     **            x=5 AND y<10
116752     **            x=5 AND y>5 AND y<10
116753     **            x=5 AND y=5 AND z<=10
116754     **
116755     **         The z<10 term of the following cannot be used, only
116756     **         the x=5 term:
116757     **
116758     **            x=5 AND z<10
116759     **
116760     **         N may be zero if there are inequality constraints.
116761     **         If there are no inequality constraints, then N is at
116762     **         least one.
116763     **
116764     **         This case is also used when there are no WHERE clause
116765     **         constraints but an index is selected anyway, in order
116766     **         to force the output order to conform to an ORDER BY.
116767     */
116768     static const u8 aStartOp[] = {
116769       0,
116770       0,
116771       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
116772       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
116773       OP_SeekGT,           /* 4: (start_constraints  && !startEq && !bRev) */
116774       OP_SeekLT,           /* 5: (start_constraints  && !startEq &&  bRev) */
116775       OP_SeekGE,           /* 6: (start_constraints  &&  startEq && !bRev) */
116776       OP_SeekLE            /* 7: (start_constraints  &&  startEq &&  bRev) */
116777     };
116778     static const u8 aEndOp[] = {
116779       OP_IdxGE,            /* 0: (end_constraints && !bRev && !endEq) */
116780       OP_IdxGT,            /* 1: (end_constraints && !bRev &&  endEq) */
116781       OP_IdxLE,            /* 2: (end_constraints &&  bRev && !endEq) */
116782       OP_IdxLT,            /* 3: (end_constraints &&  bRev &&  endEq) */
116783     };
116784     u16 nEq = pLoop->u.btree.nEq;     /* Number of == or IN terms */
116785     int regBase;                 /* Base register holding constraint values */
116786     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
116787     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
116788     int startEq;                 /* True if range start uses ==, >= or <= */
116789     int endEq;                   /* True if range end uses ==, >= or <= */
116790     int start_constraints;       /* Start of range is constrained */
116791     int nConstraint;             /* Number of constraint terms */
116792     Index *pIdx;                 /* The index we will be using */
116793     int iIdxCur;                 /* The VDBE cursor for the index */
116794     int nExtraReg = 0;           /* Number of extra registers needed */
116795     int op;                      /* Instruction opcode */
116796     char *zStartAff;             /* Affinity for start of range constraint */
116797     char cEndAff = 0;            /* Affinity for end of range constraint */
116798     u8 bSeekPastNull = 0;        /* True to seek past initial nulls */
116799     u8 bStopAtNull = 0;          /* Add condition to terminate at NULLs */
116800 
116801     pIdx = pLoop->u.btree.pIndex;
116802     iIdxCur = pLevel->iIdxCur;
116803     assert( nEq>=pLoop->u.btree.nSkip );
116804 
116805     /* If this loop satisfies a sort order (pOrderBy) request that
116806     ** was passed to this function to implement a "SELECT min(x) ..."
116807     ** query, then the caller will only allow the loop to run for
116808     ** a single iteration. This means that the first row returned
116809     ** should not have a NULL value stored in 'x'. If column 'x' is
116810     ** the first one after the nEq equality constraints in the index,
116811     ** this requires some special handling.
116812     */
116813     assert( pWInfo->pOrderBy==0
116814          || pWInfo->pOrderBy->nExpr==1
116815          || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
116816     if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
116817      && pWInfo->nOBSat>0
116818      && (pIdx->nKeyCol>nEq)
116819     ){
116820       assert( pLoop->u.btree.nSkip==0 );
116821       bSeekPastNull = 1;
116822       nExtraReg = 1;
116823     }
116824 
116825     /* Find any inequality constraint terms for the start and end
116826     ** of the range.
116827     */
116828     j = nEq;
116829     if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
116830       pRangeStart = pLoop->aLTerm[j++];
116831       nExtraReg = 1;
116832     }
116833     if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
116834       pRangeEnd = pLoop->aLTerm[j++];
116835       nExtraReg = 1;
116836       if( pRangeStart==0
116837        && (j = pIdx->aiColumn[nEq])>=0
116838        && pIdx->pTable->aCol[j].notNull==0
116839       ){
116840         bSeekPastNull = 1;
116841       }
116842     }
116843     assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
116844 
116845     /* Generate code to evaluate all constraint terms using == or IN
116846     ** and store the values of those terms in an array of registers
116847     ** starting at regBase.
116848     */
116849     regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
116850     assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
116851     if( zStartAff ) cEndAff = zStartAff[nEq];
116852     addrNxt = pLevel->addrNxt;
116853 
116854     /* If we are doing a reverse order scan on an ascending index, or
116855     ** a forward order scan on a descending index, interchange the
116856     ** start and end terms (pRangeStart and pRangeEnd).
116857     */
116858     if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
116859      || (bRev && pIdx->nKeyCol==nEq)
116860     ){
116861       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
116862       SWAP(u8, bSeekPastNull, bStopAtNull);
116863     }
116864 
116865     testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
116866     testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
116867     testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
116868     testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
116869     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
116870     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
116871     start_constraints = pRangeStart || nEq>0;
116872 
116873     /* Seek the index cursor to the start of the range. */
116874     nConstraint = nEq;
116875     if( pRangeStart ){
116876       Expr *pRight = pRangeStart->pExpr->pRight;
116877       sqlite3ExprCode(pParse, pRight, regBase+nEq);
116878       if( (pRangeStart->wtFlags & TERM_VNULL)==0
116879        && sqlite3ExprCanBeNull(pRight)
116880       ){
116881         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
116882         VdbeCoverage(v);
116883       }
116884       if( zStartAff ){
116885         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
116886           /* Since the comparison is to be performed with no conversions
116887           ** applied to the operands, set the affinity to apply to pRight to
116888           ** SQLITE_AFF_NONE.  */
116889           zStartAff[nEq] = SQLITE_AFF_NONE;
116890         }
116891         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
116892           zStartAff[nEq] = SQLITE_AFF_NONE;
116893         }
116894       }
116895       nConstraint++;
116896       testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
116897     }else if( bSeekPastNull ){
116898       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
116899       nConstraint++;
116900       startEq = 0;
116901       start_constraints = 1;
116902     }
116903     codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
116904     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
116905     assert( op!=0 );
116906     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
116907     VdbeCoverage(v);
116908     VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
116909     VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
116910     VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );
116911     VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
116912     VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
116913     VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );
116914 
116915     /* Load the value for the inequality constraint at the end of the
116916     ** range (if any).
116917     */
116918     nConstraint = nEq;
116919     if( pRangeEnd ){
116920       Expr *pRight = pRangeEnd->pExpr->pRight;
116921       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
116922       sqlite3ExprCode(pParse, pRight, regBase+nEq);
116923       if( (pRangeEnd->wtFlags & TERM_VNULL)==0
116924        && sqlite3ExprCanBeNull(pRight)
116925       ){
116926         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
116927         VdbeCoverage(v);
116928       }
116929       if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE
116930        && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
116931       ){
116932         codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
116933       }
116934       nConstraint++;
116935       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
116936     }else if( bStopAtNull ){
116937       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
116938       endEq = 0;
116939       nConstraint++;
116940     }
116941     sqlite3DbFree(db, zStartAff);
116942 
116943     /* Top of the loop body */
116944     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
116945 
116946     /* Check if the index cursor is past the end of the range. */
116947     if( nConstraint ){
116948       op = aEndOp[bRev*2 + endEq];
116949       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
116950       testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );
116951       testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );
116952       testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );
116953       testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
116954     }
116955 
116956     /* Seek the table cursor, if required */
116957     disableTerm(pLevel, pRangeStart);
116958     disableTerm(pLevel, pRangeEnd);
116959     if( omitTable ){
116960       /* pIdx is a covering index.  No need to access the main table. */
116961     }else if( HasRowid(pIdx->pTable) ){
116962       iRowidReg = ++pParse->nMem;
116963       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
116964       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
116965       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
116966     }else if( iCur!=iIdxCur ){
116967       Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
116968       iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
116969       for(j=0; j<pPk->nKeyCol; j++){
116970         k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
116971         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
116972       }
116973       sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
116974                            iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
116975     }
116976 
116977     /* Record the instruction used to terminate the loop. Disable
116978     ** WHERE clause terms made redundant by the index range scan.
116979     */
116980     if( pLoop->wsFlags & WHERE_ONEROW ){
116981       pLevel->op = OP_Noop;
116982     }else if( bRev ){
116983       pLevel->op = OP_Prev;
116984     }else{
116985       pLevel->op = OP_Next;
116986     }
116987     pLevel->p1 = iIdxCur;
116988     pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
116989     if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
116990       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
116991     }else{
116992       assert( pLevel->p5==0 );
116993     }
116994   }else
116995 
116996 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
116997   if( pLoop->wsFlags & WHERE_MULTI_OR ){
116998     /* Case 5:  Two or more separately indexed terms connected by OR
116999     **
117000     ** Example:
117001     **
117002     **   CREATE TABLE t1(a,b,c,d);
117003     **   CREATE INDEX i1 ON t1(a);
117004     **   CREATE INDEX i2 ON t1(b);
117005     **   CREATE INDEX i3 ON t1(c);
117006     **
117007     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
117008     **
117009     ** In the example, there are three indexed terms connected by OR.
117010     ** The top of the loop looks like this:
117011     **
117012     **          Null       1                # Zero the rowset in reg 1
117013     **
117014     ** Then, for each indexed term, the following. The arguments to
117015     ** RowSetTest are such that the rowid of the current row is inserted
117016     ** into the RowSet. If it is already present, control skips the
117017     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
117018     **
117019     **        sqlite3WhereBegin(<term>)
117020     **          RowSetTest                  # Insert rowid into rowset
117021     **          Gosub      2 A
117022     **        sqlite3WhereEnd()
117023     **
117024     ** Following the above, code to terminate the loop. Label A, the target
117025     ** of the Gosub above, jumps to the instruction right after the Goto.
117026     **
117027     **          Null       1                # Zero the rowset in reg 1
117028     **          Goto       B                # The loop is finished.
117029     **
117030     **       A: <loop body>                 # Return data, whatever.
117031     **
117032     **          Return     2                # Jump back to the Gosub
117033     **
117034     **       B: <after the loop>
117035     **
117036     ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
117037     ** use an ephemeral index instead of a RowSet to record the primary
117038     ** keys of the rows we have already seen.
117039     **
117040     */
117041     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
117042     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
117043     Index *pCov = 0;             /* Potential covering index (or NULL) */
117044     int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
117045 
117046     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
117047     int regRowset = 0;                        /* Register for RowSet object */
117048     int regRowid = 0;                         /* Register holding rowid */
117049     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
117050     int iRetInit;                             /* Address of regReturn init */
117051     int untestedTerms = 0;             /* Some terms not completely tested */
117052     int ii;                            /* Loop counter */
117053     u16 wctrlFlags;                    /* Flags for sub-WHERE clause */
117054     Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
117055     Table *pTab = pTabItem->pTab;
117056 
117057     pTerm = pLoop->aLTerm[0];
117058     assert( pTerm!=0 );
117059     assert( pTerm->eOperator & WO_OR );
117060     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
117061     pOrWc = &pTerm->u.pOrInfo->wc;
117062     pLevel->op = OP_Return;
117063     pLevel->p1 = regReturn;
117064 
117065     /* Set up a new SrcList in pOrTab containing the table being scanned
117066     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
117067     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
117068     */
117069     if( pWInfo->nLevel>1 ){
117070       int nNotReady;                 /* The number of notReady tables */
117071       struct SrcList_item *origSrc;     /* Original list of tables */
117072       nNotReady = pWInfo->nLevel - iLevel - 1;
117073       pOrTab = sqlite3StackAllocRaw(db,
117074                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
117075       if( pOrTab==0 ) return notReady;
117076       pOrTab->nAlloc = (u8)(nNotReady + 1);
117077       pOrTab->nSrc = pOrTab->nAlloc;
117078       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
117079       origSrc = pWInfo->pTabList->a;
117080       for(k=1; k<=nNotReady; k++){
117081         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
117082       }
117083     }else{
117084       pOrTab = pWInfo->pTabList;
117085     }
117086 
117087     /* Initialize the rowset register to contain NULL. An SQL NULL is
117088     ** equivalent to an empty rowset.  Or, create an ephemeral index
117089     ** capable of holding primary keys in the case of a WITHOUT ROWID.
117090     **
117091     ** Also initialize regReturn to contain the address of the instruction
117092     ** immediately following the OP_Return at the bottom of the loop. This
117093     ** is required in a few obscure LEFT JOIN cases where control jumps
117094     ** over the top of the loop into the body of it. In this case the
117095     ** correct response for the end-of-loop code (the OP_Return) is to
117096     ** fall through to the next instruction, just as an OP_Next does if
117097     ** called on an uninitialized cursor.
117098     */
117099     if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
117100       if( HasRowid(pTab) ){
117101         regRowset = ++pParse->nMem;
117102         sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
117103       }else{
117104         Index *pPk = sqlite3PrimaryKeyIndex(pTab);
117105         regRowset = pParse->nTab++;
117106         sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
117107         sqlite3VdbeSetP4KeyInfo(pParse, pPk);
117108       }
117109       regRowid = ++pParse->nMem;
117110     }
117111     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
117112 
117113     /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
117114     ** Then for every term xN, evaluate as the subexpression: xN AND z
117115     ** That way, terms in y that are factored into the disjunction will
117116     ** be picked up by the recursive calls to sqlite3WhereBegin() below.
117117     **
117118     ** Actually, each subexpression is converted to "xN AND w" where w is
117119     ** the "interesting" terms of z - terms that did not originate in the
117120     ** ON or USING clause of a LEFT JOIN, and terms that are usable as
117121     ** indices.
117122     **
117123     ** This optimization also only applies if the (x1 OR x2 OR ...) term
117124     ** is not contained in the ON clause of a LEFT JOIN.
117125     ** See ticket http://www.sqlite.org/src/info/f2369304e4
117126     */
117127     if( pWC->nTerm>1 ){
117128       int iTerm;
117129       for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
117130         Expr *pExpr = pWC->a[iTerm].pExpr;
117131         if( &pWC->a[iTerm] == pTerm ) continue;
117132         if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
117133         testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
117134         testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
117135         if( pWC->a[iTerm].wtFlags & (TERM_ORINFO|TERM_VIRTUAL) ) continue;
117136         if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
117137         pExpr = sqlite3ExprDup(db, pExpr, 0);
117138         pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
117139       }
117140       if( pAndExpr ){
117141         pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
117142       }
117143     }
117144 
117145     /* Run a separate WHERE clause for each term of the OR clause.  After
117146     ** eliminating duplicates from other WHERE clauses, the action for each
117147     ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
117148     */
117149     wctrlFlags =  WHERE_OMIT_OPEN_CLOSE
117150                 | WHERE_FORCE_TABLE
117151                 | WHERE_ONETABLE_ONLY;
117152     for(ii=0; ii<pOrWc->nTerm; ii++){
117153       WhereTerm *pOrTerm = &pOrWc->a[ii];
117154       if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
117155         WhereInfo *pSubWInfo;           /* Info for single OR-term scan */
117156         Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
117157         int j1 = 0;                     /* Address of jump operation */
117158         if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
117159           pAndExpr->pLeft = pOrExpr;
117160           pOrExpr = pAndExpr;
117161         }
117162         /* Loop through table entries that match term pOrTerm. */
117163         WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
117164         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
117165                                       wctrlFlags, iCovCur);
117166         assert( pSubWInfo || pParse->nErr || db->mallocFailed );
117167         if( pSubWInfo ){
117168           WhereLoop *pSubLoop;
117169           explainOneScan(
117170               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
117171           );
117172           /* This is the sub-WHERE clause body.  First skip over
117173           ** duplicate rows from prior sub-WHERE clauses, and record the
117174           ** rowid (or PRIMARY KEY) for the current row so that the same
117175           ** row will be skipped in subsequent sub-WHERE clauses.
117176           */
117177           if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
117178             int r;
117179             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
117180             if( HasRowid(pTab) ){
117181               r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
117182               j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet);
117183               VdbeCoverage(v);
117184             }else{
117185               Index *pPk = sqlite3PrimaryKeyIndex(pTab);
117186               int nPk = pPk->nKeyCol;
117187               int iPk;
117188 
117189               /* Read the PK into an array of temp registers. */
117190               r = sqlite3GetTempRange(pParse, nPk);
117191               for(iPk=0; iPk<nPk; iPk++){
117192                 int iCol = pPk->aiColumn[iPk];
117193                 sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur, r+iPk, 0);
117194               }
117195 
117196               /* Check if the temp table already contains this key. If so,
117197               ** the row has already been included in the result set and
117198               ** can be ignored (by jumping past the Gosub below). Otherwise,
117199               ** insert the key into the temp table and proceed with processing
117200               ** the row.
117201               **
117202               ** Use some of the same optimizations as OP_RowSetTest: If iSet
117203               ** is zero, assume that the key cannot already be present in
117204               ** the temp table. And if iSet is -1, assume that there is no
117205               ** need to insert the key into the temp table, as it will never
117206               ** be tested for.  */
117207               if( iSet ){
117208                 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
117209                 VdbeCoverage(v);
117210               }
117211               if( iSet>=0 ){
117212                 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
117213                 sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
117214                 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
117215               }
117216 
117217               /* Release the array of temp registers */
117218               sqlite3ReleaseTempRange(pParse, r, nPk);
117219             }
117220           }
117221 
117222           /* Invoke the main loop body as a subroutine */
117223           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
117224 
117225           /* Jump here (skipping the main loop body subroutine) if the
117226           ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
117227           if( j1 ) sqlite3VdbeJumpHere(v, j1);
117228 
117229           /* The pSubWInfo->untestedTerms flag means that this OR term
117230           ** contained one or more AND term from a notReady table.  The
117231           ** terms from the notReady table could not be tested and will
117232           ** need to be tested later.
117233           */
117234           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
117235 
117236           /* If all of the OR-connected terms are optimized using the same
117237           ** index, and the index is opened using the same cursor number
117238           ** by each call to sqlite3WhereBegin() made by this loop, it may
117239           ** be possible to use that index as a covering index.
117240           **
117241           ** If the call to sqlite3WhereBegin() above resulted in a scan that
117242           ** uses an index, and this is either the first OR-connected term
117243           ** processed or the index is the same as that used by all previous
117244           ** terms, set pCov to the candidate covering index. Otherwise, set
117245           ** pCov to NULL to indicate that no candidate covering index will
117246           ** be available.
117247           */
117248           pSubLoop = pSubWInfo->a[0].pWLoop;
117249           assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
117250           if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
117251            && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
117252            && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
117253           ){
117254             assert( pSubWInfo->a[0].iIdxCur==iCovCur );
117255             pCov = pSubLoop->u.btree.pIndex;
117256             wctrlFlags |= WHERE_REOPEN_IDX;
117257           }else{
117258             pCov = 0;
117259           }
117260 
117261           /* Finish the loop through table entries that match term pOrTerm. */
117262           sqlite3WhereEnd(pSubWInfo);
117263         }
117264       }
117265     }
117266     pLevel->u.pCovidx = pCov;
117267     if( pCov ) pLevel->iIdxCur = iCovCur;
117268     if( pAndExpr ){
117269       pAndExpr->pLeft = 0;
117270       sqlite3ExprDelete(db, pAndExpr);
117271     }
117272     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
117273     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
117274     sqlite3VdbeResolveLabel(v, iLoopBody);
117275 
117276     if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
117277     if( !untestedTerms ) disableTerm(pLevel, pTerm);
117278   }else
117279 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
117280 
117281   {
117282     /* Case 6:  There is no usable index.  We must do a complete
117283     **          scan of the entire table.
117284     */
117285     static const u8 aStep[] = { OP_Next, OP_Prev };
117286     static const u8 aStart[] = { OP_Rewind, OP_Last };
117287     assert( bRev==0 || bRev==1 );
117288     if( pTabItem->isRecursive ){
117289       /* Tables marked isRecursive have only a single row that is stored in
117290       ** a pseudo-cursor.  No need to Rewind or Next such cursors. */
117291       pLevel->op = OP_Noop;
117292     }else{
117293       pLevel->op = aStep[bRev];
117294       pLevel->p1 = iCur;
117295       pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
117296       VdbeCoverageIf(v, bRev==0);
117297       VdbeCoverageIf(v, bRev!=0);
117298       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
117299     }
117300   }
117301 
117302   /* Insert code to test every subexpression that can be completely
117303   ** computed using the current set of tables.
117304   */
117305   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
117306     Expr *pE;
117307     testcase( pTerm->wtFlags & TERM_VIRTUAL );
117308     testcase( pTerm->wtFlags & TERM_CODED );
117309     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
117310     if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
117311       testcase( pWInfo->untestedTerms==0
117312                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
117313       pWInfo->untestedTerms = 1;
117314       continue;
117315     }
117316     pE = pTerm->pExpr;
117317     assert( pE!=0 );
117318     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
117319       continue;
117320     }
117321     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
117322     pTerm->wtFlags |= TERM_CODED;
117323   }
117324 
117325   /* Insert code to test for implied constraints based on transitivity
117326   ** of the "==" operator.
117327   **
117328   ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
117329   ** and we are coding the t1 loop and the t2 loop has not yet coded,
117330   ** then we cannot use the "t1.a=t2.b" constraint, but we can code
117331   ** the implied "t1.a=123" constraint.
117332   */
117333   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
117334     Expr *pE, *pEAlt;
117335     WhereTerm *pAlt;
117336     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
117337     if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
117338     if( pTerm->leftCursor!=iCur ) continue;
117339     if( pLevel->iLeftJoin ) continue;
117340     pE = pTerm->pExpr;
117341     assert( !ExprHasProperty(pE, EP_FromJoin) );
117342     assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
117343     pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
117344     if( pAlt==0 ) continue;
117345     if( pAlt->wtFlags & (TERM_CODED) ) continue;
117346     testcase( pAlt->eOperator & WO_EQ );
117347     testcase( pAlt->eOperator & WO_IN );
117348     VdbeModuleComment((v, "begin transitive constraint"));
117349     pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
117350     if( pEAlt ){
117351       *pEAlt = *pAlt->pExpr;
117352       pEAlt->pLeft = pE->pLeft;
117353       sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
117354       sqlite3StackFree(db, pEAlt);
117355     }
117356   }
117357 
117358   /* For a LEFT OUTER JOIN, generate code that will record the fact that
117359   ** at least one row of the right table has matched the left table.
117360   */
117361   if( pLevel->iLeftJoin ){
117362     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
117363     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
117364     VdbeComment((v, "record LEFT JOIN hit"));
117365     sqlite3ExprCacheClear(pParse);
117366     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
117367       testcase( pTerm->wtFlags & TERM_VIRTUAL );
117368       testcase( pTerm->wtFlags & TERM_CODED );
117369       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
117370       if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
117371         assert( pWInfo->untestedTerms );
117372         continue;
117373       }
117374       assert( pTerm->pExpr );
117375       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
117376       pTerm->wtFlags |= TERM_CODED;
117377     }
117378   }
117379 
117380   return pLevel->notReady;
117381 }
117382 
117383 #ifdef WHERETRACE_ENABLED
117384 /*
117385 ** Print the content of a WhereTerm object
117386 */
117387 static void whereTermPrint(WhereTerm *pTerm, int iTerm){
117388   if( pTerm==0 ){
117389     sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
117390   }else{
117391     char zType[4];
117392     memcpy(zType, "...", 4);
117393     if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
117394     if( pTerm->eOperator & WO_EQUIV  ) zType[1] = 'E';
117395     if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
117396     sqlite3DebugPrintf("TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x\n",
117397                        iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
117398                        pTerm->eOperator);
117399     sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
117400   }
117401 }
117402 #endif
117403 
117404 #ifdef WHERETRACE_ENABLED
117405 /*
117406 ** Print a WhereLoop object for debugging purposes
117407 */
117408 static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
117409   WhereInfo *pWInfo = pWC->pWInfo;
117410   int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
117411   struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
117412   Table *pTab = pItem->pTab;
117413   sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
117414                      p->iTab, nb, p->maskSelf, nb, p->prereq);
117415   sqlite3DebugPrintf(" %12s",
117416                      pItem->zAlias ? pItem->zAlias : pTab->zName);
117417   if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
117418     const char *zName;
117419     if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
117420       if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
117421         int i = sqlite3Strlen30(zName) - 1;
117422         while( zName[i]!='_' ) i--;
117423         zName += i;
117424       }
117425       sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
117426     }else{
117427       sqlite3DebugPrintf("%20s","");
117428     }
117429   }else{
117430     char *z;
117431     if( p->u.vtab.idxStr ){
117432       z = sqlite3_mprintf("(%d,\"%s\",%x)",
117433                 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
117434     }else{
117435       z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
117436     }
117437     sqlite3DebugPrintf(" %-19s", z);
117438     sqlite3_free(z);
117439   }
117440   if( p->wsFlags & WHERE_SKIPSCAN ){
117441     sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->u.btree.nSkip);
117442   }else{
117443     sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
117444   }
117445   sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
117446   if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
117447     int i;
117448     for(i=0; i<p->nLTerm; i++){
117449       whereTermPrint(p->aLTerm[i], i);
117450     }
117451   }
117452 }
117453 #endif
117454 
117455 /*
117456 ** Convert bulk memory into a valid WhereLoop that can be passed
117457 ** to whereLoopClear harmlessly.
117458 */
117459 static void whereLoopInit(WhereLoop *p){
117460   p->aLTerm = p->aLTermSpace;
117461   p->nLTerm = 0;
117462   p->nLSlot = ArraySize(p->aLTermSpace);
117463   p->wsFlags = 0;
117464 }
117465 
117466 /*
117467 ** Clear the WhereLoop.u union.  Leave WhereLoop.pLTerm intact.
117468 */
117469 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
117470   if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
117471     if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
117472       sqlite3_free(p->u.vtab.idxStr);
117473       p->u.vtab.needFree = 0;
117474       p->u.vtab.idxStr = 0;
117475     }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
117476       sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
117477       sqlite3KeyInfoUnref(p->u.btree.pIndex->pKeyInfo);
117478       sqlite3DbFree(db, p->u.btree.pIndex);
117479       p->u.btree.pIndex = 0;
117480     }
117481   }
117482 }
117483 
117484 /*
117485 ** Deallocate internal memory used by a WhereLoop object
117486 */
117487 static void whereLoopClear(sqlite3 *db, WhereLoop *p){
117488   if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
117489   whereLoopClearUnion(db, p);
117490   whereLoopInit(p);
117491 }
117492 
117493 /*
117494 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
117495 */
117496 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
117497   WhereTerm **paNew;
117498   if( p->nLSlot>=n ) return SQLITE_OK;
117499   n = (n+7)&~7;
117500   paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
117501   if( paNew==0 ) return SQLITE_NOMEM;
117502   memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
117503   if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
117504   p->aLTerm = paNew;
117505   p->nLSlot = n;
117506   return SQLITE_OK;
117507 }
117508 
117509 /*
117510 ** Transfer content from the second pLoop into the first.
117511 */
117512 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
117513   whereLoopClearUnion(db, pTo);
117514   if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
117515     memset(&pTo->u, 0, sizeof(pTo->u));
117516     return SQLITE_NOMEM;
117517   }
117518   memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
117519   memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
117520   if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
117521     pFrom->u.vtab.needFree = 0;
117522   }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
117523     pFrom->u.btree.pIndex = 0;
117524   }
117525   return SQLITE_OK;
117526 }
117527 
117528 /*
117529 ** Delete a WhereLoop object
117530 */
117531 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
117532   whereLoopClear(db, p);
117533   sqlite3DbFree(db, p);
117534 }
117535 
117536 /*
117537 ** Free a WhereInfo structure
117538 */
117539 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
117540   if( ALWAYS(pWInfo) ){
117541     whereClauseClear(&pWInfo->sWC);
117542     while( pWInfo->pLoops ){
117543       WhereLoop *p = pWInfo->pLoops;
117544       pWInfo->pLoops = p->pNextLoop;
117545       whereLoopDelete(db, p);
117546     }
117547     sqlite3DbFree(db, pWInfo);
117548   }
117549 }
117550 
117551 /*
117552 ** Return TRUE if both of the following are true:
117553 **
117554 **   (1)  X has the same or lower cost that Y
117555 **   (2)  X is a proper subset of Y
117556 **
117557 ** By "proper subset" we mean that X uses fewer WHERE clause terms
117558 ** than Y and that every WHERE clause term used by X is also used
117559 ** by Y.
117560 **
117561 ** If X is a proper subset of Y then Y is a better choice and ought
117562 ** to have a lower cost.  This routine returns TRUE when that cost
117563 ** relationship is inverted and needs to be adjusted.
117564 */
117565 static int whereLoopCheaperProperSubset(
117566   const WhereLoop *pX,       /* First WhereLoop to compare */
117567   const WhereLoop *pY        /* Compare against this WhereLoop */
117568 ){
117569   int i, j;
117570   if( pX->nLTerm >= pY->nLTerm ) return 0; /* X is not a subset of Y */
117571   if( pX->rRun >= pY->rRun ){
117572     if( pX->rRun > pY->rRun ) return 0;    /* X costs more than Y */
117573     if( pX->nOut > pY->nOut ) return 0;    /* X costs more than Y */
117574   }
117575   for(i=pX->nLTerm-1; i>=0; i--){
117576     for(j=pY->nLTerm-1; j>=0; j--){
117577       if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
117578     }
117579     if( j<0 ) return 0;  /* X not a subset of Y since term X[i] not used by Y */
117580   }
117581   return 1;  /* All conditions meet */
117582 }
117583 
117584 /*
117585 ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
117586 ** that:
117587 **
117588 **   (1) pTemplate costs less than any other WhereLoops that are a proper
117589 **       subset of pTemplate
117590 **
117591 **   (2) pTemplate costs more than any other WhereLoops for which pTemplate
117592 **       is a proper subset.
117593 **
117594 ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
117595 ** WHERE clause terms than Y and that every WHERE clause term used by X is
117596 ** also used by Y.
117597 **
117598 ** This adjustment is omitted for SKIPSCAN loops.  In a SKIPSCAN loop, the
117599 ** WhereLoop.nLTerm field is not an accurate measure of the number of WHERE
117600 ** clause terms covered, since some of the first nLTerm entries in aLTerm[]
117601 ** will be NULL (because they are skipped).  That makes it more difficult
117602 ** to compare the loops.  We could add extra code to do the comparison, and
117603 ** perhaps we will someday.  But SKIPSCAN is sufficiently uncommon, and this
117604 ** adjustment is sufficient minor, that it is very difficult to construct
117605 ** a test case where the extra code would improve the query plan.  Better
117606 ** to avoid the added complexity and just omit cost adjustments to SKIPSCAN
117607 ** loops.
117608 */
117609 static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
117610   if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
117611   if( (pTemplate->wsFlags & WHERE_SKIPSCAN)!=0 ) return;
117612   for(; p; p=p->pNextLoop){
117613     if( p->iTab!=pTemplate->iTab ) continue;
117614     if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
117615     if( (p->wsFlags & WHERE_SKIPSCAN)!=0 ) continue;
117616     if( whereLoopCheaperProperSubset(p, pTemplate) ){
117617       /* Adjust pTemplate cost downward so that it is cheaper than its
117618       ** subset p */
117619       pTemplate->rRun = p->rRun;
117620       pTemplate->nOut = p->nOut - 1;
117621     }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
117622       /* Adjust pTemplate cost upward so that it is costlier than p since
117623       ** pTemplate is a proper subset of p */
117624       pTemplate->rRun = p->rRun;
117625       pTemplate->nOut = p->nOut + 1;
117626     }
117627   }
117628 }
117629 
117630 /*
117631 ** Search the list of WhereLoops in *ppPrev looking for one that can be
117632 ** supplanted by pTemplate.
117633 **
117634 ** Return NULL if the WhereLoop list contains an entry that can supplant
117635 ** pTemplate, in other words if pTemplate does not belong on the list.
117636 **
117637 ** If pX is a WhereLoop that pTemplate can supplant, then return the
117638 ** link that points to pX.
117639 **
117640 ** If pTemplate cannot supplant any existing element of the list but needs
117641 ** to be added to the list, then return a pointer to the tail of the list.
117642 */
117643 static WhereLoop **whereLoopFindLesser(
117644   WhereLoop **ppPrev,
117645   const WhereLoop *pTemplate
117646 ){
117647   WhereLoop *p;
117648   for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
117649     if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
117650       /* If either the iTab or iSortIdx values for two WhereLoop are different
117651       ** then those WhereLoops need to be considered separately.  Neither is
117652       ** a candidate to replace the other. */
117653       continue;
117654     }
117655     /* In the current implementation, the rSetup value is either zero
117656     ** or the cost of building an automatic index (NlogN) and the NlogN
117657     ** is the same for compatible WhereLoops. */
117658     assert( p->rSetup==0 || pTemplate->rSetup==0
117659                  || p->rSetup==pTemplate->rSetup );
117660 
117661     /* whereLoopAddBtree() always generates and inserts the automatic index
117662     ** case first.  Hence compatible candidate WhereLoops never have a larger
117663     ** rSetup. Call this SETUP-INVARIANT */
117664     assert( p->rSetup>=pTemplate->rSetup );
117665 
117666     /* Any loop using an appliation-defined index (or PRIMARY KEY or
117667     ** UNIQUE constraint) with one or more == constraints is better
117668     ** than an automatic index. */
117669     if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
117670      && (pTemplate->wsFlags & WHERE_INDEXED)!=0
117671      && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
117672      && (p->prereq & pTemplate->prereq)==pTemplate->prereq
117673     ){
117674       break;
117675     }
117676 
117677     /* If existing WhereLoop p is better than pTemplate, pTemplate can be
117678     ** discarded.  WhereLoop p is better if:
117679     **   (1)  p has no more dependencies than pTemplate, and
117680     **   (2)  p has an equal or lower cost than pTemplate
117681     */
117682     if( (p->prereq & pTemplate->prereq)==p->prereq    /* (1)  */
117683      && p->rSetup<=pTemplate->rSetup                  /* (2a) */
117684      && p->rRun<=pTemplate->rRun                      /* (2b) */
117685      && p->nOut<=pTemplate->nOut                      /* (2c) */
117686     ){
117687       return 0;  /* Discard pTemplate */
117688     }
117689 
117690     /* If pTemplate is always better than p, then cause p to be overwritten
117691     ** with pTemplate.  pTemplate is better than p if:
117692     **   (1)  pTemplate has no more dependences than p, and
117693     **   (2)  pTemplate has an equal or lower cost than p.
117694     */
117695     if( (p->prereq & pTemplate->prereq)==pTemplate->prereq   /* (1)  */
117696      && p->rRun>=pTemplate->rRun                             /* (2a) */
117697      && p->nOut>=pTemplate->nOut                             /* (2b) */
117698     ){
117699       assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
117700       break;   /* Cause p to be overwritten by pTemplate */
117701     }
117702   }
117703   return ppPrev;
117704 }
117705 
117706 /*
117707 ** Insert or replace a WhereLoop entry using the template supplied.
117708 **
117709 ** An existing WhereLoop entry might be overwritten if the new template
117710 ** is better and has fewer dependencies.  Or the template will be ignored
117711 ** and no insert will occur if an existing WhereLoop is faster and has
117712 ** fewer dependencies than the template.  Otherwise a new WhereLoop is
117713 ** added based on the template.
117714 **
117715 ** If pBuilder->pOrSet is not NULL then we care about only the
117716 ** prerequisites and rRun and nOut costs of the N best loops.  That
117717 ** information is gathered in the pBuilder->pOrSet object.  This special
117718 ** processing mode is used only for OR clause processing.
117719 **
117720 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
117721 ** still might overwrite similar loops with the new template if the
117722 ** new template is better.  Loops may be overwritten if the following
117723 ** conditions are met:
117724 **
117725 **    (1)  They have the same iTab.
117726 **    (2)  They have the same iSortIdx.
117727 **    (3)  The template has same or fewer dependencies than the current loop
117728 **    (4)  The template has the same or lower cost than the current loop
117729 */
117730 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
117731   WhereLoop **ppPrev, *p;
117732   WhereInfo *pWInfo = pBuilder->pWInfo;
117733   sqlite3 *db = pWInfo->pParse->db;
117734 
117735   /* If pBuilder->pOrSet is defined, then only keep track of the costs
117736   ** and prereqs.
117737   */
117738   if( pBuilder->pOrSet!=0 ){
117739 #if WHERETRACE_ENABLED
117740     u16 n = pBuilder->pOrSet->n;
117741     int x =
117742 #endif
117743     whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
117744                                     pTemplate->nOut);
117745 #if WHERETRACE_ENABLED /* 0x8 */
117746     if( sqlite3WhereTrace & 0x8 ){
117747       sqlite3DebugPrintf(x?"   or-%d:  ":"   or-X:  ", n);
117748       whereLoopPrint(pTemplate, pBuilder->pWC);
117749     }
117750 #endif
117751     return SQLITE_OK;
117752   }
117753 
117754   /* Look for an existing WhereLoop to replace with pTemplate
117755   */
117756   whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
117757   ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
117758 
117759   if( ppPrev==0 ){
117760     /* There already exists a WhereLoop on the list that is better
117761     ** than pTemplate, so just ignore pTemplate */
117762 #if WHERETRACE_ENABLED /* 0x8 */
117763     if( sqlite3WhereTrace & 0x8 ){
117764       sqlite3DebugPrintf("   skip: ");
117765       whereLoopPrint(pTemplate, pBuilder->pWC);
117766     }
117767 #endif
117768     return SQLITE_OK;
117769   }else{
117770     p = *ppPrev;
117771   }
117772 
117773   /* If we reach this point it means that either p[] should be overwritten
117774   ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
117775   ** WhereLoop and insert it.
117776   */
117777 #if WHERETRACE_ENABLED /* 0x8 */
117778   if( sqlite3WhereTrace & 0x8 ){
117779     if( p!=0 ){
117780       sqlite3DebugPrintf("replace: ");
117781       whereLoopPrint(p, pBuilder->pWC);
117782     }
117783     sqlite3DebugPrintf("    add: ");
117784     whereLoopPrint(pTemplate, pBuilder->pWC);
117785   }
117786 #endif
117787   if( p==0 ){
117788     /* Allocate a new WhereLoop to add to the end of the list */
117789     *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
117790     if( p==0 ) return SQLITE_NOMEM;
117791     whereLoopInit(p);
117792     p->pNextLoop = 0;
117793   }else{
117794     /* We will be overwriting WhereLoop p[].  But before we do, first
117795     ** go through the rest of the list and delete any other entries besides
117796     ** p[] that are also supplated by pTemplate */
117797     WhereLoop **ppTail = &p->pNextLoop;
117798     WhereLoop *pToDel;
117799     while( *ppTail ){
117800       ppTail = whereLoopFindLesser(ppTail, pTemplate);
117801       if( ppTail==0 ) break;
117802       pToDel = *ppTail;
117803       if( pToDel==0 ) break;
117804       *ppTail = pToDel->pNextLoop;
117805 #if WHERETRACE_ENABLED /* 0x8 */
117806       if( sqlite3WhereTrace & 0x8 ){
117807         sqlite3DebugPrintf(" delete: ");
117808         whereLoopPrint(pToDel, pBuilder->pWC);
117809       }
117810 #endif
117811       whereLoopDelete(db, pToDel);
117812     }
117813   }
117814   whereLoopXfer(db, p, pTemplate);
117815   if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
117816     Index *pIndex = p->u.btree.pIndex;
117817     if( pIndex && pIndex->tnum==0 ){
117818       p->u.btree.pIndex = 0;
117819     }
117820   }
117821   return SQLITE_OK;
117822 }
117823 
117824 /*
117825 ** Adjust the WhereLoop.nOut value downward to account for terms of the
117826 ** WHERE clause that reference the loop but which are not used by an
117827 ** index.
117828 **
117829 ** In the current implementation, the first extra WHERE clause term reduces
117830 ** the number of output rows by a factor of 10 and each additional term
117831 ** reduces the number of output rows by sqrt(2).
117832 */
117833 static void whereLoopOutputAdjust(
117834   WhereClause *pWC,      /* The WHERE clause */
117835   WhereLoop *pLoop,      /* The loop to adjust downward */
117836   LogEst nRow            /* Number of rows in the entire table */
117837 ){
117838   WhereTerm *pTerm, *pX;
117839   Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
117840   int i, j;
117841   int nEq = 0;    /* Number of = constraints not within likely()/unlikely() */
117842 
117843   for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
117844     if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
117845     if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
117846     if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
117847     for(j=pLoop->nLTerm-1; j>=0; j--){
117848       pX = pLoop->aLTerm[j];
117849       if( pX==0 ) continue;
117850       if( pX==pTerm ) break;
117851       if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
117852     }
117853     if( j<0 ){
117854       if( pTerm->truthProb<=0 ){
117855         pLoop->nOut += pTerm->truthProb;
117856       }else{
117857         pLoop->nOut--;
117858         if( pTerm->eOperator&WO_EQ ) nEq++;
117859       }
117860     }
117861   }
117862   /* TUNING:  If there is at least one equality constraint in the WHERE
117863   ** clause that does not have a likelihood() explicitly assigned to it
117864   ** then do not let the estimated number of output rows exceed half
117865   ** the number of rows in the table. */
117866   if( nEq && pLoop->nOut>nRow-10 ){
117867     pLoop->nOut = nRow - 10;
117868   }
117869 }
117870 
117871 /*
117872 ** Adjust the cost C by the costMult facter T.  This only occurs if
117873 ** compiled with -DSQLITE_ENABLE_COSTMULT
117874 */
117875 #ifdef SQLITE_ENABLE_COSTMULT
117876 # define ApplyCostMultiplier(C,T)  C += T
117877 #else
117878 # define ApplyCostMultiplier(C,T)
117879 #endif
117880 
117881 /*
117882 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
117883 ** index pIndex. Try to match one more.
117884 **
117885 ** When this function is called, pBuilder->pNew->nOut contains the
117886 ** number of rows expected to be visited by filtering using the nEq
117887 ** terms only. If it is modified, this value is restored before this
117888 ** function returns.
117889 **
117890 ** If pProbe->tnum==0, that means pIndex is a fake index used for the
117891 ** INTEGER PRIMARY KEY.
117892 */
117893 static int whereLoopAddBtreeIndex(
117894   WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */
117895   struct SrcList_item *pSrc,      /* FROM clause term being analyzed */
117896   Index *pProbe,                  /* An index on pSrc */
117897   LogEst nInMul                   /* log(Number of iterations due to IN) */
117898 ){
117899   WhereInfo *pWInfo = pBuilder->pWInfo;  /* WHERE analyse context */
117900   Parse *pParse = pWInfo->pParse;        /* Parsing context */
117901   sqlite3 *db = pParse->db;       /* Database connection malloc context */
117902   WhereLoop *pNew;                /* Template WhereLoop under construction */
117903   WhereTerm *pTerm;               /* A WhereTerm under consideration */
117904   int opMask;                     /* Valid operators for constraints */
117905   WhereScan scan;                 /* Iterator for WHERE terms */
117906   Bitmask saved_prereq;           /* Original value of pNew->prereq */
117907   u16 saved_nLTerm;               /* Original value of pNew->nLTerm */
117908   u16 saved_nEq;                  /* Original value of pNew->u.btree.nEq */
117909   u16 saved_nSkip;                /* Original value of pNew->u.btree.nSkip */
117910   u32 saved_wsFlags;              /* Original value of pNew->wsFlags */
117911   LogEst saved_nOut;              /* Original value of pNew->nOut */
117912   int iCol;                       /* Index of the column in the table */
117913   int rc = SQLITE_OK;             /* Return code */
117914   LogEst rSize;                   /* Number of rows in the table */
117915   LogEst rLogSize;                /* Logarithm of table size */
117916   WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
117917 
117918   pNew = pBuilder->pNew;
117919   if( db->mallocFailed ) return SQLITE_NOMEM;
117920 
117921   assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
117922   assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
117923   if( pNew->wsFlags & WHERE_BTM_LIMIT ){
117924     opMask = WO_LT|WO_LE;
117925   }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
117926     opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
117927   }else{
117928     opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
117929   }
117930   if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
117931 
117932   assert( pNew->u.btree.nEq<pProbe->nColumn );
117933   iCol = pProbe->aiColumn[pNew->u.btree.nEq];
117934 
117935   pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
117936                         opMask, pProbe);
117937   saved_nEq = pNew->u.btree.nEq;
117938   saved_nSkip = pNew->u.btree.nSkip;
117939   saved_nLTerm = pNew->nLTerm;
117940   saved_wsFlags = pNew->wsFlags;
117941   saved_prereq = pNew->prereq;
117942   saved_nOut = pNew->nOut;
117943   pNew->rSetup = 0;
117944   rSize = pProbe->aiRowLogEst[0];
117945   rLogSize = estLog(rSize);
117946 
117947   /* Consider using a skip-scan if there are no WHERE clause constraints
117948   ** available for the left-most terms of the index, and if the average
117949   ** number of repeats in the left-most terms is at least 18.
117950   **
117951   ** The magic number 18 is selected on the basis that scanning 17 rows
117952   ** is almost always quicker than an index seek (even though if the index
117953   ** contains fewer than 2^17 rows we assume otherwise in other parts of
117954   ** the code). And, even if it is not, it should not be too much slower.
117955   ** On the other hand, the extra seeks could end up being significantly
117956   ** more expensive.  */
117957   assert( 42==sqlite3LogEst(18) );
117958   if( saved_nEq==saved_nSkip
117959    && saved_nEq+1<pProbe->nKeyCol
117960    && pProbe->aiRowLogEst[saved_nEq+1]>=42  /* TUNING: Minimum for skip-scan */
117961    && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
117962   ){
117963     LogEst nIter;
117964     pNew->u.btree.nEq++;
117965     pNew->u.btree.nSkip++;
117966     pNew->aLTerm[pNew->nLTerm++] = 0;
117967     pNew->wsFlags |= WHERE_SKIPSCAN;
117968     nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
117969     if( pTerm ){
117970       /* TUNING:  When estimating skip-scan for a term that is also indexable,
117971       ** multiply the cost of the skip-scan by 2.0, to make it a little less
117972       ** desirable than the regular index lookup. */
117973       nIter += 10;  assert( 10==sqlite3LogEst(2) );
117974     }
117975     pNew->nOut -= nIter;
117976     /* TUNING:  Because uncertainties in the estimates for skip-scan queries,
117977     ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
117978     nIter += 5;
117979     whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
117980     pNew->nOut = saved_nOut;
117981     pNew->u.btree.nEq = saved_nEq;
117982     pNew->u.btree.nSkip = saved_nSkip;
117983   }
117984   for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
117985     u16 eOp = pTerm->eOperator;   /* Shorthand for pTerm->eOperator */
117986     LogEst rCostIdx;
117987     LogEst nOutUnadjusted;        /* nOut before IN() and WHERE adjustments */
117988     int nIn = 0;
117989 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
117990     int nRecValid = pBuilder->nRecValid;
117991 #endif
117992     if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
117993      && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
117994     ){
117995       continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
117996     }
117997     if( pTerm->prereqRight & pNew->maskSelf ) continue;
117998 
117999     pNew->wsFlags = saved_wsFlags;
118000     pNew->u.btree.nEq = saved_nEq;
118001     pNew->nLTerm = saved_nLTerm;
118002     if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
118003     pNew->aLTerm[pNew->nLTerm++] = pTerm;
118004     pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
118005 
118006     assert( nInMul==0
118007         || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
118008         || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
118009         || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
118010     );
118011 
118012     if( eOp & WO_IN ){
118013       Expr *pExpr = pTerm->pExpr;
118014       pNew->wsFlags |= WHERE_COLUMN_IN;
118015       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
118016         /* "x IN (SELECT ...)":  TUNING: the SELECT returns 25 rows */
118017         nIn = 46;  assert( 46==sqlite3LogEst(25) );
118018       }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
118019         /* "x IN (value, value, ...)" */
118020         nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
118021       }
118022       assert( nIn>0 );  /* RHS always has 2 or more terms...  The parser
118023                         ** changes "x IN (?)" into "x=?". */
118024 
118025     }else if( eOp & (WO_EQ) ){
118026       pNew->wsFlags |= WHERE_COLUMN_EQ;
118027       if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1) ){
118028         if( iCol>=0 && !IsUniqueIndex(pProbe) ){
118029           pNew->wsFlags |= WHERE_UNQ_WANTED;
118030         }else{
118031           pNew->wsFlags |= WHERE_ONEROW;
118032         }
118033       }
118034     }else if( eOp & WO_ISNULL ){
118035       pNew->wsFlags |= WHERE_COLUMN_NULL;
118036     }else if( eOp & (WO_GT|WO_GE) ){
118037       testcase( eOp & WO_GT );
118038       testcase( eOp & WO_GE );
118039       pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
118040       pBtm = pTerm;
118041       pTop = 0;
118042     }else{
118043       assert( eOp & (WO_LT|WO_LE) );
118044       testcase( eOp & WO_LT );
118045       testcase( eOp & WO_LE );
118046       pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
118047       pTop = pTerm;
118048       pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
118049                      pNew->aLTerm[pNew->nLTerm-2] : 0;
118050     }
118051 
118052     /* At this point pNew->nOut is set to the number of rows expected to
118053     ** be visited by the index scan before considering term pTerm, or the
118054     ** values of nIn and nInMul. In other words, assuming that all
118055     ** "x IN(...)" terms are replaced with "x = ?". This block updates
118056     ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul).  */
118057     assert( pNew->nOut==saved_nOut );
118058     if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
118059       /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
118060       ** data, using some other estimate.  */
118061       whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
118062     }else{
118063       int nEq = ++pNew->u.btree.nEq;
118064       assert( eOp & (WO_ISNULL|WO_EQ|WO_IN) );
118065 
118066       assert( pNew->nOut==saved_nOut );
118067       if( pTerm->truthProb<=0 && iCol>=0 ){
118068         assert( (eOp & WO_IN) || nIn==0 );
118069         testcase( eOp & WO_IN );
118070         pNew->nOut += pTerm->truthProb;
118071         pNew->nOut -= nIn;
118072       }else{
118073 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
118074         tRowcnt nOut = 0;
118075         if( nInMul==0
118076          && pProbe->nSample
118077          && pNew->u.btree.nEq<=pProbe->nSampleCol
118078          && OptimizationEnabled(db, SQLITE_Stat3)
118079          && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
118080         ){
118081           Expr *pExpr = pTerm->pExpr;
118082           if( (eOp & (WO_EQ|WO_ISNULL))!=0 ){
118083             testcase( eOp & WO_EQ );
118084             testcase( eOp & WO_ISNULL );
118085             rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
118086           }else{
118087             rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
118088           }
118089           if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
118090           if( rc!=SQLITE_OK ) break;          /* Jump out of the pTerm loop */
118091           if( nOut ){
118092             pNew->nOut = sqlite3LogEst(nOut);
118093             if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
118094             pNew->nOut -= nIn;
118095           }
118096         }
118097         if( nOut==0 )
118098 #endif
118099         {
118100           pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
118101           if( eOp & WO_ISNULL ){
118102             /* TUNING: If there is no likelihood() value, assume that a
118103             ** "col IS NULL" expression matches twice as many rows
118104             ** as (col=?). */
118105             pNew->nOut += 10;
118106           }
118107         }
118108       }
118109     }
118110 
118111     /* Set rCostIdx to the cost of visiting selected rows in index. Add
118112     ** it to pNew->rRun, which is currently set to the cost of the index
118113     ** seek only. Then, if this is a non-covering index, add the cost of
118114     ** visiting the rows in the main table.  */
118115     rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
118116     pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
118117     if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
118118       pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
118119     }
118120     ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
118121 
118122     nOutUnadjusted = pNew->nOut;
118123     pNew->rRun += nInMul + nIn;
118124     pNew->nOut += nInMul + nIn;
118125     whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
118126     rc = whereLoopInsert(pBuilder, pNew);
118127 
118128     if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
118129       pNew->nOut = saved_nOut;
118130     }else{
118131       pNew->nOut = nOutUnadjusted;
118132     }
118133 
118134     if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
118135      && pNew->u.btree.nEq<pProbe->nColumn
118136     ){
118137       whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
118138     }
118139     pNew->nOut = saved_nOut;
118140 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
118141     pBuilder->nRecValid = nRecValid;
118142 #endif
118143   }
118144   pNew->prereq = saved_prereq;
118145   pNew->u.btree.nEq = saved_nEq;
118146   pNew->u.btree.nSkip = saved_nSkip;
118147   pNew->wsFlags = saved_wsFlags;
118148   pNew->nOut = saved_nOut;
118149   pNew->nLTerm = saved_nLTerm;
118150   return rc;
118151 }
118152 
118153 /*
118154 ** Return True if it is possible that pIndex might be useful in
118155 ** implementing the ORDER BY clause in pBuilder.
118156 **
118157 ** Return False if pBuilder does not contain an ORDER BY clause or
118158 ** if there is no way for pIndex to be useful in implementing that
118159 ** ORDER BY clause.
118160 */
118161 static int indexMightHelpWithOrderBy(
118162   WhereLoopBuilder *pBuilder,
118163   Index *pIndex,
118164   int iCursor
118165 ){
118166   ExprList *pOB;
118167   int ii, jj;
118168 
118169   if( pIndex->bUnordered ) return 0;
118170   if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
118171   for(ii=0; ii<pOB->nExpr; ii++){
118172     Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
118173     if( pExpr->op!=TK_COLUMN ) return 0;
118174     if( pExpr->iTable==iCursor ){
118175       if( pExpr->iColumn<0 ) return 1;
118176       for(jj=0; jj<pIndex->nKeyCol; jj++){
118177         if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
118178       }
118179     }
118180   }
118181   return 0;
118182 }
118183 
118184 /*
118185 ** Return a bitmask where 1s indicate that the corresponding column of
118186 ** the table is used by an index.  Only the first 63 columns are considered.
118187 */
118188 static Bitmask columnsInIndex(Index *pIdx){
118189   Bitmask m = 0;
118190   int j;
118191   for(j=pIdx->nColumn-1; j>=0; j--){
118192     int x = pIdx->aiColumn[j];
118193     if( x>=0 ){
118194       testcase( x==BMS-1 );
118195       testcase( x==BMS-2 );
118196       if( x<BMS-1 ) m |= MASKBIT(x);
118197     }
118198   }
118199   return m;
118200 }
118201 
118202 /* Check to see if a partial index with pPartIndexWhere can be used
118203 ** in the current query.  Return true if it can be and false if not.
118204 */
118205 static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
118206   int i;
118207   WhereTerm *pTerm;
118208   for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
118209     if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
118210   }
118211   return 0;
118212 }
118213 
118214 /*
118215 ** Add all WhereLoop objects for a single table of the join where the table
118216 ** is idenfied by pBuilder->pNew->iTab.  That table is guaranteed to be
118217 ** a b-tree table, not a virtual table.
118218 **
118219 ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
118220 ** are calculated as follows:
118221 **
118222 ** For a full scan, assuming the table (or index) contains nRow rows:
118223 **
118224 **     cost = nRow * 3.0                    // full-table scan
118225 **     cost = nRow * K                      // scan of covering index
118226 **     cost = nRow * (K+3.0)                // scan of non-covering index
118227 **
118228 ** where K is a value between 1.1 and 3.0 set based on the relative
118229 ** estimated average size of the index and table records.
118230 **
118231 ** For an index scan, where nVisit is the number of index rows visited
118232 ** by the scan, and nSeek is the number of seek operations required on
118233 ** the index b-tree:
118234 **
118235 **     cost = nSeek * (log(nRow) + K * nVisit)          // covering index
118236 **     cost = nSeek * (log(nRow) + (K+3.0) * nVisit)    // non-covering index
118237 **
118238 ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
118239 ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
118240 ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
118241 **
118242 ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
118243 ** of uncertainty.  For this reason, scoring is designed to pick plans that
118244 ** "do the least harm" if the estimates are inaccurate.  For example, a
118245 ** log(nRow) factor is omitted from a non-covering index scan in order to
118246 ** bias the scoring in favor of using an index, since the worst-case
118247 ** performance of using an index is far better than the worst-case performance
118248 ** of a full table scan.
118249 */
118250 static int whereLoopAddBtree(
118251   WhereLoopBuilder *pBuilder, /* WHERE clause information */
118252   Bitmask mExtra              /* Extra prerequesites for using this table */
118253 ){
118254   WhereInfo *pWInfo;          /* WHERE analysis context */
118255   Index *pProbe;              /* An index we are evaluating */
118256   Index sPk;                  /* A fake index object for the primary key */
118257   LogEst aiRowEstPk[2];       /* The aiRowLogEst[] value for the sPk index */
118258   i16 aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
118259   SrcList *pTabList;          /* The FROM clause */
118260   struct SrcList_item *pSrc;  /* The FROM clause btree term to add */
118261   WhereLoop *pNew;            /* Template WhereLoop object */
118262   int rc = SQLITE_OK;         /* Return code */
118263   int iSortIdx = 1;           /* Index number */
118264   int b;                      /* A boolean value */
118265   LogEst rSize;               /* number of rows in the table */
118266   LogEst rLogSize;            /* Logarithm of the number of rows in the table */
118267   WhereClause *pWC;           /* The parsed WHERE clause */
118268   Table *pTab;                /* Table being queried */
118269 
118270   pNew = pBuilder->pNew;
118271   pWInfo = pBuilder->pWInfo;
118272   pTabList = pWInfo->pTabList;
118273   pSrc = pTabList->a + pNew->iTab;
118274   pTab = pSrc->pTab;
118275   pWC = pBuilder->pWC;
118276   assert( !IsVirtual(pSrc->pTab) );
118277 
118278   if( pSrc->pIndex ){
118279     /* An INDEXED BY clause specifies a particular index to use */
118280     pProbe = pSrc->pIndex;
118281   }else if( !HasRowid(pTab) ){
118282     pProbe = pTab->pIndex;
118283   }else{
118284     /* There is no INDEXED BY clause.  Create a fake Index object in local
118285     ** variable sPk to represent the rowid primary key index.  Make this
118286     ** fake index the first in a chain of Index objects with all of the real
118287     ** indices to follow */
118288     Index *pFirst;                  /* First of real indices on the table */
118289     memset(&sPk, 0, sizeof(Index));
118290     sPk.nKeyCol = 1;
118291     sPk.nColumn = 1;
118292     sPk.aiColumn = &aiColumnPk;
118293     sPk.aiRowLogEst = aiRowEstPk;
118294     sPk.onError = OE_Replace;
118295     sPk.pTable = pTab;
118296     sPk.szIdxRow = pTab->szTabRow;
118297     aiRowEstPk[0] = pTab->nRowLogEst;
118298     aiRowEstPk[1] = 0;
118299     pFirst = pSrc->pTab->pIndex;
118300     if( pSrc->notIndexed==0 ){
118301       /* The real indices of the table are only considered if the
118302       ** NOT INDEXED qualifier is omitted from the FROM clause */
118303       sPk.pNext = pFirst;
118304     }
118305     pProbe = &sPk;
118306   }
118307   rSize = pTab->nRowLogEst;
118308   rLogSize = estLog(rSize);
118309 
118310 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
118311   /* Automatic indexes */
118312   if( !pBuilder->pOrSet
118313    && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
118314    && pSrc->pIndex==0
118315    && !pSrc->viaCoroutine
118316    && !pSrc->notIndexed
118317    && HasRowid(pTab)
118318    && !pSrc->isCorrelated
118319    && !pSrc->isRecursive
118320   ){
118321     /* Generate auto-index WhereLoops */
118322     WhereTerm *pTerm;
118323     WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
118324     for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
118325       if( pTerm->prereqRight & pNew->maskSelf ) continue;
118326       if( termCanDriveIndex(pTerm, pSrc, 0) ){
118327         pNew->u.btree.nEq = 1;
118328         pNew->u.btree.nSkip = 0;
118329         pNew->u.btree.pIndex = 0;
118330         pNew->nLTerm = 1;
118331         pNew->aLTerm[0] = pTerm;
118332         /* TUNING: One-time cost for computing the automatic index is
118333         ** estimated to be X*N*log2(N) where N is the number of rows in
118334         ** the table being indexed and where X is 7 (LogEst=28) for normal
118335         ** tables or 1.375 (LogEst=4) for views and subqueries.  The value
118336         ** of X is smaller for views and subqueries so that the query planner
118337         ** will be more aggressive about generating automatic indexes for
118338         ** those objects, since there is no opportunity to add schema
118339         ** indexes on subqueries and views. */
118340         pNew->rSetup = rLogSize + rSize + 4;
118341         if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
118342           pNew->rSetup += 24;
118343         }
118344         ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
118345         /* TUNING: Each index lookup yields 20 rows in the table.  This
118346         ** is more than the usual guess of 10 rows, since we have no way
118347         ** of knowing how selective the index will ultimately be.  It would
118348         ** not be unreasonable to make this value much larger. */
118349         pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );
118350         pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
118351         pNew->wsFlags = WHERE_AUTO_INDEX;
118352         pNew->prereq = mExtra | pTerm->prereqRight;
118353         rc = whereLoopInsert(pBuilder, pNew);
118354       }
118355     }
118356   }
118357 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
118358 
118359   /* Loop over all indices
118360   */
118361   for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
118362     if( pProbe->pPartIdxWhere!=0
118363      && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
118364       testcase( pNew->iTab!=pSrc->iCursor );  /* See ticket [98d973b8f5] */
118365       continue;  /* Partial index inappropriate for this query */
118366     }
118367     rSize = pProbe->aiRowLogEst[0];
118368     pNew->u.btree.nEq = 0;
118369     pNew->u.btree.nSkip = 0;
118370     pNew->nLTerm = 0;
118371     pNew->iSortIdx = 0;
118372     pNew->rSetup = 0;
118373     pNew->prereq = mExtra;
118374     pNew->nOut = rSize;
118375     pNew->u.btree.pIndex = pProbe;
118376     b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
118377     /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
118378     assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
118379     if( pProbe->tnum<=0 ){
118380       /* Integer primary key index */
118381       pNew->wsFlags = WHERE_IPK;
118382 
118383       /* Full table scan */
118384       pNew->iSortIdx = b ? iSortIdx : 0;
118385       /* TUNING: Cost of full table scan is (N*3.0). */
118386       pNew->rRun = rSize + 16;
118387       ApplyCostMultiplier(pNew->rRun, pTab->costMult);
118388       whereLoopOutputAdjust(pWC, pNew, rSize);
118389       rc = whereLoopInsert(pBuilder, pNew);
118390       pNew->nOut = rSize;
118391       if( rc ) break;
118392     }else{
118393       Bitmask m;
118394       if( pProbe->isCovering ){
118395         pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
118396         m = 0;
118397       }else{
118398         m = pSrc->colUsed & ~columnsInIndex(pProbe);
118399         pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
118400       }
118401 
118402       /* Full scan via index */
118403       if( b
118404        || !HasRowid(pTab)
118405        || ( m==0
118406          && pProbe->bUnordered==0
118407          && (pProbe->szIdxRow<pTab->szTabRow)
118408          && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
118409          && sqlite3GlobalConfig.bUseCis
118410          && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
118411           )
118412       ){
118413         pNew->iSortIdx = b ? iSortIdx : 0;
118414 
118415         /* The cost of visiting the index rows is N*K, where K is
118416         ** between 1.1 and 3.0, depending on the relative sizes of the
118417         ** index and table rows. If this is a non-covering index scan,
118418         ** also add the cost of visiting table rows (N*3.0).  */
118419         pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
118420         if( m!=0 ){
118421           pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
118422         }
118423         ApplyCostMultiplier(pNew->rRun, pTab->costMult);
118424         whereLoopOutputAdjust(pWC, pNew, rSize);
118425         rc = whereLoopInsert(pBuilder, pNew);
118426         pNew->nOut = rSize;
118427         if( rc ) break;
118428       }
118429     }
118430 
118431     rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
118432 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
118433     sqlite3Stat4ProbeFree(pBuilder->pRec);
118434     pBuilder->nRecValid = 0;
118435     pBuilder->pRec = 0;
118436 #endif
118437 
118438     /* If there was an INDEXED BY clause, then only that one index is
118439     ** considered. */
118440     if( pSrc->pIndex ) break;
118441   }
118442   return rc;
118443 }
118444 
118445 #ifndef SQLITE_OMIT_VIRTUALTABLE
118446 /*
118447 ** Add all WhereLoop objects for a table of the join identified by
118448 ** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
118449 */
118450 static int whereLoopAddVirtual(
118451   WhereLoopBuilder *pBuilder,  /* WHERE clause information */
118452   Bitmask mExtra
118453 ){
118454   WhereInfo *pWInfo;           /* WHERE analysis context */
118455   Parse *pParse;               /* The parsing context */
118456   WhereClause *pWC;            /* The WHERE clause */
118457   struct SrcList_item *pSrc;   /* The FROM clause term to search */
118458   Table *pTab;
118459   sqlite3 *db;
118460   sqlite3_index_info *pIdxInfo;
118461   struct sqlite3_index_constraint *pIdxCons;
118462   struct sqlite3_index_constraint_usage *pUsage;
118463   WhereTerm *pTerm;
118464   int i, j;
118465   int iTerm, mxTerm;
118466   int nConstraint;
118467   int seenIn = 0;              /* True if an IN operator is seen */
118468   int seenVar = 0;             /* True if a non-constant constraint is seen */
118469   int iPhase;                  /* 0: const w/o IN, 1: const, 2: no IN,  2: IN */
118470   WhereLoop *pNew;
118471   int rc = SQLITE_OK;
118472 
118473   pWInfo = pBuilder->pWInfo;
118474   pParse = pWInfo->pParse;
118475   db = pParse->db;
118476   pWC = pBuilder->pWC;
118477   pNew = pBuilder->pNew;
118478   pSrc = &pWInfo->pTabList->a[pNew->iTab];
118479   pTab = pSrc->pTab;
118480   assert( IsVirtual(pTab) );
118481   pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
118482   if( pIdxInfo==0 ) return SQLITE_NOMEM;
118483   pNew->prereq = 0;
118484   pNew->rSetup = 0;
118485   pNew->wsFlags = WHERE_VIRTUALTABLE;
118486   pNew->nLTerm = 0;
118487   pNew->u.vtab.needFree = 0;
118488   pUsage = pIdxInfo->aConstraintUsage;
118489   nConstraint = pIdxInfo->nConstraint;
118490   if( whereLoopResize(db, pNew, nConstraint) ){
118491     sqlite3DbFree(db, pIdxInfo);
118492     return SQLITE_NOMEM;
118493   }
118494 
118495   for(iPhase=0; iPhase<=3; iPhase++){
118496     if( !seenIn && (iPhase&1)!=0 ){
118497       iPhase++;
118498       if( iPhase>3 ) break;
118499     }
118500     if( !seenVar && iPhase>1 ) break;
118501     pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
118502     for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
118503       j = pIdxCons->iTermOffset;
118504       pTerm = &pWC->a[j];
118505       switch( iPhase ){
118506         case 0:    /* Constants without IN operator */
118507           pIdxCons->usable = 0;
118508           if( (pTerm->eOperator & WO_IN)!=0 ){
118509             seenIn = 1;
118510           }
118511           if( pTerm->prereqRight!=0 ){
118512             seenVar = 1;
118513           }else if( (pTerm->eOperator & WO_IN)==0 ){
118514             pIdxCons->usable = 1;
118515           }
118516           break;
118517         case 1:    /* Constants with IN operators */
118518           assert( seenIn );
118519           pIdxCons->usable = (pTerm->prereqRight==0);
118520           break;
118521         case 2:    /* Variables without IN */
118522           assert( seenVar );
118523           pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
118524           break;
118525         default:   /* Variables with IN */
118526           assert( seenVar && seenIn );
118527           pIdxCons->usable = 1;
118528           break;
118529       }
118530     }
118531     memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
118532     if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
118533     pIdxInfo->idxStr = 0;
118534     pIdxInfo->idxNum = 0;
118535     pIdxInfo->needToFreeIdxStr = 0;
118536     pIdxInfo->orderByConsumed = 0;
118537     pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
118538     pIdxInfo->estimatedRows = 25;
118539     rc = vtabBestIndex(pParse, pTab, pIdxInfo);
118540     if( rc ) goto whereLoopAddVtab_exit;
118541     pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
118542     pNew->prereq = mExtra;
118543     mxTerm = -1;
118544     assert( pNew->nLSlot>=nConstraint );
118545     for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
118546     pNew->u.vtab.omitMask = 0;
118547     for(i=0; i<nConstraint; i++, pIdxCons++){
118548       if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
118549         j = pIdxCons->iTermOffset;
118550         if( iTerm>=nConstraint
118551          || j<0
118552          || j>=pWC->nTerm
118553          || pNew->aLTerm[iTerm]!=0
118554         ){
118555           rc = SQLITE_ERROR;
118556           sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
118557           goto whereLoopAddVtab_exit;
118558         }
118559         testcase( iTerm==nConstraint-1 );
118560         testcase( j==0 );
118561         testcase( j==pWC->nTerm-1 );
118562         pTerm = &pWC->a[j];
118563         pNew->prereq |= pTerm->prereqRight;
118564         assert( iTerm<pNew->nLSlot );
118565         pNew->aLTerm[iTerm] = pTerm;
118566         if( iTerm>mxTerm ) mxTerm = iTerm;
118567         testcase( iTerm==15 );
118568         testcase( iTerm==16 );
118569         if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
118570         if( (pTerm->eOperator & WO_IN)!=0 ){
118571           if( pUsage[i].omit==0 ){
118572             /* Do not attempt to use an IN constraint if the virtual table
118573             ** says that the equivalent EQ constraint cannot be safely omitted.
118574             ** If we do attempt to use such a constraint, some rows might be
118575             ** repeated in the output. */
118576             break;
118577           }
118578           /* A virtual table that is constrained by an IN clause may not
118579           ** consume the ORDER BY clause because (1) the order of IN terms
118580           ** is not necessarily related to the order of output terms and
118581           ** (2) Multiple outputs from a single IN value will not merge
118582           ** together.  */
118583           pIdxInfo->orderByConsumed = 0;
118584         }
118585       }
118586     }
118587     if( i>=nConstraint ){
118588       pNew->nLTerm = mxTerm+1;
118589       assert( pNew->nLTerm<=pNew->nLSlot );
118590       pNew->u.vtab.idxNum = pIdxInfo->idxNum;
118591       pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
118592       pIdxInfo->needToFreeIdxStr = 0;
118593       pNew->u.vtab.idxStr = pIdxInfo->idxStr;
118594       pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
118595                                       pIdxInfo->nOrderBy : 0);
118596       pNew->rSetup = 0;
118597       pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
118598       pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
118599       whereLoopInsert(pBuilder, pNew);
118600       if( pNew->u.vtab.needFree ){
118601         sqlite3_free(pNew->u.vtab.idxStr);
118602         pNew->u.vtab.needFree = 0;
118603       }
118604     }
118605   }
118606 
118607 whereLoopAddVtab_exit:
118608   if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
118609   sqlite3DbFree(db, pIdxInfo);
118610   return rc;
118611 }
118612 #endif /* SQLITE_OMIT_VIRTUALTABLE */
118613 
118614 /*
118615 ** Add WhereLoop entries to handle OR terms.  This works for either
118616 ** btrees or virtual tables.
118617 */
118618 static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
118619   WhereInfo *pWInfo = pBuilder->pWInfo;
118620   WhereClause *pWC;
118621   WhereLoop *pNew;
118622   WhereTerm *pTerm, *pWCEnd;
118623   int rc = SQLITE_OK;
118624   int iCur;
118625   WhereClause tempWC;
118626   WhereLoopBuilder sSubBuild;
118627   WhereOrSet sSum, sCur;
118628   struct SrcList_item *pItem;
118629 
118630   pWC = pBuilder->pWC;
118631   pWCEnd = pWC->a + pWC->nTerm;
118632   pNew = pBuilder->pNew;
118633   memset(&sSum, 0, sizeof(sSum));
118634   pItem = pWInfo->pTabList->a + pNew->iTab;
118635   iCur = pItem->iCursor;
118636 
118637   for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
118638     if( (pTerm->eOperator & WO_OR)!=0
118639      && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
118640     ){
118641       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
118642       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
118643       WhereTerm *pOrTerm;
118644       int once = 1;
118645       int i, j;
118646 
118647       sSubBuild = *pBuilder;
118648       sSubBuild.pOrderBy = 0;
118649       sSubBuild.pOrSet = &sCur;
118650 
118651       WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
118652       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
118653         if( (pOrTerm->eOperator & WO_AND)!=0 ){
118654           sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
118655         }else if( pOrTerm->leftCursor==iCur ){
118656           tempWC.pWInfo = pWC->pWInfo;
118657           tempWC.pOuter = pWC;
118658           tempWC.op = TK_AND;
118659           tempWC.nTerm = 1;
118660           tempWC.a = pOrTerm;
118661           sSubBuild.pWC = &tempWC;
118662         }else{
118663           continue;
118664         }
118665         sCur.n = 0;
118666 #ifdef WHERETRACE_ENABLED
118667         WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
118668                    (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
118669         if( sqlite3WhereTrace & 0x400 ){
118670           for(i=0; i<sSubBuild.pWC->nTerm; i++){
118671             whereTermPrint(&sSubBuild.pWC->a[i], i);
118672           }
118673         }
118674 #endif
118675 #ifndef SQLITE_OMIT_VIRTUALTABLE
118676         if( IsVirtual(pItem->pTab) ){
118677           rc = whereLoopAddVirtual(&sSubBuild, mExtra);
118678         }else
118679 #endif
118680         {
118681           rc = whereLoopAddBtree(&sSubBuild, mExtra);
118682         }
118683         if( rc==SQLITE_OK ){
118684           rc = whereLoopAddOr(&sSubBuild, mExtra);
118685         }
118686         assert( rc==SQLITE_OK || sCur.n==0 );
118687         if( sCur.n==0 ){
118688           sSum.n = 0;
118689           break;
118690         }else if( once ){
118691           whereOrMove(&sSum, &sCur);
118692           once = 0;
118693         }else{
118694           WhereOrSet sPrev;
118695           whereOrMove(&sPrev, &sSum);
118696           sSum.n = 0;
118697           for(i=0; i<sPrev.n; i++){
118698             for(j=0; j<sCur.n; j++){
118699               whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
118700                             sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
118701                             sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
118702             }
118703           }
118704         }
118705       }
118706       pNew->nLTerm = 1;
118707       pNew->aLTerm[0] = pTerm;
118708       pNew->wsFlags = WHERE_MULTI_OR;
118709       pNew->rSetup = 0;
118710       pNew->iSortIdx = 0;
118711       memset(&pNew->u, 0, sizeof(pNew->u));
118712       for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
118713         /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
118714         ** of all sub-scans required by the OR-scan. However, due to rounding
118715         ** errors, it may be that the cost of the OR-scan is equal to its
118716         ** most expensive sub-scan. Add the smallest possible penalty
118717         ** (equivalent to multiplying the cost by 1.07) to ensure that
118718         ** this does not happen. Otherwise, for WHERE clauses such as the
118719         ** following where there is an index on "y":
118720         **
118721         **     WHERE likelihood(x=?, 0.99) OR y=?
118722         **
118723         ** the planner may elect to "OR" together a full-table scan and an
118724         ** index lookup. And other similarly odd results.  */
118725         pNew->rRun = sSum.a[i].rRun + 1;
118726         pNew->nOut = sSum.a[i].nOut;
118727         pNew->prereq = sSum.a[i].prereq;
118728         rc = whereLoopInsert(pBuilder, pNew);
118729       }
118730       WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
118731     }
118732   }
118733   return rc;
118734 }
118735 
118736 /*
118737 ** Add all WhereLoop objects for all tables
118738 */
118739 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
118740   WhereInfo *pWInfo = pBuilder->pWInfo;
118741   Bitmask mExtra = 0;
118742   Bitmask mPrior = 0;
118743   int iTab;
118744   SrcList *pTabList = pWInfo->pTabList;
118745   struct SrcList_item *pItem;
118746   sqlite3 *db = pWInfo->pParse->db;
118747   int nTabList = pWInfo->nLevel;
118748   int rc = SQLITE_OK;
118749   u8 priorJoinType = 0;
118750   WhereLoop *pNew;
118751 
118752   /* Loop over the tables in the join, from left to right */
118753   pNew = pBuilder->pNew;
118754   whereLoopInit(pNew);
118755   for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
118756     pNew->iTab = iTab;
118757     pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
118758     if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
118759       mExtra = mPrior;
118760     }
118761     priorJoinType = pItem->jointype;
118762     if( IsVirtual(pItem->pTab) ){
118763       rc = whereLoopAddVirtual(pBuilder, mExtra);
118764     }else{
118765       rc = whereLoopAddBtree(pBuilder, mExtra);
118766     }
118767     if( rc==SQLITE_OK ){
118768       rc = whereLoopAddOr(pBuilder, mExtra);
118769     }
118770     mPrior |= pNew->maskSelf;
118771     if( rc || db->mallocFailed ) break;
118772   }
118773   whereLoopClear(db, pNew);
118774   return rc;
118775 }
118776 
118777 /*
118778 ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
118779 ** parameters) to see if it outputs rows in the requested ORDER BY
118780 ** (or GROUP BY) without requiring a separate sort operation.  Return N:
118781 **
118782 **   N>0:   N terms of the ORDER BY clause are satisfied
118783 **   N==0:  No terms of the ORDER BY clause are satisfied
118784 **   N<0:   Unknown yet how many terms of ORDER BY might be satisfied.
118785 **
118786 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
118787 ** strict.  With GROUP BY and DISTINCT the only requirement is that
118788 ** equivalent rows appear immediately adjacent to one another.  GROUP BY
118789 ** and DISTINCT do not require rows to appear in any particular order as long
118790 ** as equivalent rows are grouped together.  Thus for GROUP BY and DISTINCT
118791 ** the pOrderBy terms can be matched in any order.  With ORDER BY, the
118792 ** pOrderBy terms must be matched in strict left-to-right order.
118793 */
118794 static i8 wherePathSatisfiesOrderBy(
118795   WhereInfo *pWInfo,    /* The WHERE clause */
118796   ExprList *pOrderBy,   /* ORDER BY or GROUP BY or DISTINCT clause to check */
118797   WherePath *pPath,     /* The WherePath to check */
118798   u16 wctrlFlags,       /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
118799   u16 nLoop,            /* Number of entries in pPath->aLoop[] */
118800   WhereLoop *pLast,     /* Add this WhereLoop to the end of pPath->aLoop[] */
118801   Bitmask *pRevMask     /* OUT: Mask of WhereLoops to run in reverse order */
118802 ){
118803   u8 revSet;            /* True if rev is known */
118804   u8 rev;               /* Composite sort order */
118805   u8 revIdx;            /* Index sort order */
118806   u8 isOrderDistinct;   /* All prior WhereLoops are order-distinct */
118807   u8 distinctColumns;   /* True if the loop has UNIQUE NOT NULL columns */
118808   u8 isMatch;           /* iColumn matches a term of the ORDER BY clause */
118809   u16 nKeyCol;          /* Number of key columns in pIndex */
118810   u16 nColumn;          /* Total number of ordered columns in the index */
118811   u16 nOrderBy;         /* Number terms in the ORDER BY clause */
118812   int iLoop;            /* Index of WhereLoop in pPath being processed */
118813   int i, j;             /* Loop counters */
118814   int iCur;             /* Cursor number for current WhereLoop */
118815   int iColumn;          /* A column number within table iCur */
118816   WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
118817   WhereTerm *pTerm;     /* A single term of the WHERE clause */
118818   Expr *pOBExpr;        /* An expression from the ORDER BY clause */
118819   CollSeq *pColl;       /* COLLATE function from an ORDER BY clause term */
118820   Index *pIndex;        /* The index associated with pLoop */
118821   sqlite3 *db = pWInfo->pParse->db;  /* Database connection */
118822   Bitmask obSat = 0;    /* Mask of ORDER BY terms satisfied so far */
118823   Bitmask obDone;       /* Mask of all ORDER BY terms */
118824   Bitmask orderDistinctMask;  /* Mask of all well-ordered loops */
118825   Bitmask ready;              /* Mask of inner loops */
118826 
118827   /*
118828   ** We say the WhereLoop is "one-row" if it generates no more than one
118829   ** row of output.  A WhereLoop is one-row if all of the following are true:
118830   **  (a) All index columns match with WHERE_COLUMN_EQ.
118831   **  (b) The index is unique
118832   ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
118833   ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
118834   **
118835   ** We say the WhereLoop is "order-distinct" if the set of columns from
118836   ** that WhereLoop that are in the ORDER BY clause are different for every
118837   ** row of the WhereLoop.  Every one-row WhereLoop is automatically
118838   ** order-distinct.   A WhereLoop that has no columns in the ORDER BY clause
118839   ** is not order-distinct. To be order-distinct is not quite the same as being
118840   ** UNIQUE since a UNIQUE column or index can have multiple rows that
118841   ** are NULL and NULL values are equivalent for the purpose of order-distinct.
118842   ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
118843   **
118844   ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
118845   ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
118846   ** automatically order-distinct.
118847   */
118848 
118849   assert( pOrderBy!=0 );
118850   if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
118851 
118852   nOrderBy = pOrderBy->nExpr;
118853   testcase( nOrderBy==BMS-1 );
118854   if( nOrderBy>BMS-1 ) return 0;  /* Cannot optimize overly large ORDER BYs */
118855   isOrderDistinct = 1;
118856   obDone = MASKBIT(nOrderBy)-1;
118857   orderDistinctMask = 0;
118858   ready = 0;
118859   for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
118860     if( iLoop>0 ) ready |= pLoop->maskSelf;
118861     pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
118862     if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
118863       if( pLoop->u.vtab.isOrdered ) obSat = obDone;
118864       break;
118865     }
118866     iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
118867 
118868     /* Mark off any ORDER BY term X that is a column in the table of
118869     ** the current loop for which there is term in the WHERE
118870     ** clause of the form X IS NULL or X=? that reference only outer
118871     ** loops.
118872     */
118873     for(i=0; i<nOrderBy; i++){
118874       if( MASKBIT(i) & obSat ) continue;
118875       pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
118876       if( pOBExpr->op!=TK_COLUMN ) continue;
118877       if( pOBExpr->iTable!=iCur ) continue;
118878       pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
118879                        ~ready, WO_EQ|WO_ISNULL, 0);
118880       if( pTerm==0 ) continue;
118881       if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
118882         const char *z1, *z2;
118883         pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
118884         if( !pColl ) pColl = db->pDfltColl;
118885         z1 = pColl->zName;
118886         pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
118887         if( !pColl ) pColl = db->pDfltColl;
118888         z2 = pColl->zName;
118889         if( sqlite3StrICmp(z1, z2)!=0 ) continue;
118890       }
118891       obSat |= MASKBIT(i);
118892     }
118893 
118894     if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
118895       if( pLoop->wsFlags & WHERE_IPK ){
118896         pIndex = 0;
118897         nKeyCol = 0;
118898         nColumn = 1;
118899       }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
118900         return 0;
118901       }else{
118902         nKeyCol = pIndex->nKeyCol;
118903         nColumn = pIndex->nColumn;
118904         assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
118905         assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
118906         isOrderDistinct = IsUniqueIndex(pIndex);
118907       }
118908 
118909       /* Loop through all columns of the index and deal with the ones
118910       ** that are not constrained by == or IN.
118911       */
118912       rev = revSet = 0;
118913       distinctColumns = 0;
118914       for(j=0; j<nColumn; j++){
118915         u8 bOnce;   /* True to run the ORDER BY search loop */
118916 
118917         /* Skip over == and IS NULL terms */
118918         if( j<pLoop->u.btree.nEq
118919          && pLoop->u.btree.nSkip==0
118920          && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
118921         ){
118922           if( i & WO_ISNULL ){
118923             testcase( isOrderDistinct );
118924             isOrderDistinct = 0;
118925           }
118926           continue;
118927         }
118928 
118929         /* Get the column number in the table (iColumn) and sort order
118930         ** (revIdx) for the j-th column of the index.
118931         */
118932         if( pIndex ){
118933           iColumn = pIndex->aiColumn[j];
118934           revIdx = pIndex->aSortOrder[j];
118935           if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
118936         }else{
118937           iColumn = -1;
118938           revIdx = 0;
118939         }
118940 
118941         /* An unconstrained column that might be NULL means that this
118942         ** WhereLoop is not well-ordered
118943         */
118944         if( isOrderDistinct
118945          && iColumn>=0
118946          && j>=pLoop->u.btree.nEq
118947          && pIndex->pTable->aCol[iColumn].notNull==0
118948         ){
118949           isOrderDistinct = 0;
118950         }
118951 
118952         /* Find the ORDER BY term that corresponds to the j-th column
118953         ** of the index and mark that ORDER BY term off
118954         */
118955         bOnce = 1;
118956         isMatch = 0;
118957         for(i=0; bOnce && i<nOrderBy; i++){
118958           if( MASKBIT(i) & obSat ) continue;
118959           pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
118960           testcase( wctrlFlags & WHERE_GROUPBY );
118961           testcase( wctrlFlags & WHERE_DISTINCTBY );
118962           if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
118963           if( pOBExpr->op!=TK_COLUMN ) continue;
118964           if( pOBExpr->iTable!=iCur ) continue;
118965           if( pOBExpr->iColumn!=iColumn ) continue;
118966           if( iColumn>=0 ){
118967             pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
118968             if( !pColl ) pColl = db->pDfltColl;
118969             if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
118970           }
118971           isMatch = 1;
118972           break;
118973         }
118974         if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
118975           /* Make sure the sort order is compatible in an ORDER BY clause.
118976           ** Sort order is irrelevant for a GROUP BY clause. */
118977           if( revSet ){
118978             if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
118979           }else{
118980             rev = revIdx ^ pOrderBy->a[i].sortOrder;
118981             if( rev ) *pRevMask |= MASKBIT(iLoop);
118982             revSet = 1;
118983           }
118984         }
118985         if( isMatch ){
118986           if( iColumn<0 ){
118987             testcase( distinctColumns==0 );
118988             distinctColumns = 1;
118989           }
118990           obSat |= MASKBIT(i);
118991         }else{
118992           /* No match found */
118993           if( j==0 || j<nKeyCol ){
118994             testcase( isOrderDistinct!=0 );
118995             isOrderDistinct = 0;
118996           }
118997           break;
118998         }
118999       } /* end Loop over all index columns */
119000       if( distinctColumns ){
119001         testcase( isOrderDistinct==0 );
119002         isOrderDistinct = 1;
119003       }
119004     } /* end-if not one-row */
119005 
119006     /* Mark off any other ORDER BY terms that reference pLoop */
119007     if( isOrderDistinct ){
119008       orderDistinctMask |= pLoop->maskSelf;
119009       for(i=0; i<nOrderBy; i++){
119010         Expr *p;
119011         Bitmask mTerm;
119012         if( MASKBIT(i) & obSat ) continue;
119013         p = pOrderBy->a[i].pExpr;
119014         mTerm = exprTableUsage(&pWInfo->sMaskSet,p);
119015         if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
119016         if( (mTerm&~orderDistinctMask)==0 ){
119017           obSat |= MASKBIT(i);
119018         }
119019       }
119020     }
119021   } /* End the loop over all WhereLoops from outer-most down to inner-most */
119022   if( obSat==obDone ) return (i8)nOrderBy;
119023   if( !isOrderDistinct ){
119024     for(i=nOrderBy-1; i>0; i--){
119025       Bitmask m = MASKBIT(i) - 1;
119026       if( (obSat&m)==m ) return i;
119027     }
119028     return 0;
119029   }
119030   return -1;
119031 }
119032 
119033 
119034 /*
119035 ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
119036 ** the planner assumes that the specified pOrderBy list is actually a GROUP
119037 ** BY clause - and so any order that groups rows as required satisfies the
119038 ** request.
119039 **
119040 ** Normally, in this case it is not possible for the caller to determine
119041 ** whether or not the rows are really being delivered in sorted order, or
119042 ** just in some other order that provides the required grouping. However,
119043 ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
119044 ** this function may be called on the returned WhereInfo object. It returns
119045 ** true if the rows really will be sorted in the specified order, or false
119046 ** otherwise.
119047 **
119048 ** For example, assuming:
119049 **
119050 **   CREATE INDEX i1 ON t1(x, Y);
119051 **
119052 ** then
119053 **
119054 **   SELECT * FROM t1 GROUP BY x,y ORDER BY x,y;   -- IsSorted()==1
119055 **   SELECT * FROM t1 GROUP BY y,x ORDER BY y,x;   -- IsSorted()==0
119056 */
119057 SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
119058   assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
119059   assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
119060   return pWInfo->sorted;
119061 }
119062 
119063 #ifdef WHERETRACE_ENABLED
119064 /* For debugging use only: */
119065 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
119066   static char zName[65];
119067   int i;
119068   for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
119069   if( pLast ) zName[i++] = pLast->cId;
119070   zName[i] = 0;
119071   return zName;
119072 }
119073 #endif
119074 
119075 /*
119076 ** Return the cost of sorting nRow rows, assuming that the keys have
119077 ** nOrderby columns and that the first nSorted columns are already in
119078 ** order.
119079 */
119080 static LogEst whereSortingCost(
119081   WhereInfo *pWInfo,
119082   LogEst nRow,
119083   int nOrderBy,
119084   int nSorted
119085 ){
119086   /* TUNING: Estimated cost of a full external sort, where N is
119087   ** the number of rows to sort is:
119088   **
119089   **   cost = (3.0 * N * log(N)).
119090   **
119091   ** Or, if the order-by clause has X terms but only the last Y
119092   ** terms are out of order, then block-sorting will reduce the
119093   ** sorting cost to:
119094   **
119095   **   cost = (3.0 * N * log(N)) * (Y/X)
119096   **
119097   ** The (Y/X) term is implemented using stack variable rScale
119098   ** below.  */
119099   LogEst rScale, rSortCost;
119100   assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
119101   rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
119102   rSortCost = nRow + estLog(nRow) + rScale + 16;
119103 
119104   /* TUNING: The cost of implementing DISTINCT using a B-TREE is
119105   ** similar but with a larger constant of proportionality.
119106   ** Multiply by an additional factor of 3.0.  */
119107   if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
119108     rSortCost += 16;
119109   }
119110 
119111   return rSortCost;
119112 }
119113 
119114 /*
119115 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
119116 ** attempts to find the lowest cost path that visits each WhereLoop
119117 ** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
119118 **
119119 ** Assume that the total number of output rows that will need to be sorted
119120 ** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting
119121 ** costs if nRowEst==0.
119122 **
119123 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
119124 ** error occurs.
119125 */
119126 static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
119127   int mxChoice;             /* Maximum number of simultaneous paths tracked */
119128   int nLoop;                /* Number of terms in the join */
119129   Parse *pParse;            /* Parsing context */
119130   sqlite3 *db;              /* The database connection */
119131   int iLoop;                /* Loop counter over the terms of the join */
119132   int ii, jj;               /* Loop counters */
119133   int mxI = 0;              /* Index of next entry to replace */
119134   int nOrderBy;             /* Number of ORDER BY clause terms */
119135   LogEst mxCost = 0;        /* Maximum cost of a set of paths */
119136   LogEst mxUnsorted = 0;    /* Maximum unsorted cost of a set of path */
119137   int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */
119138   WherePath *aFrom;         /* All nFrom paths at the previous level */
119139   WherePath *aTo;           /* The nTo best paths at the current level */
119140   WherePath *pFrom;         /* An element of aFrom[] that we are working on */
119141   WherePath *pTo;           /* An element of aTo[] that we are working on */
119142   WhereLoop *pWLoop;        /* One of the WhereLoop objects */
119143   WhereLoop **pX;           /* Used to divy up the pSpace memory */
119144   LogEst *aSortCost = 0;    /* Sorting and partial sorting costs */
119145   char *pSpace;             /* Temporary memory used by this routine */
119146   int nSpace;               /* Bytes of space allocated at pSpace */
119147 
119148   pParse = pWInfo->pParse;
119149   db = pParse->db;
119150   nLoop = pWInfo->nLevel;
119151   /* TUNING: For simple queries, only the best path is tracked.
119152   ** For 2-way joins, the 5 best paths are followed.
119153   ** For joins of 3 or more tables, track the 10 best paths */
119154   mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
119155   assert( nLoop<=pWInfo->pTabList->nSrc );
119156   WHERETRACE(0x002, ("---- begin solver.  (nRowEst=%d)\n", nRowEst));
119157 
119158   /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
119159   ** case the purpose of this call is to estimate the number of rows returned
119160   ** by the overall query. Once this estimate has been obtained, the caller
119161   ** will invoke this function a second time, passing the estimate as the
119162   ** nRowEst parameter.  */
119163   if( pWInfo->pOrderBy==0 || nRowEst==0 ){
119164     nOrderBy = 0;
119165   }else{
119166     nOrderBy = pWInfo->pOrderBy->nExpr;
119167   }
119168 
119169   /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
119170   nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
119171   nSpace += sizeof(LogEst) * nOrderBy;
119172   pSpace = sqlite3DbMallocRaw(db, nSpace);
119173   if( pSpace==0 ) return SQLITE_NOMEM;
119174   aTo = (WherePath*)pSpace;
119175   aFrom = aTo+mxChoice;
119176   memset(aFrom, 0, sizeof(aFrom[0]));
119177   pX = (WhereLoop**)(aFrom+mxChoice);
119178   for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
119179     pFrom->aLoop = pX;
119180   }
119181   if( nOrderBy ){
119182     /* If there is an ORDER BY clause and it is not being ignored, set up
119183     ** space for the aSortCost[] array. Each element of the aSortCost array
119184     ** is either zero - meaning it has not yet been initialized - or the
119185     ** cost of sorting nRowEst rows of data where the first X terms of
119186     ** the ORDER BY clause are already in order, where X is the array
119187     ** index.  */
119188     aSortCost = (LogEst*)pX;
119189     memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
119190   }
119191   assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
119192   assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
119193 
119194   /* Seed the search with a single WherePath containing zero WhereLoops.
119195   **
119196   ** TUNING: Do not let the number of iterations go above 25.  If the cost
119197   ** of computing an automatic index is not paid back within the first 25
119198   ** rows, then do not use the automatic index. */
119199   aFrom[0].nRow = MIN(pParse->nQueryLoop, 46);  assert( 46==sqlite3LogEst(25) );
119200   nFrom = 1;
119201   assert( aFrom[0].isOrdered==0 );
119202   if( nOrderBy ){
119203     /* If nLoop is zero, then there are no FROM terms in the query. Since
119204     ** in this case the query may return a maximum of one row, the results
119205     ** are already in the requested order. Set isOrdered to nOrderBy to
119206     ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
119207     ** -1, indicating that the result set may or may not be ordered,
119208     ** depending on the loops added to the current plan.  */
119209     aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
119210   }
119211 
119212   /* Compute successively longer WherePaths using the previous generation
119213   ** of WherePaths as the basis for the next.  Keep track of the mxChoice
119214   ** best paths at each generation */
119215   for(iLoop=0; iLoop<nLoop; iLoop++){
119216     nTo = 0;
119217     for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
119218       for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
119219         LogEst nOut;                      /* Rows visited by (pFrom+pWLoop) */
119220         LogEst rCost;                     /* Cost of path (pFrom+pWLoop) */
119221         LogEst rUnsorted;                 /* Unsorted cost of (pFrom+pWLoop) */
119222         i8 isOrdered = pFrom->isOrdered;  /* isOrdered for (pFrom+pWLoop) */
119223         Bitmask maskNew;                  /* Mask of src visited by (..) */
119224         Bitmask revMask = 0;              /* Mask of rev-order loops for (..) */
119225 
119226         if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
119227         if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
119228         /* At this point, pWLoop is a candidate to be the next loop.
119229         ** Compute its cost */
119230         rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
119231         rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
119232         nOut = pFrom->nRow + pWLoop->nOut;
119233         maskNew = pFrom->maskLoop | pWLoop->maskSelf;
119234         if( isOrdered<0 ){
119235           isOrdered = wherePathSatisfiesOrderBy(pWInfo,
119236                        pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
119237                        iLoop, pWLoop, &revMask);
119238         }else{
119239           revMask = pFrom->revLoop;
119240         }
119241         if( isOrdered>=0 && isOrdered<nOrderBy ){
119242           if( aSortCost[isOrdered]==0 ){
119243             aSortCost[isOrdered] = whereSortingCost(
119244                 pWInfo, nRowEst, nOrderBy, isOrdered
119245             );
119246           }
119247           rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
119248 
119249           WHERETRACE(0x002,
119250               ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
119251                aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
119252                rUnsorted, rCost));
119253         }else{
119254           rCost = rUnsorted;
119255         }
119256 
119257         /* Check to see if pWLoop should be added to the set of
119258         ** mxChoice best-so-far paths.
119259         **
119260         ** First look for an existing path among best-so-far paths
119261         ** that covers the same set of loops and has the same isOrdered
119262         ** setting as the current path candidate.
119263         **
119264         ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
119265         ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
119266         ** of legal values for isOrdered, -1..64.
119267         */
119268         for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
119269           if( pTo->maskLoop==maskNew
119270            && ((pTo->isOrdered^isOrdered)&0x80)==0
119271           ){
119272             testcase( jj==nTo-1 );
119273             break;
119274           }
119275         }
119276         if( jj>=nTo ){
119277           /* None of the existing best-so-far paths match the candidate. */
119278           if( nTo>=mxChoice
119279            && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
119280           ){
119281             /* The current candidate is no better than any of the mxChoice
119282             ** paths currently in the best-so-far buffer.  So discard
119283             ** this candidate as not viable. */
119284 #ifdef WHERETRACE_ENABLED /* 0x4 */
119285             if( sqlite3WhereTrace&0x4 ){
119286               sqlite3DebugPrintf("Skip   %s cost=%-3d,%3d order=%c\n",
119287                   wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
119288                   isOrdered>=0 ? isOrdered+'0' : '?');
119289             }
119290 #endif
119291             continue;
119292           }
119293           /* If we reach this points it means that the new candidate path
119294           ** needs to be added to the set of best-so-far paths. */
119295           if( nTo<mxChoice ){
119296             /* Increase the size of the aTo set by one */
119297             jj = nTo++;
119298           }else{
119299             /* New path replaces the prior worst to keep count below mxChoice */
119300             jj = mxI;
119301           }
119302           pTo = &aTo[jj];
119303 #ifdef WHERETRACE_ENABLED /* 0x4 */
119304           if( sqlite3WhereTrace&0x4 ){
119305             sqlite3DebugPrintf("New    %s cost=%-3d,%3d order=%c\n",
119306                 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
119307                 isOrdered>=0 ? isOrdered+'0' : '?');
119308           }
119309 #endif
119310         }else{
119311           /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
119312           ** same set of loops and has the sam isOrdered setting as the
119313           ** candidate path.  Check to see if the candidate should replace
119314           ** pTo or if the candidate should be skipped */
119315           if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
119316 #ifdef WHERETRACE_ENABLED /* 0x4 */
119317             if( sqlite3WhereTrace&0x4 ){
119318               sqlite3DebugPrintf(
119319                   "Skip   %s cost=%-3d,%3d order=%c",
119320                   wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
119321                   isOrdered>=0 ? isOrdered+'0' : '?');
119322               sqlite3DebugPrintf("   vs %s cost=%-3d,%d order=%c\n",
119323                   wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
119324                   pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
119325             }
119326 #endif
119327             /* Discard the candidate path from further consideration */
119328             testcase( pTo->rCost==rCost );
119329             continue;
119330           }
119331           testcase( pTo->rCost==rCost+1 );
119332           /* Control reaches here if the candidate path is better than the
119333           ** pTo path.  Replace pTo with the candidate. */
119334 #ifdef WHERETRACE_ENABLED /* 0x4 */
119335           if( sqlite3WhereTrace&0x4 ){
119336             sqlite3DebugPrintf(
119337                 "Update %s cost=%-3d,%3d order=%c",
119338                 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
119339                 isOrdered>=0 ? isOrdered+'0' : '?');
119340             sqlite3DebugPrintf("  was %s cost=%-3d,%3d order=%c\n",
119341                 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
119342                 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
119343           }
119344 #endif
119345         }
119346         /* pWLoop is a winner.  Add it to the set of best so far */
119347         pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
119348         pTo->revLoop = revMask;
119349         pTo->nRow = nOut;
119350         pTo->rCost = rCost;
119351         pTo->rUnsorted = rUnsorted;
119352         pTo->isOrdered = isOrdered;
119353         memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
119354         pTo->aLoop[iLoop] = pWLoop;
119355         if( nTo>=mxChoice ){
119356           mxI = 0;
119357           mxCost = aTo[0].rCost;
119358           mxUnsorted = aTo[0].nRow;
119359           for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
119360             if( pTo->rCost>mxCost
119361              || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
119362             ){
119363               mxCost = pTo->rCost;
119364               mxUnsorted = pTo->rUnsorted;
119365               mxI = jj;
119366             }
119367           }
119368         }
119369       }
119370     }
119371 
119372 #ifdef WHERETRACE_ENABLED  /* >=2 */
119373     if( sqlite3WhereTrace>=2 ){
119374       sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
119375       for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
119376         sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
119377            wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
119378            pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
119379         if( pTo->isOrdered>0 ){
119380           sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
119381         }else{
119382           sqlite3DebugPrintf("\n");
119383         }
119384       }
119385     }
119386 #endif
119387 
119388     /* Swap the roles of aFrom and aTo for the next generation */
119389     pFrom = aTo;
119390     aTo = aFrom;
119391     aFrom = pFrom;
119392     nFrom = nTo;
119393   }
119394 
119395   if( nFrom==0 ){
119396     sqlite3ErrorMsg(pParse, "no query solution");
119397     sqlite3DbFree(db, pSpace);
119398     return SQLITE_ERROR;
119399   }
119400 
119401   /* Find the lowest cost path.  pFrom will be left pointing to that path */
119402   pFrom = aFrom;
119403   for(ii=1; ii<nFrom; ii++){
119404     if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
119405   }
119406   assert( pWInfo->nLevel==nLoop );
119407   /* Load the lowest cost path into pWInfo */
119408   for(iLoop=0; iLoop<nLoop; iLoop++){
119409     WhereLevel *pLevel = pWInfo->a + iLoop;
119410     pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
119411     pLevel->iFrom = pWLoop->iTab;
119412     pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
119413   }
119414   if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
119415    && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
119416    && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
119417    && nRowEst
119418   ){
119419     Bitmask notUsed;
119420     int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
119421                  WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
119422     if( rc==pWInfo->pResultSet->nExpr ){
119423       pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
119424     }
119425   }
119426   if( pWInfo->pOrderBy ){
119427     if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
119428       if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
119429         pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
119430       }
119431     }else{
119432       pWInfo->nOBSat = pFrom->isOrdered;
119433       if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
119434       pWInfo->revMask = pFrom->revLoop;
119435     }
119436     if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
119437         && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr
119438     ){
119439       Bitmask revMask = 0;
119440       int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
119441           pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
119442       );
119443       assert( pWInfo->sorted==0 );
119444       if( nOrder==pWInfo->pOrderBy->nExpr ){
119445         pWInfo->sorted = 1;
119446         pWInfo->revMask = revMask;
119447       }
119448     }
119449   }
119450 
119451 
119452   pWInfo->nRowOut = pFrom->nRow;
119453 
119454   /* Free temporary memory and return success */
119455   sqlite3DbFree(db, pSpace);
119456   return SQLITE_OK;
119457 }
119458 
119459 /*
119460 ** Most queries use only a single table (they are not joins) and have
119461 ** simple == constraints against indexed fields.  This routine attempts
119462 ** to plan those simple cases using much less ceremony than the
119463 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
119464 ** times for the common case.
119465 **
119466 ** Return non-zero on success, if this query can be handled by this
119467 ** no-frills query planner.  Return zero if this query needs the
119468 ** general-purpose query planner.
119469 */
119470 static int whereShortCut(WhereLoopBuilder *pBuilder){
119471   WhereInfo *pWInfo;
119472   struct SrcList_item *pItem;
119473   WhereClause *pWC;
119474   WhereTerm *pTerm;
119475   WhereLoop *pLoop;
119476   int iCur;
119477   int j;
119478   Table *pTab;
119479   Index *pIdx;
119480 
119481   pWInfo = pBuilder->pWInfo;
119482   if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
119483   assert( pWInfo->pTabList->nSrc>=1 );
119484   pItem = pWInfo->pTabList->a;
119485   pTab = pItem->pTab;
119486   if( IsVirtual(pTab) ) return 0;
119487   if( pItem->zIndex ) return 0;
119488   iCur = pItem->iCursor;
119489   pWC = &pWInfo->sWC;
119490   pLoop = pBuilder->pNew;
119491   pLoop->wsFlags = 0;
119492   pLoop->u.btree.nSkip = 0;
119493   pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
119494   if( pTerm ){
119495     pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
119496     pLoop->aLTerm[0] = pTerm;
119497     pLoop->nLTerm = 1;
119498     pLoop->u.btree.nEq = 1;
119499     /* TUNING: Cost of a rowid lookup is 10 */
119500     pLoop->rRun = 33;  /* 33==sqlite3LogEst(10) */
119501   }else{
119502     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
119503       assert( pLoop->aLTermSpace==pLoop->aLTerm );
119504       assert( ArraySize(pLoop->aLTermSpace)==4 );
119505       if( !IsUniqueIndex(pIdx)
119506        || pIdx->pPartIdxWhere!=0
119507        || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
119508       ) continue;
119509       for(j=0; j<pIdx->nKeyCol; j++){
119510         pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
119511         if( pTerm==0 ) break;
119512         pLoop->aLTerm[j] = pTerm;
119513       }
119514       if( j!=pIdx->nKeyCol ) continue;
119515       pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
119516       if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
119517         pLoop->wsFlags |= WHERE_IDX_ONLY;
119518       }
119519       pLoop->nLTerm = j;
119520       pLoop->u.btree.nEq = j;
119521       pLoop->u.btree.pIndex = pIdx;
119522       /* TUNING: Cost of a unique index lookup is 15 */
119523       pLoop->rRun = 39;  /* 39==sqlite3LogEst(15) */
119524       break;
119525     }
119526   }
119527   if( pLoop->wsFlags ){
119528     pLoop->nOut = (LogEst)1;
119529     pWInfo->a[0].pWLoop = pLoop;
119530     pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
119531     pWInfo->a[0].iTabCur = iCur;
119532     pWInfo->nRowOut = 1;
119533     if( pWInfo->pOrderBy ) pWInfo->nOBSat =  pWInfo->pOrderBy->nExpr;
119534     if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
119535       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
119536     }
119537 #ifdef SQLITE_DEBUG
119538     pLoop->cId = '0';
119539 #endif
119540     return 1;
119541   }
119542   return 0;
119543 }
119544 
119545 /*
119546 ** Generate the beginning of the loop used for WHERE clause processing.
119547 ** The return value is a pointer to an opaque structure that contains
119548 ** information needed to terminate the loop.  Later, the calling routine
119549 ** should invoke sqlite3WhereEnd() with the return value of this function
119550 ** in order to complete the WHERE clause processing.
119551 **
119552 ** If an error occurs, this routine returns NULL.
119553 **
119554 ** The basic idea is to do a nested loop, one loop for each table in
119555 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
119556 ** same as a SELECT with only a single table in the FROM clause.)  For
119557 ** example, if the SQL is this:
119558 **
119559 **       SELECT * FROM t1, t2, t3 WHERE ...;
119560 **
119561 ** Then the code generated is conceptually like the following:
119562 **
119563 **      foreach row1 in t1 do       \    Code generated
119564 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
119565 **          foreach row3 in t3 do   /
119566 **            ...
119567 **          end                     \    Code generated
119568 **        end                        |-- by sqlite3WhereEnd()
119569 **      end                         /
119570 **
119571 ** Note that the loops might not be nested in the order in which they
119572 ** appear in the FROM clause if a different order is better able to make
119573 ** use of indices.  Note also that when the IN operator appears in
119574 ** the WHERE clause, it might result in additional nested loops for
119575 ** scanning through all values on the right-hand side of the IN.
119576 **
119577 ** There are Btree cursors associated with each table.  t1 uses cursor
119578 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
119579 ** And so forth.  This routine generates code to open those VDBE cursors
119580 ** and sqlite3WhereEnd() generates the code to close them.
119581 **
119582 ** The code that sqlite3WhereBegin() generates leaves the cursors named
119583 ** in pTabList pointing at their appropriate entries.  The [...] code
119584 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
119585 ** data from the various tables of the loop.
119586 **
119587 ** If the WHERE clause is empty, the foreach loops must each scan their
119588 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
119589 ** the tables have indices and there are terms in the WHERE clause that
119590 ** refer to those indices, a complete table scan can be avoided and the
119591 ** code will run much faster.  Most of the work of this routine is checking
119592 ** to see if there are indices that can be used to speed up the loop.
119593 **
119594 ** Terms of the WHERE clause are also used to limit which rows actually
119595 ** make it to the "..." in the middle of the loop.  After each "foreach",
119596 ** terms of the WHERE clause that use only terms in that loop and outer
119597 ** loops are evaluated and if false a jump is made around all subsequent
119598 ** inner loops (or around the "..." if the test occurs within the inner-
119599 ** most loop)
119600 **
119601 ** OUTER JOINS
119602 **
119603 ** An outer join of tables t1 and t2 is conceptally coded as follows:
119604 **
119605 **    foreach row1 in t1 do
119606 **      flag = 0
119607 **      foreach row2 in t2 do
119608 **        start:
119609 **          ...
119610 **          flag = 1
119611 **      end
119612 **      if flag==0 then
119613 **        move the row2 cursor to a null row
119614 **        goto start
119615 **      fi
119616 **    end
119617 **
119618 ** ORDER BY CLAUSE PROCESSING
119619 **
119620 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
119621 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
119622 ** if there is one.  If there is no ORDER BY clause or if this routine
119623 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
119624 **
119625 ** The iIdxCur parameter is the cursor number of an index.  If
119626 ** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
119627 ** to use for OR clause processing.  The WHERE clause should use this
119628 ** specific cursor.  If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
119629 ** the first cursor in an array of cursors for all indices.  iIdxCur should
119630 ** be used to compute the appropriate cursor depending on which index is
119631 ** used.
119632 */
119633 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
119634   Parse *pParse,        /* The parser context */
119635   SrcList *pTabList,    /* FROM clause: A list of all tables to be scanned */
119636   Expr *pWhere,         /* The WHERE clause */
119637   ExprList *pOrderBy,   /* An ORDER BY (or GROUP BY) clause, or NULL */
119638   ExprList *pResultSet, /* Result set of the query */
119639   u16 wctrlFlags,       /* One of the WHERE_* flags defined in sqliteInt.h */
119640   int iIdxCur           /* If WHERE_ONETABLE_ONLY is set, index cursor number */
119641 ){
119642   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
119643   int nTabList;              /* Number of elements in pTabList */
119644   WhereInfo *pWInfo;         /* Will become the return value of this function */
119645   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
119646   Bitmask notReady;          /* Cursors that are not yet positioned */
119647   WhereLoopBuilder sWLB;     /* The WhereLoop builder */
119648   WhereMaskSet *pMaskSet;    /* The expression mask set */
119649   WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
119650   WhereLoop *pLoop;          /* Pointer to a single WhereLoop object */
119651   int ii;                    /* Loop counter */
119652   sqlite3 *db;               /* Database connection */
119653   int rc;                    /* Return code */
119654 
119655 
119656   /* Variable initialization */
119657   db = pParse->db;
119658   memset(&sWLB, 0, sizeof(sWLB));
119659 
119660   /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
119661   testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
119662   if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
119663   sWLB.pOrderBy = pOrderBy;
119664 
119665   /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
119666   ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
119667   if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
119668     wctrlFlags &= ~WHERE_WANT_DISTINCT;
119669   }
119670 
119671   /* The number of tables in the FROM clause is limited by the number of
119672   ** bits in a Bitmask
119673   */
119674   testcase( pTabList->nSrc==BMS );
119675   if( pTabList->nSrc>BMS ){
119676     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
119677     return 0;
119678   }
119679 
119680   /* This function normally generates a nested loop for all tables in
119681   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
119682   ** only generate code for the first table in pTabList and assume that
119683   ** any cursors associated with subsequent tables are uninitialized.
119684   */
119685   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
119686 
119687   /* Allocate and initialize the WhereInfo structure that will become the
119688   ** return value. A single allocation is used to store the WhereInfo
119689   ** struct, the contents of WhereInfo.a[], the WhereClause structure
119690   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
119691   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
119692   ** some architectures. Hence the ROUND8() below.
119693   */
119694   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
119695   pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
119696   if( db->mallocFailed ){
119697     sqlite3DbFree(db, pWInfo);
119698     pWInfo = 0;
119699     goto whereBeginError;
119700   }
119701   pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
119702   pWInfo->nLevel = nTabList;
119703   pWInfo->pParse = pParse;
119704   pWInfo->pTabList = pTabList;
119705   pWInfo->pOrderBy = pOrderBy;
119706   pWInfo->pResultSet = pResultSet;
119707   pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
119708   pWInfo->wctrlFlags = wctrlFlags;
119709   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
119710   pMaskSet = &pWInfo->sMaskSet;
119711   sWLB.pWInfo = pWInfo;
119712   sWLB.pWC = &pWInfo->sWC;
119713   sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
119714   assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
119715   whereLoopInit(sWLB.pNew);
119716 #ifdef SQLITE_DEBUG
119717   sWLB.pNew->cId = '*';
119718 #endif
119719 
119720   /* Split the WHERE clause into separate subexpressions where each
119721   ** subexpression is separated by an AND operator.
119722   */
119723   initMaskSet(pMaskSet);
119724   whereClauseInit(&pWInfo->sWC, pWInfo);
119725   whereSplit(&pWInfo->sWC, pWhere, TK_AND);
119726 
119727   /* Special case: a WHERE clause that is constant.  Evaluate the
119728   ** expression and either jump over all of the code or fall thru.
119729   */
119730   for(ii=0; ii<sWLB.pWC->nTerm; ii++){
119731     if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
119732       sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
119733                          SQLITE_JUMPIFNULL);
119734       sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
119735     }
119736   }
119737 
119738   /* Special case: No FROM clause
119739   */
119740   if( nTabList==0 ){
119741     if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
119742     if( wctrlFlags & WHERE_WANT_DISTINCT ){
119743       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
119744     }
119745   }
119746 
119747   /* Assign a bit from the bitmask to every term in the FROM clause.
119748   **
119749   ** When assigning bitmask values to FROM clause cursors, it must be
119750   ** the case that if X is the bitmask for the N-th FROM clause term then
119751   ** the bitmask for all FROM clause terms to the left of the N-th term
119752   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
119753   ** its Expr.iRightJoinTable value to find the bitmask of the right table
119754   ** of the join.  Subtracting one from the right table bitmask gives a
119755   ** bitmask for all tables to the left of the join.  Knowing the bitmask
119756   ** for all tables to the left of a left join is important.  Ticket #3015.
119757   **
119758   ** Note that bitmasks are created for all pTabList->nSrc tables in
119759   ** pTabList, not just the first nTabList tables.  nTabList is normally
119760   ** equal to pTabList->nSrc but might be shortened to 1 if the
119761   ** WHERE_ONETABLE_ONLY flag is set.
119762   */
119763   for(ii=0; ii<pTabList->nSrc; ii++){
119764     createMask(pMaskSet, pTabList->a[ii].iCursor);
119765   }
119766 #ifndef NDEBUG
119767   {
119768     Bitmask toTheLeft = 0;
119769     for(ii=0; ii<pTabList->nSrc; ii++){
119770       Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
119771       assert( (m-1)==toTheLeft );
119772       toTheLeft |= m;
119773     }
119774   }
119775 #endif
119776 
119777   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
119778   ** add new virtual terms onto the end of the WHERE clause.  We do not
119779   ** want to analyze these virtual terms, so start analyzing at the end
119780   ** and work forward so that the added virtual terms are never processed.
119781   */
119782   exprAnalyzeAll(pTabList, &pWInfo->sWC);
119783   if( db->mallocFailed ){
119784     goto whereBeginError;
119785   }
119786 
119787   if( wctrlFlags & WHERE_WANT_DISTINCT ){
119788     if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
119789       /* The DISTINCT marking is pointless.  Ignore it. */
119790       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
119791     }else if( pOrderBy==0 ){
119792       /* Try to ORDER BY the result set to make distinct processing easier */
119793       pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
119794       pWInfo->pOrderBy = pResultSet;
119795     }
119796   }
119797 
119798   /* Construct the WhereLoop objects */
119799   WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
119800 #if defined(WHERETRACE_ENABLED)
119801   /* Display all terms of the WHERE clause */
119802   if( sqlite3WhereTrace & 0x100 ){
119803     int i;
119804     for(i=0; i<sWLB.pWC->nTerm; i++){
119805       whereTermPrint(&sWLB.pWC->a[i], i);
119806     }
119807   }
119808 #endif
119809 
119810   if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
119811     rc = whereLoopAddAll(&sWLB);
119812     if( rc ) goto whereBeginError;
119813 
119814     /* Display all of the WhereLoop objects if wheretrace is enabled */
119815 #ifdef WHERETRACE_ENABLED /* !=0 */
119816     if( sqlite3WhereTrace ){
119817       WhereLoop *p;
119818       int i;
119819       static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
119820                                        "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
119821       for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
119822         p->cId = zLabel[i%sizeof(zLabel)];
119823         whereLoopPrint(p, sWLB.pWC);
119824       }
119825     }
119826 #endif
119827 
119828     wherePathSolver(pWInfo, 0);
119829     if( db->mallocFailed ) goto whereBeginError;
119830     if( pWInfo->pOrderBy ){
119831        wherePathSolver(pWInfo, pWInfo->nRowOut+1);
119832        if( db->mallocFailed ) goto whereBeginError;
119833     }
119834   }
119835   if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
119836      pWInfo->revMask = (Bitmask)(-1);
119837   }
119838   if( pParse->nErr || NEVER(db->mallocFailed) ){
119839     goto whereBeginError;
119840   }
119841 #ifdef WHERETRACE_ENABLED /* !=0 */
119842   if( sqlite3WhereTrace ){
119843     int ii;
119844     sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
119845     if( pWInfo->nOBSat>0 ){
119846       sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
119847     }
119848     switch( pWInfo->eDistinct ){
119849       case WHERE_DISTINCT_UNIQUE: {
119850         sqlite3DebugPrintf("  DISTINCT=unique");
119851         break;
119852       }
119853       case WHERE_DISTINCT_ORDERED: {
119854         sqlite3DebugPrintf("  DISTINCT=ordered");
119855         break;
119856       }
119857       case WHERE_DISTINCT_UNORDERED: {
119858         sqlite3DebugPrintf("  DISTINCT=unordered");
119859         break;
119860       }
119861     }
119862     sqlite3DebugPrintf("\n");
119863     for(ii=0; ii<pWInfo->nLevel; ii++){
119864       whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
119865     }
119866   }
119867 #endif
119868   /* Attempt to omit tables from the join that do not effect the result */
119869   if( pWInfo->nLevel>=2
119870    && pResultSet!=0
119871    && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
119872   ){
119873     Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
119874     if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
119875     while( pWInfo->nLevel>=2 ){
119876       WhereTerm *pTerm, *pEnd;
119877       pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
119878       if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
119879       if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
119880        && (pLoop->wsFlags & WHERE_ONEROW)==0
119881       ){
119882         break;
119883       }
119884       if( (tabUsed & pLoop->maskSelf)!=0 ) break;
119885       pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
119886       for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
119887         if( (pTerm->prereqAll & pLoop->maskSelf)!=0
119888          && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
119889         ){
119890           break;
119891         }
119892       }
119893       if( pTerm<pEnd ) break;
119894       WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
119895       pWInfo->nLevel--;
119896       nTabList--;
119897     }
119898   }
119899   WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
119900   pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
119901 
119902   /* If the caller is an UPDATE or DELETE statement that is requesting
119903   ** to use a one-pass algorithm, determine if this is appropriate.
119904   ** The one-pass algorithm only works if the WHERE clause constrains
119905   ** the statement to update a single row.
119906   */
119907   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
119908   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
119909    && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
119910     pWInfo->okOnePass = 1;
119911     if( HasRowid(pTabList->a[0].pTab) ){
119912       pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
119913     }
119914   }
119915 
119916   /* Open all tables in the pTabList and any indices selected for
119917   ** searching those tables.
119918   */
119919   notReady = ~(Bitmask)0;
119920   for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
119921     Table *pTab;     /* Table to open */
119922     int iDb;         /* Index of database containing table/index */
119923     struct SrcList_item *pTabItem;
119924 
119925     pTabItem = &pTabList->a[pLevel->iFrom];
119926     pTab = pTabItem->pTab;
119927     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
119928     pLoop = pLevel->pWLoop;
119929     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
119930       /* Do nothing */
119931     }else
119932 #ifndef SQLITE_OMIT_VIRTUALTABLE
119933     if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
119934       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
119935       int iCur = pTabItem->iCursor;
119936       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
119937     }else if( IsVirtual(pTab) ){
119938       /* noop */
119939     }else
119940 #endif
119941     if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
119942          && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
119943       int op = OP_OpenRead;
119944       if( pWInfo->okOnePass ){
119945         op = OP_OpenWrite;
119946         pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
119947       };
119948       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
119949       assert( pTabItem->iCursor==pLevel->iTabCur );
119950       testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
119951       testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
119952       if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
119953         Bitmask b = pTabItem->colUsed;
119954         int n = 0;
119955         for(; b; b=b>>1, n++){}
119956         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
119957                             SQLITE_INT_TO_PTR(n), P4_INT32);
119958         assert( n<=pTab->nCol );
119959       }
119960     }else{
119961       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
119962     }
119963     if( pLoop->wsFlags & WHERE_INDEXED ){
119964       Index *pIx = pLoop->u.btree.pIndex;
119965       int iIndexCur;
119966       int op = OP_OpenRead;
119967       /* iIdxCur is always set if to a positive value if ONEPASS is possible */
119968       assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
119969       if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
119970        && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
119971       ){
119972         /* This is one term of an OR-optimization using the PRIMARY KEY of a
119973         ** WITHOUT ROWID table.  No need for a separate index */
119974         iIndexCur = pLevel->iTabCur;
119975         op = 0;
119976       }else if( pWInfo->okOnePass ){
119977         Index *pJ = pTabItem->pTab->pIndex;
119978         iIndexCur = iIdxCur;
119979         assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
119980         while( ALWAYS(pJ) && pJ!=pIx ){
119981           iIndexCur++;
119982           pJ = pJ->pNext;
119983         }
119984         op = OP_OpenWrite;
119985         pWInfo->aiCurOnePass[1] = iIndexCur;
119986       }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
119987         iIndexCur = iIdxCur;
119988         if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
119989       }else{
119990         iIndexCur = pParse->nTab++;
119991       }
119992       pLevel->iIdxCur = iIndexCur;
119993       assert( pIx->pSchema==pTab->pSchema );
119994       assert( iIndexCur>=0 );
119995       if( op ){
119996         sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
119997         sqlite3VdbeSetP4KeyInfo(pParse, pIx);
119998         VdbeComment((v, "%s", pIx->zName));
119999       }
120000     }
120001     if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
120002     notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
120003   }
120004   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
120005   if( db->mallocFailed ) goto whereBeginError;
120006 
120007   /* Generate the code to do the search.  Each iteration of the for
120008   ** loop below generates code for a single nested loop of the VM
120009   ** program.
120010   */
120011   notReady = ~(Bitmask)0;
120012   for(ii=0; ii<nTabList; ii++){
120013     pLevel = &pWInfo->a[ii];
120014 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
120015     if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
120016       constructAutomaticIndex(pParse, &pWInfo->sWC,
120017                 &pTabList->a[pLevel->iFrom], notReady, pLevel);
120018       if( db->mallocFailed ) goto whereBeginError;
120019     }
120020 #endif
120021     explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
120022     pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
120023     notReady = codeOneLoopStart(pWInfo, ii, notReady);
120024     pWInfo->iContinue = pLevel->addrCont;
120025   }
120026 
120027   /* Done. */
120028   VdbeModuleComment((v, "Begin WHERE-core"));
120029   return pWInfo;
120030 
120031   /* Jump here if malloc fails */
120032 whereBeginError:
120033   if( pWInfo ){
120034     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
120035     whereInfoFree(db, pWInfo);
120036   }
120037   return 0;
120038 }
120039 
120040 /*
120041 ** Generate the end of the WHERE loop.  See comments on
120042 ** sqlite3WhereBegin() for additional information.
120043 */
120044 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
120045   Parse *pParse = pWInfo->pParse;
120046   Vdbe *v = pParse->pVdbe;
120047   int i;
120048   WhereLevel *pLevel;
120049   WhereLoop *pLoop;
120050   SrcList *pTabList = pWInfo->pTabList;
120051   sqlite3 *db = pParse->db;
120052 
120053   /* Generate loop termination code.
120054   */
120055   VdbeModuleComment((v, "End WHERE-core"));
120056   sqlite3ExprCacheClear(pParse);
120057   for(i=pWInfo->nLevel-1; i>=0; i--){
120058     int addr;
120059     pLevel = &pWInfo->a[i];
120060     pLoop = pLevel->pWLoop;
120061     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
120062     if( pLevel->op!=OP_Noop ){
120063       sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
120064       sqlite3VdbeChangeP5(v, pLevel->p5);
120065       VdbeCoverage(v);
120066       VdbeCoverageIf(v, pLevel->op==OP_Next);
120067       VdbeCoverageIf(v, pLevel->op==OP_Prev);
120068       VdbeCoverageIf(v, pLevel->op==OP_VNext);
120069     }
120070     if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
120071       struct InLoop *pIn;
120072       int j;
120073       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
120074       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
120075         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
120076         sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
120077         VdbeCoverage(v);
120078         VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
120079         VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
120080         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
120081       }
120082       sqlite3DbFree(db, pLevel->u.in.aInLoop);
120083     }
120084     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
120085     if( pLevel->addrSkip ){
120086       sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
120087       VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
120088       sqlite3VdbeJumpHere(v, pLevel->addrSkip);
120089       sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
120090     }
120091     if( pLevel->iLeftJoin ){
120092       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
120093       assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
120094            || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
120095       if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
120096         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
120097       }
120098       if( pLoop->wsFlags & WHERE_INDEXED ){
120099         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
120100       }
120101       if( pLevel->op==OP_Return ){
120102         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
120103       }else{
120104         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
120105       }
120106       sqlite3VdbeJumpHere(v, addr);
120107     }
120108     VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
120109                      pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
120110   }
120111 
120112   /* The "break" point is here, just past the end of the outer loop.
120113   ** Set it.
120114   */
120115   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
120116 
120117   assert( pWInfo->nLevel<=pTabList->nSrc );
120118   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
120119     int k, last;
120120     VdbeOp *pOp;
120121     Index *pIdx = 0;
120122     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
120123     Table *pTab = pTabItem->pTab;
120124     assert( pTab!=0 );
120125     pLoop = pLevel->pWLoop;
120126 
120127     /* For a co-routine, change all OP_Column references to the table of
120128     ** the co-routine into OP_SCopy of result contained in a register.
120129     ** OP_Rowid becomes OP_Null.
120130     */
120131     if( pTabItem->viaCoroutine && !db->mallocFailed ){
120132       last = sqlite3VdbeCurrentAddr(v);
120133       k = pLevel->addrBody;
120134       pOp = sqlite3VdbeGetOp(v, k);
120135       for(; k<last; k++, pOp++){
120136         if( pOp->p1!=pLevel->iTabCur ) continue;
120137         if( pOp->opcode==OP_Column ){
120138           pOp->opcode = OP_Copy;
120139           pOp->p1 = pOp->p2 + pTabItem->regResult;
120140           pOp->p2 = pOp->p3;
120141           pOp->p3 = 0;
120142         }else if( pOp->opcode==OP_Rowid ){
120143           pOp->opcode = OP_Null;
120144           pOp->p1 = 0;
120145           pOp->p3 = 0;
120146         }
120147       }
120148       continue;
120149     }
120150 
120151     /* Close all of the cursors that were opened by sqlite3WhereBegin.
120152     ** Except, do not close cursors that will be reused by the OR optimization
120153     ** (WHERE_OMIT_OPEN_CLOSE).  And do not close the OP_OpenWrite cursors
120154     ** created for the ONEPASS optimization.
120155     */
120156     if( (pTab->tabFlags & TF_Ephemeral)==0
120157      && pTab->pSelect==0
120158      && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
120159     ){
120160       int ws = pLoop->wsFlags;
120161       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
120162         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
120163       }
120164       if( (ws & WHERE_INDEXED)!=0
120165        && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
120166        && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
120167       ){
120168         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
120169       }
120170     }
120171 
120172     /* If this scan uses an index, make VDBE code substitutions to read data
120173     ** from the index instead of from the table where possible.  In some cases
120174     ** this optimization prevents the table from ever being read, which can
120175     ** yield a significant performance boost.
120176     **
120177     ** Calls to the code generator in between sqlite3WhereBegin and
120178     ** sqlite3WhereEnd will have created code that references the table
120179     ** directly.  This loop scans all that code looking for opcodes
120180     ** that reference the table and converts them into opcodes that
120181     ** reference the index.
120182     */
120183     if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
120184       pIdx = pLoop->u.btree.pIndex;
120185     }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
120186       pIdx = pLevel->u.pCovidx;
120187     }
120188     if( pIdx && !db->mallocFailed ){
120189       last = sqlite3VdbeCurrentAddr(v);
120190       k = pLevel->addrBody;
120191       pOp = sqlite3VdbeGetOp(v, k);
120192       for(; k<last; k++, pOp++){
120193         if( pOp->p1!=pLevel->iTabCur ) continue;
120194         if( pOp->opcode==OP_Column ){
120195           int x = pOp->p2;
120196           assert( pIdx->pTable==pTab );
120197           if( !HasRowid(pTab) ){
120198             Index *pPk = sqlite3PrimaryKeyIndex(pTab);
120199             x = pPk->aiColumn[x];
120200           }
120201           x = sqlite3ColumnOfIndex(pIdx, x);
120202           if( x>=0 ){
120203             pOp->p2 = x;
120204             pOp->p1 = pLevel->iIdxCur;
120205           }
120206           assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
120207         }else if( pOp->opcode==OP_Rowid ){
120208           pOp->p1 = pLevel->iIdxCur;
120209           pOp->opcode = OP_IdxRowid;
120210         }
120211       }
120212     }
120213   }
120214 
120215   /* Final cleanup
120216   */
120217   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
120218   whereInfoFree(db, pWInfo);
120219   return;
120220 }
120221 
120222 /************** End of where.c ***********************************************/
120223 /************** Begin file parse.c *******************************************/
120224 /* Driver template for the LEMON parser generator.
120225 ** The author disclaims copyright to this source code.
120226 **
120227 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
120228 ** The only modifications are the addition of a couple of NEVER()
120229 ** macros to disable tests that are needed in the case of a general
120230 ** LALR(1) grammar but which are always false in the
120231 ** specific grammar used by SQLite.
120232 */
120233 /* First off, code is included that follows the "include" declaration
120234 ** in the input grammar file. */
120235 /* #include <stdio.h> */
120236 
120237 
120238 /*
120239 ** Disable all error recovery processing in the parser push-down
120240 ** automaton.
120241 */
120242 #define YYNOERRORRECOVERY 1
120243 
120244 /*
120245 ** Make yytestcase() the same as testcase()
120246 */
120247 #define yytestcase(X) testcase(X)
120248 
120249 /*
120250 ** An instance of this structure holds information about the
120251 ** LIMIT clause of a SELECT statement.
120252 */
120253 struct LimitVal {
120254   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
120255   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
120256 };
120257 
120258 /*
120259 ** An instance of this structure is used to store the LIKE,
120260 ** GLOB, NOT LIKE, and NOT GLOB operators.
120261 */
120262 struct LikeOp {
120263   Token eOperator;  /* "like" or "glob" or "regexp" */
120264   int bNot;         /* True if the NOT keyword is present */
120265 };
120266 
120267 /*
120268 ** An instance of the following structure describes the event of a
120269 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
120270 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
120271 **
120272 **      UPDATE ON (a,b,c)
120273 **
120274 ** Then the "b" IdList records the list "a,b,c".
120275 */
120276 struct TrigEvent { int a; IdList * b; };
120277 
120278 /*
120279 ** An instance of this structure holds the ATTACH key and the key type.
120280 */
120281 struct AttachKey { int type;  Token key; };
120282 
120283 
120284   /* This is a utility routine used to set the ExprSpan.zStart and
120285   ** ExprSpan.zEnd values of pOut so that the span covers the complete
120286   ** range of text beginning with pStart and going to the end of pEnd.
120287   */
120288   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
120289     pOut->zStart = pStart->z;
120290     pOut->zEnd = &pEnd->z[pEnd->n];
120291   }
120292 
120293   /* Construct a new Expr object from a single identifier.  Use the
120294   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
120295   ** that created the expression.
120296   */
120297   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
120298     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
120299     pOut->zStart = pValue->z;
120300     pOut->zEnd = &pValue->z[pValue->n];
120301   }
120302 
120303   /* This routine constructs a binary expression node out of two ExprSpan
120304   ** objects and uses the result to populate a new ExprSpan object.
120305   */
120306   static void spanBinaryExpr(
120307     ExprSpan *pOut,     /* Write the result here */
120308     Parse *pParse,      /* The parsing context.  Errors accumulate here */
120309     int op,             /* The binary operation */
120310     ExprSpan *pLeft,    /* The left operand */
120311     ExprSpan *pRight    /* The right operand */
120312   ){
120313     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
120314     pOut->zStart = pLeft->zStart;
120315     pOut->zEnd = pRight->zEnd;
120316   }
120317 
120318   /* Construct an expression node for a unary postfix operator
120319   */
120320   static void spanUnaryPostfix(
120321     ExprSpan *pOut,        /* Write the new expression node here */
120322     Parse *pParse,         /* Parsing context to record errors */
120323     int op,                /* The operator */
120324     ExprSpan *pOperand,    /* The operand */
120325     Token *pPostOp         /* The operand token for setting the span */
120326   ){
120327     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
120328     pOut->zStart = pOperand->zStart;
120329     pOut->zEnd = &pPostOp->z[pPostOp->n];
120330   }
120331 
120332   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
120333   ** unary TK_ISNULL or TK_NOTNULL expression. */
120334   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
120335     sqlite3 *db = pParse->db;
120336     if( pY && pA && pY->op==TK_NULL ){
120337       pA->op = (u8)op;
120338       sqlite3ExprDelete(db, pA->pRight);
120339       pA->pRight = 0;
120340     }
120341   }
120342 
120343   /* Construct an expression node for a unary prefix operator
120344   */
120345   static void spanUnaryPrefix(
120346     ExprSpan *pOut,        /* Write the new expression node here */
120347     Parse *pParse,         /* Parsing context to record errors */
120348     int op,                /* The operator */
120349     ExprSpan *pOperand,    /* The operand */
120350     Token *pPreOp         /* The operand token for setting the span */
120351   ){
120352     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
120353     pOut->zStart = pPreOp->z;
120354     pOut->zEnd = pOperand->zEnd;
120355   }
120356 /* Next is all token values, in a form suitable for use by makeheaders.
120357 ** This section will be null unless lemon is run with the -m switch.
120358 */
120359 /*
120360 ** These constants (all generated automatically by the parser generator)
120361 ** specify the various kinds of tokens (terminals) that the parser
120362 ** understands.
120363 **
120364 ** Each symbol here is a terminal symbol in the grammar.
120365 */
120366 /* Make sure the INTERFACE macro is defined.
120367 */
120368 #ifndef INTERFACE
120369 # define INTERFACE 1
120370 #endif
120371 /* The next thing included is series of defines which control
120372 ** various aspects of the generated parser.
120373 **    YYCODETYPE         is the data type used for storing terminal
120374 **                       and nonterminal numbers.  "unsigned char" is
120375 **                       used if there are fewer than 250 terminals
120376 **                       and nonterminals.  "int" is used otherwise.
120377 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
120378 **                       to no legal terminal or nonterminal number.  This
120379 **                       number is used to fill in empty slots of the hash
120380 **                       table.
120381 **    YYFALLBACK         If defined, this indicates that one or more tokens
120382 **                       have fall-back values which should be used if the
120383 **                       original value of the token will not parse.
120384 **    YYACTIONTYPE       is the data type used for storing terminal
120385 **                       and nonterminal numbers.  "unsigned char" is
120386 **                       used if there are fewer than 250 rules and
120387 **                       states combined.  "int" is used otherwise.
120388 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
120389 **                       directly to the parser from the tokenizer.
120390 **    YYMINORTYPE        is the data type used for all minor tokens.
120391 **                       This is typically a union of many types, one of
120392 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
120393 **                       for base tokens is called "yy0".
120394 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
120395 **                       zero the stack is dynamically sized using realloc()
120396 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
120397 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
120398 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
120399 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
120400 **    YYNSTATE           the combined number of states.
120401 **    YYNRULE            the number of rules in the grammar
120402 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
120403 **                       defined, then do no error processing.
120404 */
120405 #define YYCODETYPE unsigned char
120406 #define YYNOCODE 254
120407 #define YYACTIONTYPE unsigned short int
120408 #define YYWILDCARD 70
120409 #define sqlite3ParserTOKENTYPE Token
120410 typedef union {
120411   int yyinit;
120412   sqlite3ParserTOKENTYPE yy0;
120413   Select* yy3;
120414   ExprList* yy14;
120415   With* yy59;
120416   SrcList* yy65;
120417   struct LikeOp yy96;
120418   Expr* yy132;
120419   u8 yy186;
120420   int yy328;
120421   ExprSpan yy346;
120422   struct TrigEvent yy378;
120423   u16 yy381;
120424   IdList* yy408;
120425   struct {int value; int mask;} yy429;
120426   TriggerStep* yy473;
120427   struct LimitVal yy476;
120428 } YYMINORTYPE;
120429 #ifndef YYSTACKDEPTH
120430 #define YYSTACKDEPTH 100
120431 #endif
120432 #define sqlite3ParserARG_SDECL Parse *pParse;
120433 #define sqlite3ParserARG_PDECL ,Parse *pParse
120434 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
120435 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
120436 #define YYNSTATE 642
120437 #define YYNRULE 327
120438 #define YYFALLBACK 1
120439 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
120440 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
120441 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
120442 
120443 /* The yyzerominor constant is used to initialize instances of
120444 ** YYMINORTYPE objects to zero. */
120445 static const YYMINORTYPE yyzerominor = { 0 };
120446 
120447 /* Define the yytestcase() macro to be a no-op if is not already defined
120448 ** otherwise.
120449 **
120450 ** Applications can choose to define yytestcase() in the %include section
120451 ** to a macro that can assist in verifying code coverage.  For production
120452 ** code the yytestcase() macro should be turned off.  But it is useful
120453 ** for testing.
120454 */
120455 #ifndef yytestcase
120456 # define yytestcase(X)
120457 #endif
120458 
120459 
120460 /* Next are the tables used to determine what action to take based on the
120461 ** current state and lookahead token.  These tables are used to implement
120462 ** functions that take a state number and lookahead value and return an
120463 ** action integer.
120464 **
120465 ** Suppose the action integer is N.  Then the action is determined as
120466 ** follows
120467 **
120468 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
120469 **                                      token onto the stack and goto state N.
120470 **
120471 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
120472 **
120473 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
120474 **
120475 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
120476 **
120477 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
120478 **                                      slots in the yy_action[] table.
120479 **
120480 ** The action table is constructed as a single large table named yy_action[].
120481 ** Given state S and lookahead X, the action is computed as
120482 **
120483 **      yy_action[ yy_shift_ofst[S] + X ]
120484 **
120485 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
120486 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
120487 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
120488 ** and that yy_default[S] should be used instead.
120489 **
120490 ** The formula above is for computing the action when the lookahead is
120491 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
120492 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
120493 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
120494 ** YY_SHIFT_USE_DFLT.
120495 **
120496 ** The following are the tables generated in this section:
120497 **
120498 **  yy_action[]        A single table containing all actions.
120499 **  yy_lookahead[]     A table containing the lookahead for each entry in
120500 **                     yy_action.  Used to detect hash collisions.
120501 **  yy_shift_ofst[]    For each state, the offset into yy_action for
120502 **                     shifting terminals.
120503 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
120504 **                     shifting non-terminals after a reduce.
120505 **  yy_default[]       Default action for each state.
120506 */
120507 #define YY_ACTTAB_COUNT (1497)
120508 static const YYACTIONTYPE yy_action[] = {
120509  /*     0 */   306,  212,  432,  955,  639,  191,  955,  295,  559,   88,
120510  /*    10 */    88,   88,   88,   81,   86,   86,   86,   86,   85,   85,
120511  /*    20 */    84,   84,   84,   83,  330,  185,  184,  183,  635,  635,
120512  /*    30 */   292,  606,  606,   88,   88,   88,   88,  683,   86,   86,
120513  /*    40 */    86,   86,   85,   85,   84,   84,   84,   83,  330,   16,
120514  /*    50 */   436,  597,   89,   90,   80,  600,  599,  601,  601,   87,
120515  /*    60 */    87,   88,   88,   88,   88,  684,   86,   86,   86,   86,
120516  /*    70 */    85,   85,   84,   84,   84,   83,  330,  306,  559,   84,
120517  /*    80 */    84,   84,   83,  330,   65,   86,   86,   86,   86,   85,
120518  /*    90 */    85,   84,   84,   84,   83,  330,  635,  635,  634,  633,
120519  /*   100 */   182,  682,  550,  379,  376,  375,   17,  322,  606,  606,
120520  /*   110 */   371,  198,  479,   91,  374,   82,   79,  165,   85,   85,
120521  /*   120 */    84,   84,   84,   83,  330,  598,  635,  635,  107,   89,
120522  /*   130 */    90,   80,  600,  599,  601,  601,   87,   87,   88,   88,
120523  /*   140 */    88,   88,  186,   86,   86,   86,   86,   85,   85,   84,
120524  /*   150 */    84,   84,   83,  330,  306,  594,  594,  142,  328,  327,
120525  /*   160 */   484,  249,  344,  238,  635,  635,  634,  633,  585,  448,
120526  /*   170 */   526,  525,  229,  388,    1,  394,  450,  584,  449,  635,
120527  /*   180 */   635,  635,  635,  319,  395,  606,  606,  199,  157,  273,
120528  /*   190 */   382,  268,  381,  187,  635,  635,  634,  633,  311,  555,
120529  /*   200 */   266,  593,  593,  266,  347,  588,   89,   90,   80,  600,
120530  /*   210 */   599,  601,  601,   87,   87,   88,   88,   88,   88,  478,
120531  /*   220 */    86,   86,   86,   86,   85,   85,   84,   84,   84,   83,
120532  /*   230 */   330,  306,  272,  536,  634,  633,  146,  610,  197,  310,
120533  /*   240 */   575,  182,  482,  271,  379,  376,  375,  506,   21,  634,
120534  /*   250 */   633,  634,  633,  635,  635,  374,  611,  574,  548,  440,
120535  /*   260 */   111,  563,  606,  606,  634,  633,  324,  479,  608,  608,
120536  /*   270 */   608,  300,  435,  573,  119,  407,  210,  162,  562,  883,
120537  /*   280 */   592,  592,  306,   89,   90,   80,  600,  599,  601,  601,
120538  /*   290 */    87,   87,   88,   88,   88,   88,  506,   86,   86,   86,
120539  /*   300 */    86,   85,   85,   84,   84,   84,   83,  330,  620,  111,
120540  /*   310 */   635,  635,  361,  606,  606,  358,  249,  349,  248,  433,
120541  /*   320 */   243,  479,  586,  634,  633,  195,  611,   93,  119,  221,
120542  /*   330 */   575,  497,  534,  534,   89,   90,   80,  600,  599,  601,
120543  /*   340 */   601,   87,   87,   88,   88,   88,   88,  574,   86,   86,
120544  /*   350 */    86,   86,   85,   85,   84,   84,   84,   83,  330,  306,
120545  /*   360 */    77,  429,  638,  573,  589,  530,  240,  230,  242,  105,
120546  /*   370 */   249,  349,  248,  515,  588,  208,  460,  529,  564,  173,
120547  /*   380 */   634,  633,  970,  144,  430,    2,  424,  228,  380,  557,
120548  /*   390 */   606,  606,  190,  153,  159,  158,  514,   51,  632,  631,
120549  /*   400 */   630,   71,  536,  432,  954,  196,  610,  954,  614,   45,
120550  /*   410 */    18,   89,   90,   80,  600,  599,  601,  601,   87,   87,
120551  /*   420 */    88,   88,   88,   88,  261,   86,   86,   86,   86,   85,
120552  /*   430 */    85,   84,   84,   84,   83,  330,  306,  608,  608,  608,
120553  /*   440 */   542,  424,  402,  385,  241,  506,  451,  320,  211,  543,
120554  /*   450 */   164,  436,  386,  293,  451,  587,  108,  496,  111,  334,
120555  /*   460 */   391,  591,  424,  614,   27,  452,  453,  606,  606,   72,
120556  /*   470 */   257,   70,  259,  452,  339,  342,  564,  582,   68,  415,
120557  /*   480 */   469,  328,  327,   62,  614,   45,  110,  393,   89,   90,
120558  /*   490 */    80,  600,  599,  601,  601,   87,   87,   88,   88,   88,
120559  /*   500 */    88,  152,   86,   86,   86,   86,   85,   85,   84,   84,
120560  /*   510 */    84,   83,  330,  306,  110,  499,  520,  538,  402,  389,
120561  /*   520 */   424,  110,  566,  500,  593,  593,  454,   82,   79,  165,
120562  /*   530 */   424,  591,  384,  564,  340,  615,  188,  162,  424,  350,
120563  /*   540 */   616,  424,  614,   44,  606,  606,  445,  582,  300,  434,
120564  /*   550 */   151,   19,  614,    9,  568,  580,  348,  615,  469,  567,
120565  /*   560 */   614,   26,  616,  614,   45,   89,   90,   80,  600,  599,
120566  /*   570 */   601,  601,   87,   87,   88,   88,   88,   88,  411,   86,
120567  /*   580 */    86,   86,   86,   85,   85,   84,   84,   84,   83,  330,
120568  /*   590 */   306,  579,  110,  578,  521,  282,  433,  398,  400,  255,
120569  /*   600 */   486,   82,   79,  165,  487,  164,   82,   79,  165,  488,
120570  /*   610 */   488,  364,  387,  424,  544,  544,  509,  350,  362,  155,
120571  /*   620 */   191,  606,  606,  559,  642,  640,  333,   82,   79,  165,
120572  /*   630 */   305,  564,  507,  312,  357,  614,   45,  329,  596,  595,
120573  /*   640 */   194,  337,   89,   90,   80,  600,  599,  601,  601,   87,
120574  /*   650 */    87,   88,   88,   88,   88,  424,   86,   86,   86,   86,
120575  /*   660 */    85,   85,   84,   84,   84,   83,  330,  306,   20,  323,
120576  /*   670 */   150,  263,  211,  543,  421,  596,  595,  614,   22,  424,
120577  /*   680 */   193,  424,  284,  424,  391,  424,  509,  424,  577,  424,
120578  /*   690 */   186,  335,  424,  559,  424,  313,  120,  546,  606,  606,
120579  /*   700 */    67,  614,   47,  614,   50,  614,   48,  614,  100,  614,
120580  /*   710 */    99,  614,  101,  576,  614,  102,  614,  109,  326,   89,
120581  /*   720 */    90,   80,  600,  599,  601,  601,   87,   87,   88,   88,
120582  /*   730 */    88,   88,  424,   86,   86,   86,   86,   85,   85,   84,
120583  /*   740 */    84,   84,   83,  330,  306,  424,  311,  424,  585,   54,
120584  /*   750 */   424,  516,  517,  590,  614,  112,  424,  584,  424,  572,
120585  /*   760 */   424,  195,  424,  571,  424,   67,  424,  614,   94,  614,
120586  /*   770 */    98,  424,  614,   97,  264,  606,  606,  195,  614,   46,
120587  /*   780 */   614,   96,  614,   30,  614,   49,  614,  115,  614,  114,
120588  /*   790 */   418,  229,  388,  614,  113,  306,   89,   90,   80,  600,
120589  /*   800 */   599,  601,  601,   87,   87,   88,   88,   88,   88,  424,
120590  /*   810 */    86,   86,   86,   86,   85,   85,   84,   84,   84,   83,
120591  /*   820 */   330,  119,  424,  590,  110,  372,  606,  606,  195,   53,
120592  /*   830 */   250,  614,   29,  195,  472,  438,  729,  190,  302,  498,
120593  /*   840 */    14,  523,  641,    2,  614,   43,  306,   89,   90,   80,
120594  /*   850 */   600,  599,  601,  601,   87,   87,   88,   88,   88,   88,
120595  /*   860 */   424,   86,   86,   86,   86,   85,   85,   84,   84,   84,
120596  /*   870 */    83,  330,  424,  613,  964,  964,  354,  606,  606,  420,
120597  /*   880 */   312,   64,  614,   42,  391,  355,  283,  437,  301,  255,
120598  /*   890 */   414,  410,  495,  492,  614,   28,  471,  306,   89,   90,
120599  /*   900 */    80,  600,  599,  601,  601,   87,   87,   88,   88,   88,
120600  /*   910 */    88,  424,   86,   86,   86,   86,   85,   85,   84,   84,
120601  /*   920 */    84,   83,  330,  424,  110,  110,  110,  110,  606,  606,
120602  /*   930 */   110,  254,   13,  614,   41,  532,  531,  283,  481,  531,
120603  /*   940 */   457,  284,  119,  561,  356,  614,   40,  284,  306,   89,
120604  /*   950 */    78,   80,  600,  599,  601,  601,   87,   87,   88,   88,
120605  /*   960 */    88,   88,  424,   86,   86,   86,   86,   85,   85,   84,
120606  /*   970 */    84,   84,   83,  330,  110,  424,  341,  220,  555,  606,
120607  /*   980 */   606,  351,  555,  318,  614,   95,  413,  255,   83,  330,
120608  /*   990 */   284,  284,  255,  640,  333,  356,  255,  614,   39,  306,
120609  /*  1000 */   356,   90,   80,  600,  599,  601,  601,   87,   87,   88,
120610  /*  1010 */    88,   88,   88,  424,   86,   86,   86,   86,   85,   85,
120611  /*  1020 */    84,   84,   84,   83,  330,  424,  317,  316,  141,  465,
120612  /*  1030 */   606,  606,  219,  619,  463,  614,   10,  417,  462,  255,
120613  /*  1040 */   189,  510,  553,  351,  207,  363,  161,  614,   38,  315,
120614  /*  1050 */   218,  255,  255,   80,  600,  599,  601,  601,   87,   87,
120615  /*  1060 */    88,   88,   88,   88,  424,   86,   86,   86,   86,   85,
120616  /*  1070 */    85,   84,   84,   84,   83,  330,   76,  419,  255,    3,
120617  /*  1080 */   878,  461,  424,  247,  331,  331,  614,   37,  217,   76,
120618  /*  1090 */   419,  390,    3,  216,  215,  422,    4,  331,  331,  424,
120619  /*  1100 */   547,   12,  424,  545,  614,   36,  424,  541,  422,  424,
120620  /*  1110 */   540,  424,  214,  424,  408,  424,  539,  403,  605,  605,
120621  /*  1120 */   237,  614,   25,  119,  614,   24,  588,  408,  614,   45,
120622  /*  1130 */   118,  614,   35,  614,   34,  614,   33,  614,   23,  588,
120623  /*  1140 */    60,  223,  603,  602,  513,  378,   73,   74,  140,  139,
120624  /*  1150 */   424,  110,  265,   75,  426,  425,   59,  424,  610,   73,
120625  /*  1160 */    74,  549,  402,  404,  424,  373,   75,  426,  425,  604,
120626  /*  1170 */   138,  610,  614,   11,  392,   76,  419,  181,    3,  614,
120627  /*  1180 */    32,  271,  369,  331,  331,  493,  614,   31,  149,  608,
120628  /*  1190 */   608,  608,  607,   15,  422,  365,  614,    8,  137,  489,
120629  /*  1200 */   136,  190,  608,  608,  608,  607,   15,  485,  176,  135,
120630  /*  1210 */     7,  252,  477,  408,  174,  133,  175,  474,   57,   56,
120631  /*  1220 */   132,  130,  119,   76,  419,  588,    3,  468,  245,  464,
120632  /*  1230 */   171,  331,  331,  125,  123,  456,  447,  122,  446,  104,
120633  /*  1240 */   336,  231,  422,  166,  154,   73,   74,  332,  116,  431,
120634  /*  1250 */   121,  309,   75,  426,  425,  222,  106,  610,  308,  637,
120635  /*  1260 */   204,  408,  629,  627,  628,    6,  200,  428,  427,  290,
120636  /*  1270 */   203,  622,  201,  588,   62,   63,  289,   66,  419,  399,
120637  /*  1280 */     3,  401,  288,   92,  143,  331,  331,  287,  608,  608,
120638  /*  1290 */   608,  607,   15,   73,   74,  227,  422,  325,   69,  416,
120639  /*  1300 */    75,  426,  425,  612,  412,  610,  192,   61,  569,  209,
120640  /*  1310 */   396,  226,  278,  225,  383,  408,  527,  558,  276,  533,
120641  /*  1320 */   552,  528,  321,  523,  370,  508,  180,  588,  494,  179,
120642  /*  1330 */   366,  117,  253,  269,  522,  503,  608,  608,  608,  607,
120643  /*  1340 */    15,  551,  502,   58,  274,  524,  178,   73,   74,  304,
120644  /*  1350 */   501,  368,  303,  206,   75,  426,  425,  491,  360,  610,
120645  /*  1360 */   213,  177,  483,  131,  345,  298,  297,  296,  202,  294,
120646  /*  1370 */   480,  490,  466,  134,  172,  129,  444,  346,  470,  128,
120647  /*  1380 */   314,  459,  103,  127,  126,  148,  124,  167,  443,  235,
120648  /*  1390 */   608,  608,  608,  607,   15,  442,  439,  623,  234,  299,
120649  /*  1400 */   145,  583,  291,  377,  581,  160,  119,  156,  270,  636,
120650  /*  1410 */   971,  169,  279,  626,  520,  625,  473,  624,  170,  621,
120651  /*  1420 */   618,  119,  168,   55,  409,  423,  537,  609,  286,  285,
120652  /*  1430 */   405,  570,  560,  556,    5,   52,  458,  554,  147,  267,
120653  /*  1440 */   519,  504,  518,  406,  262,  239,  260,  512,  343,  511,
120654  /*  1450 */   258,  353,  565,  256,  224,  251,  359,  277,  275,  476,
120655  /*  1460 */   475,  246,  352,  244,  467,  455,  236,  233,  232,  307,
120656  /*  1470 */   441,  281,  205,  163,  397,  280,  535,  505,  330,  617,
120657  /*  1480 */   971,  971,  971,  971,  367,  971,  971,  971,  971,  971,
120658  /*  1490 */   971,  971,  971,  971,  971,  971,  338,
120659 };
120660 static const YYCODETYPE yy_lookahead[] = {
120661  /*     0 */    19,   22,   22,   23,    1,   24,   26,   15,   27,   80,
120662  /*    10 */    81,   82,   83,   84,   85,   86,   87,   88,   89,   90,
120663  /*    20 */    91,   92,   93,   94,   95,  108,  109,  110,   27,   28,
120664  /*    30 */    23,   50,   51,   80,   81,   82,   83,  122,   85,   86,
120665  /*    40 */    87,   88,   89,   90,   91,   92,   93,   94,   95,   22,
120666  /*    50 */    70,   23,   71,   72,   73,   74,   75,   76,   77,   78,
120667  /*    60 */    79,   80,   81,   82,   83,  122,   85,   86,   87,   88,
120668  /*    70 */    89,   90,   91,   92,   93,   94,   95,   19,   97,   91,
120669  /*    80 */    92,   93,   94,   95,   26,   85,   86,   87,   88,   89,
120670  /*    90 */    90,   91,   92,   93,   94,   95,   27,   28,   97,   98,
120671  /*   100 */    99,  122,  211,  102,  103,  104,   79,   19,   50,   51,
120672  /*   110 */    19,  122,   59,   55,  113,  224,  225,  226,   89,   90,
120673  /*   120 */    91,   92,   93,   94,   95,   23,   27,   28,   26,   71,
120674  /*   130 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
120675  /*   140 */    82,   83,   51,   85,   86,   87,   88,   89,   90,   91,
120676  /*   150 */    92,   93,   94,   95,   19,  132,  133,   58,   89,   90,
120677  /*   160 */    21,  108,  109,  110,   27,   28,   97,   98,   33,  100,
120678  /*   170 */     7,    8,  119,  120,   22,   19,  107,   42,  109,   27,
120679  /*   180 */    28,   27,   28,   95,   28,   50,   51,   99,  100,  101,
120680  /*   190 */   102,  103,  104,  105,   27,   28,   97,   98,  107,  152,
120681  /*   200 */   112,  132,  133,  112,   65,   69,   71,   72,   73,   74,
120682  /*   210 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   11,
120683  /*   220 */    85,   86,   87,   88,   89,   90,   91,   92,   93,   94,
120684  /*   230 */    95,   19,  101,   97,   97,   98,   24,  101,  122,  157,
120685  /*   240 */    12,   99,  103,  112,  102,  103,  104,  152,   22,   97,
120686  /*   250 */    98,   97,   98,   27,   28,  113,   27,   29,   91,  164,
120687  /*   260 */   165,  124,   50,   51,   97,   98,  219,   59,  132,  133,
120688  /*   270 */   134,   22,   23,   45,   66,   47,  212,  213,  124,  140,
120689  /*   280 */   132,  133,   19,   71,   72,   73,   74,   75,   76,   77,
120690  /*   290 */    78,   79,   80,   81,   82,   83,  152,   85,   86,   87,
120691  /*   300 */    88,   89,   90,   91,   92,   93,   94,   95,  164,  165,
120692  /*   310 */    27,   28,  230,   50,   51,  233,  108,  109,  110,   70,
120693  /*   320 */    16,   59,   23,   97,   98,   26,   97,   22,   66,  185,
120694  /*   330 */    12,  187,   27,   28,   71,   72,   73,   74,   75,   76,
120695  /*   340 */    77,   78,   79,   80,   81,   82,   83,   29,   85,   86,
120696  /*   350 */    87,   88,   89,   90,   91,   92,   93,   94,   95,   19,
120697  /*   360 */    22,  148,  149,   45,   23,   47,   62,  154,   64,  156,
120698  /*   370 */   108,  109,  110,   37,   69,   23,  163,   59,   26,   26,
120699  /*   380 */    97,   98,  144,  145,  146,  147,  152,  200,   52,   23,
120700  /*   390 */    50,   51,   26,   22,   89,   90,   60,  210,    7,    8,
120701  /*   400 */     9,  138,   97,   22,   23,   26,  101,   26,  174,  175,
120702  /*   410 */   197,   71,   72,   73,   74,   75,   76,   77,   78,   79,
120703  /*   420 */    80,   81,   82,   83,   16,   85,   86,   87,   88,   89,
120704  /*   430 */    90,   91,   92,   93,   94,   95,   19,  132,  133,  134,
120705  /*   440 */    23,  152,  208,  209,  140,  152,  152,  111,  195,  196,
120706  /*   450 */    98,   70,  163,  160,  152,   23,   22,  164,  165,  246,
120707  /*   460 */   207,   27,  152,  174,  175,  171,  172,   50,   51,  137,
120708  /*   470 */    62,  139,   64,  171,  172,  222,  124,   27,  138,   24,
120709  /*   480 */   163,   89,   90,  130,  174,  175,  197,  163,   71,   72,
120710  /*   490 */    73,   74,   75,   76,   77,   78,   79,   80,   81,   82,
120711  /*   500 */    83,   22,   85,   86,   87,   88,   89,   90,   91,   92,
120712  /*   510 */    93,   94,   95,   19,  197,  181,  182,   23,  208,  209,
120713  /*   520 */   152,  197,   26,  189,  132,  133,  232,  224,  225,  226,
120714  /*   530 */   152,   97,   91,   26,  232,  116,  212,  213,  152,  222,
120715  /*   540 */   121,  152,  174,  175,   50,   51,  243,   97,   22,   23,
120716  /*   550 */    22,  234,  174,  175,  177,   23,  239,  116,  163,  177,
120717  /*   560 */   174,  175,  121,  174,  175,   71,   72,   73,   74,   75,
120718  /*   570 */    76,   77,   78,   79,   80,   81,   82,   83,   24,   85,
120719  /*   580 */    86,   87,   88,   89,   90,   91,   92,   93,   94,   95,
120720  /*   590 */    19,   23,  197,   11,   23,  227,   70,  208,  220,  152,
120721  /*   600 */    31,  224,  225,  226,   35,   98,  224,  225,  226,  108,
120722  /*   610 */   109,  110,  115,  152,  117,  118,   27,  222,   49,  123,
120723  /*   620 */    24,   50,   51,   27,    0,    1,    2,  224,  225,  226,
120724  /*   630 */   166,  124,  168,  169,  239,  174,  175,  170,  171,  172,
120725  /*   640 */    22,  194,   71,   72,   73,   74,   75,   76,   77,   78,
120726  /*   650 */    79,   80,   81,   82,   83,  152,   85,   86,   87,   88,
120727  /*   660 */    89,   90,   91,   92,   93,   94,   95,   19,   22,  208,
120728  /*   670 */    24,   23,  195,  196,  170,  171,  172,  174,  175,  152,
120729  /*   680 */    26,  152,  152,  152,  207,  152,   97,  152,   23,  152,
120730  /*   690 */    51,  244,  152,   97,  152,  247,  248,   23,   50,   51,
120731  /*   700 */    26,  174,  175,  174,  175,  174,  175,  174,  175,  174,
120732  /*   710 */   175,  174,  175,   23,  174,  175,  174,  175,  188,   71,
120733  /*   720 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
120734  /*   730 */    82,   83,  152,   85,   86,   87,   88,   89,   90,   91,
120735  /*   740 */    92,   93,   94,   95,   19,  152,  107,  152,   33,   24,
120736  /*   750 */   152,  100,  101,   27,  174,  175,  152,   42,  152,   23,
120737  /*   760 */   152,   26,  152,   23,  152,   26,  152,  174,  175,  174,
120738  /*   770 */   175,  152,  174,  175,   23,   50,   51,   26,  174,  175,
120739  /*   780 */   174,  175,  174,  175,  174,  175,  174,  175,  174,  175,
120740  /*   790 */   163,  119,  120,  174,  175,   19,   71,   72,   73,   74,
120741  /*   800 */    75,   76,   77,   78,   79,   80,   81,   82,   83,  152,
120742  /*   810 */    85,   86,   87,   88,   89,   90,   91,   92,   93,   94,
120743  /*   820 */    95,   66,  152,   97,  197,   23,   50,   51,   26,   53,
120744  /*   830 */    23,  174,  175,   26,   23,   23,   23,   26,   26,   26,
120745  /*   840 */    36,  106,  146,  147,  174,  175,   19,   71,   72,   73,
120746  /*   850 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
120747  /*   860 */   152,   85,   86,   87,   88,   89,   90,   91,   92,   93,
120748  /*   870 */    94,   95,  152,  196,  119,  120,   19,   50,   51,  168,
120749  /*   880 */   169,   26,  174,  175,  207,   28,  152,  249,  250,  152,
120750  /*   890 */   163,  163,  163,  163,  174,  175,  163,   19,   71,   72,
120751  /*   900 */    73,   74,   75,   76,   77,   78,   79,   80,   81,   82,
120752  /*   910 */    83,  152,   85,   86,   87,   88,   89,   90,   91,   92,
120753  /*   920 */    93,   94,   95,  152,  197,  197,  197,  197,   50,   51,
120754  /*   930 */   197,  194,   36,  174,  175,  191,  192,  152,  191,  192,
120755  /*   940 */   163,  152,   66,  124,  152,  174,  175,  152,   19,   71,
120756  /*   950 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
120757  /*   960 */    82,   83,  152,   85,   86,   87,   88,   89,   90,   91,
120758  /*   970 */    92,   93,   94,   95,  197,  152,  100,  188,  152,   50,
120759  /*   980 */    51,  152,  152,  188,  174,  175,  252,  152,   94,   95,
120760  /*   990 */   152,  152,  152,    1,    2,  152,  152,  174,  175,   19,
120761  /*  1000 */   152,   72,   73,   74,   75,   76,   77,   78,   79,   80,
120762  /*  1010 */    81,   82,   83,  152,   85,   86,   87,   88,   89,   90,
120763  /*  1020 */    91,   92,   93,   94,   95,  152,  188,  188,   22,  194,
120764  /*  1030 */    50,   51,  240,  173,  194,  174,  175,  252,  194,  152,
120765  /*  1040 */    36,  181,   28,  152,   23,  219,  122,  174,  175,  219,
120766  /*  1050 */   221,  152,  152,   73,   74,   75,   76,   77,   78,   79,
120767  /*  1060 */    80,   81,   82,   83,  152,   85,   86,   87,   88,   89,
120768  /*  1070 */    90,   91,   92,   93,   94,   95,   19,   20,  152,   22,
120769  /*  1080 */    23,  194,  152,  240,   27,   28,  174,  175,  240,   19,
120770  /*  1090 */    20,   26,   22,  194,  194,   38,   22,   27,   28,  152,
120771  /*  1100 */    23,   22,  152,  116,  174,  175,  152,   23,   38,  152,
120772  /*  1110 */    23,  152,  221,  152,   57,  152,   23,  163,   50,   51,
120773  /*  1120 */   194,  174,  175,   66,  174,  175,   69,   57,  174,  175,
120774  /*  1130 */    40,  174,  175,  174,  175,  174,  175,  174,  175,   69,
120775  /*  1140 */    22,   53,   74,   75,   30,   53,   89,   90,   22,   22,
120776  /*  1150 */   152,  197,   23,   96,   97,   98,   22,  152,  101,   89,
120777  /*  1160 */    90,   91,  208,  209,  152,   53,   96,   97,   98,  101,
120778  /*  1170 */    22,  101,  174,  175,  152,   19,   20,  105,   22,  174,
120779  /*  1180 */   175,  112,   19,   27,   28,   20,  174,  175,   24,  132,
120780  /*  1190 */   133,  134,  135,  136,   38,   44,  174,  175,  107,   61,
120781  /*  1200 */    54,   26,  132,  133,  134,  135,  136,   54,  107,   22,
120782  /*  1210 */     5,  140,    1,   57,   36,  111,  122,   28,   79,   79,
120783  /*  1220 */   131,  123,   66,   19,   20,   69,   22,    1,   16,   20,
120784  /*  1230 */   125,   27,   28,  123,  111,  120,   23,  131,   23,   16,
120785  /*  1240 */    68,  142,   38,   15,   22,   89,   90,    3,  167,    4,
120786  /*  1250 */   248,  251,   96,   97,   98,  180,  180,  101,  251,  151,
120787  /*  1260 */     6,   57,  151,   13,  151,   26,   25,  151,  161,  202,
120788  /*  1270 */   153,  162,  153,   69,  130,  128,  203,   19,   20,  127,
120789  /*  1280 */    22,  126,  204,  129,   22,   27,   28,  205,  132,  133,
120790  /*  1290 */   134,  135,  136,   89,   90,  231,   38,   95,  137,  179,
120791  /*  1300 */    96,   97,   98,  206,  179,  101,  122,  107,  159,  159,
120792  /*  1310 */   125,  231,  216,  228,  107,   57,  184,  217,  216,  176,
120793  /*  1320 */   217,  176,   48,  106,   18,  184,  158,   69,  159,  158,
120794  /*  1330 */    46,   71,  237,  176,  176,  176,  132,  133,  134,  135,
120795  /*  1340 */   136,  217,  176,  137,  216,  178,  158,   89,   90,  179,
120796  /*  1350 */   176,  159,  179,  159,   96,   97,   98,  159,  159,  101,
120797  /*  1360 */     5,  158,  202,   22,   18,   10,   11,   12,   13,   14,
120798  /*  1370 */   190,  238,   17,  190,  158,  193,   41,  159,  202,  193,
120799  /*  1380 */   159,  202,  245,  193,  193,  223,  190,   32,  159,   34,
120800  /*  1390 */   132,  133,  134,  135,  136,  159,   39,  155,   43,  150,
120801  /*  1400 */   223,  177,  201,  178,  177,  186,   66,  199,  177,  152,
120802  /*  1410 */   253,   56,  215,  152,  182,  152,  202,  152,   63,  152,
120803  /*  1420 */   152,   66,   67,  242,  229,  152,  174,  152,  152,  152,
120804  /*  1430 */   152,  152,  152,  152,  199,  242,  202,  152,  198,  152,
120805  /*  1440 */   152,  152,  183,  192,  152,  215,  152,  183,  215,  183,
120806  /*  1450 */   152,  241,  214,  152,  211,  152,  152,  211,  211,  152,
120807  /*  1460 */   152,  241,  152,  152,  152,  152,  152,  152,  152,  114,
120808  /*  1470 */   152,  152,  235,  152,  152,  152,  174,  187,   95,  174,
120809  /*  1480 */   253,  253,  253,  253,  236,  253,  253,  253,  253,  253,
120810  /*  1490 */   253,  253,  253,  253,  253,  253,  141,
120811 };
120812 #define YY_SHIFT_USE_DFLT (-86)
120813 #define YY_SHIFT_COUNT (429)
120814 #define YY_SHIFT_MIN   (-85)
120815 #define YY_SHIFT_MAX   (1383)
120816 static const short yy_shift_ofst[] = {
120817  /*     0 */   992, 1057, 1355, 1156, 1204, 1204,    1,  262,  -19,  135,
120818  /*    10 */   135,  776, 1204, 1204, 1204, 1204,   69,   69,   53,  208,
120819  /*    20 */   283,  755,   58,  725,  648,  571,  494,  417,  340,  263,
120820  /*    30 */   212,  827,  827,  827,  827,  827,  827,  827,  827,  827,
120821  /*    40 */   827,  827,  827,  827,  827,  827,  878,  827,  929,  980,
120822  /*    50 */   980, 1070, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
120823  /*    60 */  1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
120824  /*    70 */  1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
120825  /*    80 */  1258, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
120826  /*    90 */  1204, 1204, 1204, 1204,  -71,  -47,  -47,  -47,  -47,  -47,
120827  /*   100 */     0,   29,  -12,  283,  283,  139,   91,  392,  392,  894,
120828  /*   110 */   672,  726, 1383,  -86,  -86,  -86,   88,  318,  318,   99,
120829  /*   120 */   381,  -20,  283,  283,  283,  283,  283,  283,  283,  283,
120830  /*   130 */   283,  283,  283,  283,  283,  283,  283,  283,  283,  283,
120831  /*   140 */   283,  283,  283,  283,  624,  876,  726,  672, 1340, 1340,
120832  /*   150 */  1340, 1340, 1340, 1340,  -86,  -86,  -86,  305,  136,  136,
120833  /*   160 */   142,  167,  226,  154,  137,  152,  283,  283,  283,  283,
120834  /*   170 */   283,  283,  283,  283,  283,  283,  283,  283,  283,  283,
120835  /*   180 */   283,  283,  283,  336,  336,  336,  283,  283,  352,  283,
120836  /*   190 */   283,  283,  283,  283,  228,  283,  283,  283,  283,  283,
120837  /*   200 */   283,  283,  283,  283,  283,  501,  569,  596,  596,  596,
120838  /*   210 */   507,  497,  441,  391,  353,  156,  156,  857,  353,  857,
120839  /*   220 */   735,  813,  639,  715,  156,  332,  715,  715,  496,  419,
120840  /*   230 */   646, 1357, 1184, 1184, 1335, 1335, 1184, 1341, 1260, 1144,
120841  /*   240 */  1346, 1346, 1346, 1346, 1184, 1306, 1144, 1341, 1260, 1260,
120842  /*   250 */  1144, 1184, 1306, 1206, 1284, 1184, 1184, 1306, 1184, 1306,
120843  /*   260 */  1184, 1306, 1262, 1207, 1207, 1207, 1274, 1262, 1207, 1217,
120844  /*   270 */  1207, 1274, 1207, 1207, 1185, 1200, 1185, 1200, 1185, 1200,
120845  /*   280 */  1184, 1184, 1161, 1262, 1202, 1202, 1262, 1154, 1155, 1147,
120846  /*   290 */  1152, 1144, 1241, 1239, 1250, 1250, 1254, 1254, 1254, 1254,
120847  /*   300 */   -86,  -86,  -86,  -86,  -86,  -86, 1068,  304,  526,  249,
120848  /*   310 */   408,  -83,  434,  812,   27,  811,  807,  802,  751,  589,
120849  /*   320 */   651,  163,  131,  674,  366,  450,  299,  148,   23,  102,
120850  /*   330 */   229,  -21, 1245, 1244, 1222, 1099, 1228, 1172, 1223, 1215,
120851  /*   340 */  1213, 1115, 1106, 1123, 1110, 1209, 1105, 1212, 1226, 1098,
120852  /*   350 */  1089, 1140, 1139, 1104, 1189, 1178, 1094, 1211, 1205, 1187,
120853  /*   360 */  1101, 1071, 1153, 1175, 1146, 1138, 1151, 1091, 1164, 1165,
120854  /*   370 */  1163, 1069, 1072, 1148, 1112, 1134, 1127, 1129, 1126, 1092,
120855  /*   380 */  1114, 1118, 1088, 1090, 1093, 1087, 1084,  987, 1079, 1077,
120856  /*   390 */  1074, 1065,  924, 1021, 1014, 1004, 1006,  819,  739,  896,
120857  /*   400 */   855,  804,  739,  740,  736,  690,  654,  665,  618,  582,
120858  /*   410 */   568,  528,  554,  379,  532,  479,  455,  379,  432,  371,
120859  /*   420 */   341,   28,  338,  116,  -11,  -57,  -85,    7,   -8,    3,
120860 };
120861 #define YY_REDUCE_USE_DFLT (-110)
120862 #define YY_REDUCE_COUNT (305)
120863 #define YY_REDUCE_MIN   (-109)
120864 #define YY_REDUCE_MAX   (1323)
120865 static const short yy_reduce_ofst[] = {
120866  /*     0 */   238,  954,  213,  289,  310,  234,  144,  317, -109,  382,
120867  /*    10 */   377,  303,  461,  389,  378,  368,  302,  294,  253,  395,
120868  /*    20 */   293,  324,  403,  403,  403,  403,  403,  403,  403,  403,
120869  /*    30 */   403,  403,  403,  403,  403,  403,  403,  403,  403,  403,
120870  /*    40 */   403,  403,  403,  403,  403,  403,  403,  403,  403,  403,
120871  /*    50 */   403, 1022, 1012, 1005,  998,  963,  961,  959,  957,  950,
120872  /*    60 */   947,  930,  912,  873,  861,  823,  810,  771,  759,  720,
120873  /*    70 */   708,  670,  657,  619,  614,  612,  610,  608,  606,  604,
120874  /*    80 */   598,  595,  593,  580,  542,  540,  537,  535,  533,  531,
120875  /*    90 */   529,  527,  503,  386,  403,  403,  403,  403,  403,  403,
120876  /*   100 */   403,  403,  403,   95,  447,   82,  334,  504,  467,  403,
120877  /*   110 */   477,  464,  403,  403,  403,  403,  860,  747,  744,  785,
120878  /*   120 */   638,  638,  926,  891,  900,  899,  887,  844,  840,  835,
120879  /*   130 */   848,  830,  843,  829,  792,  839,  826,  737,  838,  795,
120880  /*   140 */   789,   47,  734,  530,  696,  777,  711,  677,  733,  730,
120881  /*   150 */   729,  728,  727,  627,  448,   64,  187, 1305, 1302, 1252,
120882  /*   160 */  1290, 1273, 1323, 1322, 1321, 1319, 1318, 1316, 1315, 1314,
120883  /*   170 */  1313, 1312, 1311, 1310, 1308, 1307, 1304, 1303, 1301, 1298,
120884  /*   180 */  1294, 1292, 1289, 1266, 1264, 1259, 1288, 1287, 1238, 1285,
120885  /*   190 */  1281, 1280, 1279, 1278, 1251, 1277, 1276, 1275, 1273, 1268,
120886  /*   200 */  1267, 1265, 1263, 1261, 1257, 1248, 1237, 1247, 1246, 1243,
120887  /*   210 */  1238, 1240, 1235, 1249, 1234, 1233, 1230, 1220, 1214, 1210,
120888  /*   220 */  1225, 1219, 1232, 1231, 1197, 1195, 1227, 1224, 1201, 1208,
120889  /*   230 */  1242, 1137, 1236, 1229, 1193, 1181, 1221, 1177, 1196, 1179,
120890  /*   240 */  1191, 1190, 1186, 1182, 1218, 1216, 1176, 1162, 1183, 1180,
120891  /*   250 */  1160, 1199, 1203, 1133, 1095, 1198, 1194, 1188, 1192, 1171,
120892  /*   260 */  1169, 1168, 1173, 1174, 1166, 1159, 1141, 1170, 1158, 1167,
120893  /*   270 */  1157, 1132, 1145, 1143, 1124, 1128, 1103, 1102, 1100, 1096,
120894  /*   280 */  1150, 1149, 1085, 1125, 1080, 1064, 1120, 1097, 1082, 1078,
120895  /*   290 */  1073, 1067, 1109, 1107, 1119, 1117, 1116, 1113, 1111, 1108,
120896  /*   300 */  1007, 1000, 1002, 1076, 1075, 1081,
120897 };
120898 static const YYACTIONTYPE yy_default[] = {
120899  /*     0 */   647,  964,  964,  964,  878,  878,  969,  964,  774,  802,
120900  /*    10 */   802,  938,  969,  969,  969,  876,  969,  969,  969,  964,
120901  /*    20 */   969,  778,  808,  969,  969,  969,  969,  969,  969,  969,
120902  /*    30 */   969,  937,  939,  816,  815,  918,  789,  813,  806,  810,
120903  /*    40 */   879,  872,  873,  871,  875,  880,  969,  809,  841,  856,
120904  /*    50 */   840,  969,  969,  969,  969,  969,  969,  969,  969,  969,
120905  /*    60 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
120906  /*    70 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
120907  /*    80 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
120908  /*    90 */   969,  969,  969,  969,  850,  855,  862,  854,  851,  843,
120909  /*   100 */   842,  844,  845,  969,  969,  673,  739,  969,  969,  846,
120910  /*   110 */   969,  685,  847,  859,  858,  857,  680,  969,  969,  969,
120911  /*   120 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
120912  /*   130 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
120913  /*   140 */   969,  969,  969,  969,  647,  964,  969,  969,  964,  964,
120914  /*   150 */   964,  964,  964,  964,  956,  778,  768,  969,  969,  969,
120915  /*   160 */   969,  969,  969,  969,  969,  969,  969,  944,  942,  969,
120916  /*   170 */   891,  969,  969,  969,  969,  969,  969,  969,  969,  969,
120917  /*   180 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
120918  /*   190 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
120919  /*   200 */   969,  969,  969,  969,  653,  969,  911,  774,  774,  774,
120920  /*   210 */   776,  754,  766,  655,  812,  791,  791,  923,  812,  923,
120921  /*   220 */   710,  733,  707,  802,  791,  874,  802,  802,  775,  766,
120922  /*   230 */   969,  949,  782,  782,  941,  941,  782,  821,  743,  812,
120923  /*   240 */   750,  750,  750,  750,  782,  670,  812,  821,  743,  743,
120924  /*   250 */   812,  782,  670,  917,  915,  782,  782,  670,  782,  670,
120925  /*   260 */   782,  670,  884,  741,  741,  741,  725,  884,  741,  710,
120926  /*   270 */   741,  725,  741,  741,  795,  790,  795,  790,  795,  790,
120927  /*   280 */   782,  782,  969,  884,  888,  888,  884,  807,  796,  805,
120928  /*   290 */   803,  812,  676,  728,  663,  663,  652,  652,  652,  652,
120929  /*   300 */   961,  961,  956,  712,  712,  695,  969,  969,  969,  969,
120930  /*   310 */   969,  969,  687,  969,  893,  969,  969,  969,  969,  969,
120931  /*   320 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
120932  /*   330 */   969,  828,  969,  648,  951,  969,  969,  948,  969,  969,
120933  /*   340 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
120934  /*   350 */   969,  969,  969,  969,  969,  969,  921,  969,  969,  969,
120935  /*   360 */   969,  969,  969,  914,  913,  969,  969,  969,  969,  969,
120936  /*   370 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
120937  /*   380 */   969,  969,  969,  969,  969,  969,  969,  757,  969,  969,
120938  /*   390 */   969,  761,  969,  969,  969,  969,  969,  969,  804,  969,
120939  /*   400 */   797,  969,  877,  969,  969,  969,  969,  969,  969,  969,
120940  /*   410 */   969,  969,  969,  966,  969,  969,  969,  965,  969,  969,
120941  /*   420 */   969,  969,  969,  830,  969,  829,  833,  969,  661,  969,
120942  /*   430 */   644,  649,  960,  963,  962,  959,  958,  957,  952,  950,
120943  /*   440 */   947,  946,  945,  943,  940,  936,  897,  895,  902,  901,
120944  /*   450 */   900,  899,  898,  896,  894,  892,  818,  817,  814,  811,
120945  /*   460 */   753,  935,  890,  752,  749,  748,  669,  953,  920,  929,
120946  /*   470 */   928,  927,  822,  926,  925,  924,  922,  919,  906,  820,
120947  /*   480 */   819,  744,  882,  881,  672,  910,  909,  908,  912,  916,
120948  /*   490 */   907,  784,  751,  671,  668,  675,  679,  731,  732,  740,
120949  /*   500 */   738,  737,  736,  735,  734,  730,  681,  686,  724,  709,
120950  /*   510 */   708,  717,  716,  722,  721,  720,  719,  718,  715,  714,
120951  /*   520 */   713,  706,  705,  711,  704,  727,  726,  723,  703,  747,
120952  /*   530 */   746,  745,  742,  702,  701,  700,  833,  699,  698,  838,
120953  /*   540 */   837,  866,  826,  755,  759,  758,  762,  763,  771,  770,
120954  /*   550 */   769,  780,  781,  793,  792,  824,  823,  794,  779,  773,
120955  /*   560 */   772,  788,  787,  786,  785,  777,  767,  799,  798,  868,
120956  /*   570 */   783,  867,  865,  934,  933,  932,  931,  930,  870,  967,
120957  /*   580 */   968,  887,  889,  886,  801,  800,  885,  869,  839,  836,
120958  /*   590 */   690,  691,  905,  904,  903,  693,  692,  689,  688,  863,
120959  /*   600 */   860,  852,  864,  861,  853,  849,  848,  834,  832,  831,
120960  /*   610 */   827,  835,  760,  756,  825,  765,  764,  697,  696,  694,
120961  /*   620 */   678,  677,  674,  667,  665,  664,  666,  662,  660,  659,
120962  /*   630 */   658,  657,  656,  684,  683,  682,  654,  651,  650,  646,
120963  /*   640 */   645,  643,
120964 };
120965 
120966 /* The next table maps tokens into fallback tokens.  If a construct
120967 ** like the following:
120968 **
120969 **      %fallback ID X Y Z.
120970 **
120971 ** appears in the grammar, then ID becomes a fallback token for X, Y,
120972 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
120973 ** but it does not parse, the type of the token is changed to ID and
120974 ** the parse is retried before an error is thrown.
120975 */
120976 #ifdef YYFALLBACK
120977 static const YYCODETYPE yyFallback[] = {
120978     0,  /*          $ => nothing */
120979     0,  /*       SEMI => nothing */
120980    27,  /*    EXPLAIN => ID */
120981    27,  /*      QUERY => ID */
120982    27,  /*       PLAN => ID */
120983    27,  /*      BEGIN => ID */
120984     0,  /* TRANSACTION => nothing */
120985    27,  /*   DEFERRED => ID */
120986    27,  /*  IMMEDIATE => ID */
120987    27,  /*  EXCLUSIVE => ID */
120988     0,  /*     COMMIT => nothing */
120989    27,  /*        END => ID */
120990    27,  /*   ROLLBACK => ID */
120991    27,  /*  SAVEPOINT => ID */
120992    27,  /*    RELEASE => ID */
120993     0,  /*         TO => nothing */
120994     0,  /*      TABLE => nothing */
120995     0,  /*     CREATE => nothing */
120996    27,  /*         IF => ID */
120997     0,  /*        NOT => nothing */
120998     0,  /*     EXISTS => nothing */
120999    27,  /*       TEMP => ID */
121000     0,  /*         LP => nothing */
121001     0,  /*         RP => nothing */
121002     0,  /*         AS => nothing */
121003    27,  /*    WITHOUT => ID */
121004     0,  /*      COMMA => nothing */
121005     0,  /*         ID => nothing */
121006     0,  /*    INDEXED => nothing */
121007    27,  /*      ABORT => ID */
121008    27,  /*     ACTION => ID */
121009    27,  /*      AFTER => ID */
121010    27,  /*    ANALYZE => ID */
121011    27,  /*        ASC => ID */
121012    27,  /*     ATTACH => ID */
121013    27,  /*     BEFORE => ID */
121014    27,  /*         BY => ID */
121015    27,  /*    CASCADE => ID */
121016    27,  /*       CAST => ID */
121017    27,  /*   COLUMNKW => ID */
121018    27,  /*   CONFLICT => ID */
121019    27,  /*   DATABASE => ID */
121020    27,  /*       DESC => ID */
121021    27,  /*     DETACH => ID */
121022    27,  /*       EACH => ID */
121023    27,  /*       FAIL => ID */
121024    27,  /*        FOR => ID */
121025    27,  /*     IGNORE => ID */
121026    27,  /*  INITIALLY => ID */
121027    27,  /*    INSTEAD => ID */
121028    27,  /*    LIKE_KW => ID */
121029    27,  /*      MATCH => ID */
121030    27,  /*         NO => ID */
121031    27,  /*        KEY => ID */
121032    27,  /*         OF => ID */
121033    27,  /*     OFFSET => ID */
121034    27,  /*     PRAGMA => ID */
121035    27,  /*      RAISE => ID */
121036    27,  /*  RECURSIVE => ID */
121037    27,  /*    REPLACE => ID */
121038    27,  /*   RESTRICT => ID */
121039    27,  /*        ROW => ID */
121040    27,  /*    TRIGGER => ID */
121041    27,  /*     VACUUM => ID */
121042    27,  /*       VIEW => ID */
121043    27,  /*    VIRTUAL => ID */
121044    27,  /*       WITH => ID */
121045    27,  /*    REINDEX => ID */
121046    27,  /*     RENAME => ID */
121047    27,  /*   CTIME_KW => ID */
121048 };
121049 #endif /* YYFALLBACK */
121050 
121051 /* The following structure represents a single element of the
121052 ** parser's stack.  Information stored includes:
121053 **
121054 **   +  The state number for the parser at this level of the stack.
121055 **
121056 **   +  The value of the token stored at this level of the stack.
121057 **      (In other words, the "major" token.)
121058 **
121059 **   +  The semantic value stored at this level of the stack.  This is
121060 **      the information used by the action routines in the grammar.
121061 **      It is sometimes called the "minor" token.
121062 */
121063 struct yyStackEntry {
121064   YYACTIONTYPE stateno;  /* The state-number */
121065   YYCODETYPE major;      /* The major token value.  This is the code
121066                          ** number for the token at this stack level */
121067   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
121068                          ** is the value of the token  */
121069 };
121070 typedef struct yyStackEntry yyStackEntry;
121071 
121072 /* The state of the parser is completely contained in an instance of
121073 ** the following structure */
121074 struct yyParser {
121075   int yyidx;                    /* Index of top element in stack */
121076 #ifdef YYTRACKMAXSTACKDEPTH
121077   int yyidxMax;                 /* Maximum value of yyidx */
121078 #endif
121079   int yyerrcnt;                 /* Shifts left before out of the error */
121080   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
121081 #if YYSTACKDEPTH<=0
121082   int yystksz;                  /* Current side of the stack */
121083   yyStackEntry *yystack;        /* The parser's stack */
121084 #else
121085   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
121086 #endif
121087 };
121088 typedef struct yyParser yyParser;
121089 
121090 #ifndef NDEBUG
121091 /* #include <stdio.h> */
121092 static FILE *yyTraceFILE = 0;
121093 static char *yyTracePrompt = 0;
121094 #endif /* NDEBUG */
121095 
121096 #ifndef NDEBUG
121097 /*
121098 ** Turn parser tracing on by giving a stream to which to write the trace
121099 ** and a prompt to preface each trace message.  Tracing is turned off
121100 ** by making either argument NULL
121101 **
121102 ** Inputs:
121103 ** <ul>
121104 ** <li> A FILE* to which trace output should be written.
121105 **      If NULL, then tracing is turned off.
121106 ** <li> A prefix string written at the beginning of every
121107 **      line of trace output.  If NULL, then tracing is
121108 **      turned off.
121109 ** </ul>
121110 **
121111 ** Outputs:
121112 ** None.
121113 */
121114 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
121115   yyTraceFILE = TraceFILE;
121116   yyTracePrompt = zTracePrompt;
121117   if( yyTraceFILE==0 ) yyTracePrompt = 0;
121118   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
121119 }
121120 #endif /* NDEBUG */
121121 
121122 #ifndef NDEBUG
121123 /* For tracing shifts, the names of all terminals and nonterminals
121124 ** are required.  The following table supplies these names */
121125 static const char *const yyTokenName[] = {
121126   "$",             "SEMI",          "EXPLAIN",       "QUERY",
121127   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
121128   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
121129   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
121130   "TABLE",         "CREATE",        "IF",            "NOT",
121131   "EXISTS",        "TEMP",          "LP",            "RP",
121132   "AS",            "WITHOUT",       "COMMA",         "ID",
121133   "INDEXED",       "ABORT",         "ACTION",        "AFTER",
121134   "ANALYZE",       "ASC",           "ATTACH",        "BEFORE",
121135   "BY",            "CASCADE",       "CAST",          "COLUMNKW",
121136   "CONFLICT",      "DATABASE",      "DESC",          "DETACH",
121137   "EACH",          "FAIL",          "FOR",           "IGNORE",
121138   "INITIALLY",     "INSTEAD",       "LIKE_KW",       "MATCH",
121139   "NO",            "KEY",           "OF",            "OFFSET",
121140   "PRAGMA",        "RAISE",         "RECURSIVE",     "REPLACE",
121141   "RESTRICT",      "ROW",           "TRIGGER",       "VACUUM",
121142   "VIEW",          "VIRTUAL",       "WITH",          "REINDEX",
121143   "RENAME",        "CTIME_KW",      "ANY",           "OR",
121144   "AND",           "IS",            "BETWEEN",       "IN",
121145   "ISNULL",        "NOTNULL",       "NE",            "EQ",
121146   "GT",            "LE",            "LT",            "GE",
121147   "ESCAPE",        "BITAND",        "BITOR",         "LSHIFT",
121148   "RSHIFT",        "PLUS",          "MINUS",         "STAR",
121149   "SLASH",         "REM",           "CONCAT",        "COLLATE",
121150   "BITNOT",        "STRING",        "JOIN_KW",       "CONSTRAINT",
121151   "DEFAULT",       "NULL",          "PRIMARY",       "UNIQUE",
121152   "CHECK",         "REFERENCES",    "AUTOINCR",      "ON",
121153   "INSERT",        "DELETE",        "UPDATE",        "SET",
121154   "DEFERRABLE",    "FOREIGN",       "DROP",          "UNION",
121155   "ALL",           "EXCEPT",        "INTERSECT",     "SELECT",
121156   "VALUES",        "DISTINCT",      "DOT",           "FROM",
121157   "JOIN",          "USING",         "ORDER",         "GROUP",
121158   "HAVING",        "LIMIT",         "WHERE",         "INTO",
121159   "INTEGER",       "FLOAT",         "BLOB",          "VARIABLE",
121160   "CASE",          "WHEN",          "THEN",          "ELSE",
121161   "INDEX",         "ALTER",         "ADD",           "error",
121162   "input",         "cmdlist",       "ecmd",          "explain",
121163   "cmdx",          "cmd",           "transtype",     "trans_opt",
121164   "nm",            "savepoint_opt",  "create_table",  "create_table_args",
121165   "createkw",      "temp",          "ifnotexists",   "dbnm",
121166   "columnlist",    "conslist_opt",  "table_options",  "select",
121167   "column",        "columnid",      "type",          "carglist",
121168   "typetoken",     "typename",      "signed",        "plus_num",
121169   "minus_num",     "ccons",         "term",          "expr",
121170   "onconf",        "sortorder",     "autoinc",       "idxlist_opt",
121171   "refargs",       "defer_subclause",  "refarg",        "refact",
121172   "init_deferred_pred_opt",  "conslist",      "tconscomma",    "tcons",
121173   "idxlist",       "defer_subclause_opt",  "orconf",        "resolvetype",
121174   "raisetype",     "ifexists",      "fullname",      "selectnowith",
121175   "oneselect",     "with",          "multiselect_op",  "distinct",
121176   "selcollist",    "from",          "where_opt",     "groupby_opt",
121177   "having_opt",    "orderby_opt",   "limit_opt",     "values",
121178   "nexprlist",     "exprlist",      "sclp",          "as",
121179   "seltablist",    "stl_prefix",    "joinop",        "indexed_opt",
121180   "on_opt",        "using_opt",     "joinop2",       "idlist",
121181   "sortlist",      "setlist",       "insert_cmd",    "inscollist_opt",
121182   "likeop",        "between_op",    "in_op",         "case_operand",
121183   "case_exprlist",  "case_else",     "uniqueflag",    "collate",
121184   "nmnum",         "trigger_decl",  "trigger_cmd_list",  "trigger_time",
121185   "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd",
121186   "trnm",          "tridxby",       "database_kw_opt",  "key_opt",
121187   "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist",
121188   "vtabarg",       "vtabargtoken",  "lp",            "anylist",
121189   "wqlist",
121190 };
121191 #endif /* NDEBUG */
121192 
121193 #ifndef NDEBUG
121194 /* For tracing reduce actions, the names of all rules are required.
121195 */
121196 static const char *const yyRuleName[] = {
121197  /*   0 */ "input ::= cmdlist",
121198  /*   1 */ "cmdlist ::= cmdlist ecmd",
121199  /*   2 */ "cmdlist ::= ecmd",
121200  /*   3 */ "ecmd ::= SEMI",
121201  /*   4 */ "ecmd ::= explain cmdx SEMI",
121202  /*   5 */ "explain ::=",
121203  /*   6 */ "explain ::= EXPLAIN",
121204  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
121205  /*   8 */ "cmdx ::= cmd",
121206  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
121207  /*  10 */ "trans_opt ::=",
121208  /*  11 */ "trans_opt ::= TRANSACTION",
121209  /*  12 */ "trans_opt ::= TRANSACTION nm",
121210  /*  13 */ "transtype ::=",
121211  /*  14 */ "transtype ::= DEFERRED",
121212  /*  15 */ "transtype ::= IMMEDIATE",
121213  /*  16 */ "transtype ::= EXCLUSIVE",
121214  /*  17 */ "cmd ::= COMMIT trans_opt",
121215  /*  18 */ "cmd ::= END trans_opt",
121216  /*  19 */ "cmd ::= ROLLBACK trans_opt",
121217  /*  20 */ "savepoint_opt ::= SAVEPOINT",
121218  /*  21 */ "savepoint_opt ::=",
121219  /*  22 */ "cmd ::= SAVEPOINT nm",
121220  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
121221  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
121222  /*  25 */ "cmd ::= create_table create_table_args",
121223  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
121224  /*  27 */ "createkw ::= CREATE",
121225  /*  28 */ "ifnotexists ::=",
121226  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
121227  /*  30 */ "temp ::= TEMP",
121228  /*  31 */ "temp ::=",
121229  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
121230  /*  33 */ "create_table_args ::= AS select",
121231  /*  34 */ "table_options ::=",
121232  /*  35 */ "table_options ::= WITHOUT nm",
121233  /*  36 */ "columnlist ::= columnlist COMMA column",
121234  /*  37 */ "columnlist ::= column",
121235  /*  38 */ "column ::= columnid type carglist",
121236  /*  39 */ "columnid ::= nm",
121237  /*  40 */ "nm ::= ID|INDEXED",
121238  /*  41 */ "nm ::= STRING",
121239  /*  42 */ "nm ::= JOIN_KW",
121240  /*  43 */ "type ::=",
121241  /*  44 */ "type ::= typetoken",
121242  /*  45 */ "typetoken ::= typename",
121243  /*  46 */ "typetoken ::= typename LP signed RP",
121244  /*  47 */ "typetoken ::= typename LP signed COMMA signed RP",
121245  /*  48 */ "typename ::= ID|STRING",
121246  /*  49 */ "typename ::= typename ID|STRING",
121247  /*  50 */ "signed ::= plus_num",
121248  /*  51 */ "signed ::= minus_num",
121249  /*  52 */ "carglist ::= carglist ccons",
121250  /*  53 */ "carglist ::=",
121251  /*  54 */ "ccons ::= CONSTRAINT nm",
121252  /*  55 */ "ccons ::= DEFAULT term",
121253  /*  56 */ "ccons ::= DEFAULT LP expr RP",
121254  /*  57 */ "ccons ::= DEFAULT PLUS term",
121255  /*  58 */ "ccons ::= DEFAULT MINUS term",
121256  /*  59 */ "ccons ::= DEFAULT ID|INDEXED",
121257  /*  60 */ "ccons ::= NULL onconf",
121258  /*  61 */ "ccons ::= NOT NULL onconf",
121259  /*  62 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
121260  /*  63 */ "ccons ::= UNIQUE onconf",
121261  /*  64 */ "ccons ::= CHECK LP expr RP",
121262  /*  65 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
121263  /*  66 */ "ccons ::= defer_subclause",
121264  /*  67 */ "ccons ::= COLLATE ID|STRING",
121265  /*  68 */ "autoinc ::=",
121266  /*  69 */ "autoinc ::= AUTOINCR",
121267  /*  70 */ "refargs ::=",
121268  /*  71 */ "refargs ::= refargs refarg",
121269  /*  72 */ "refarg ::= MATCH nm",
121270  /*  73 */ "refarg ::= ON INSERT refact",
121271  /*  74 */ "refarg ::= ON DELETE refact",
121272  /*  75 */ "refarg ::= ON UPDATE refact",
121273  /*  76 */ "refact ::= SET NULL",
121274  /*  77 */ "refact ::= SET DEFAULT",
121275  /*  78 */ "refact ::= CASCADE",
121276  /*  79 */ "refact ::= RESTRICT",
121277  /*  80 */ "refact ::= NO ACTION",
121278  /*  81 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
121279  /*  82 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
121280  /*  83 */ "init_deferred_pred_opt ::=",
121281  /*  84 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
121282  /*  85 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
121283  /*  86 */ "conslist_opt ::=",
121284  /*  87 */ "conslist_opt ::= COMMA conslist",
121285  /*  88 */ "conslist ::= conslist tconscomma tcons",
121286  /*  89 */ "conslist ::= tcons",
121287  /*  90 */ "tconscomma ::= COMMA",
121288  /*  91 */ "tconscomma ::=",
121289  /*  92 */ "tcons ::= CONSTRAINT nm",
121290  /*  93 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
121291  /*  94 */ "tcons ::= UNIQUE LP idxlist RP onconf",
121292  /*  95 */ "tcons ::= CHECK LP expr RP onconf",
121293  /*  96 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
121294  /*  97 */ "defer_subclause_opt ::=",
121295  /*  98 */ "defer_subclause_opt ::= defer_subclause",
121296  /*  99 */ "onconf ::=",
121297  /* 100 */ "onconf ::= ON CONFLICT resolvetype",
121298  /* 101 */ "orconf ::=",
121299  /* 102 */ "orconf ::= OR resolvetype",
121300  /* 103 */ "resolvetype ::= raisetype",
121301  /* 104 */ "resolvetype ::= IGNORE",
121302  /* 105 */ "resolvetype ::= REPLACE",
121303  /* 106 */ "cmd ::= DROP TABLE ifexists fullname",
121304  /* 107 */ "ifexists ::= IF EXISTS",
121305  /* 108 */ "ifexists ::=",
121306  /* 109 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
121307  /* 110 */ "cmd ::= DROP VIEW ifexists fullname",
121308  /* 111 */ "cmd ::= select",
121309  /* 112 */ "select ::= with selectnowith",
121310  /* 113 */ "selectnowith ::= oneselect",
121311  /* 114 */ "selectnowith ::= selectnowith multiselect_op oneselect",
121312  /* 115 */ "multiselect_op ::= UNION",
121313  /* 116 */ "multiselect_op ::= UNION ALL",
121314  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
121315  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
121316  /* 119 */ "oneselect ::= values",
121317  /* 120 */ "values ::= VALUES LP nexprlist RP",
121318  /* 121 */ "values ::= values COMMA LP exprlist RP",
121319  /* 122 */ "distinct ::= DISTINCT",
121320  /* 123 */ "distinct ::= ALL",
121321  /* 124 */ "distinct ::=",
121322  /* 125 */ "sclp ::= selcollist COMMA",
121323  /* 126 */ "sclp ::=",
121324  /* 127 */ "selcollist ::= sclp expr as",
121325  /* 128 */ "selcollist ::= sclp STAR",
121326  /* 129 */ "selcollist ::= sclp nm DOT STAR",
121327  /* 130 */ "as ::= AS nm",
121328  /* 131 */ "as ::= ID|STRING",
121329  /* 132 */ "as ::=",
121330  /* 133 */ "from ::=",
121331  /* 134 */ "from ::= FROM seltablist",
121332  /* 135 */ "stl_prefix ::= seltablist joinop",
121333  /* 136 */ "stl_prefix ::=",
121334  /* 137 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
121335  /* 138 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
121336  /* 139 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
121337  /* 140 */ "dbnm ::=",
121338  /* 141 */ "dbnm ::= DOT nm",
121339  /* 142 */ "fullname ::= nm dbnm",
121340  /* 143 */ "joinop ::= COMMA|JOIN",
121341  /* 144 */ "joinop ::= JOIN_KW JOIN",
121342  /* 145 */ "joinop ::= JOIN_KW nm JOIN",
121343  /* 146 */ "joinop ::= JOIN_KW nm nm JOIN",
121344  /* 147 */ "on_opt ::= ON expr",
121345  /* 148 */ "on_opt ::=",
121346  /* 149 */ "indexed_opt ::=",
121347  /* 150 */ "indexed_opt ::= INDEXED BY nm",
121348  /* 151 */ "indexed_opt ::= NOT INDEXED",
121349  /* 152 */ "using_opt ::= USING LP idlist RP",
121350  /* 153 */ "using_opt ::=",
121351  /* 154 */ "orderby_opt ::=",
121352  /* 155 */ "orderby_opt ::= ORDER BY sortlist",
121353  /* 156 */ "sortlist ::= sortlist COMMA expr sortorder",
121354  /* 157 */ "sortlist ::= expr sortorder",
121355  /* 158 */ "sortorder ::= ASC",
121356  /* 159 */ "sortorder ::= DESC",
121357  /* 160 */ "sortorder ::=",
121358  /* 161 */ "groupby_opt ::=",
121359  /* 162 */ "groupby_opt ::= GROUP BY nexprlist",
121360  /* 163 */ "having_opt ::=",
121361  /* 164 */ "having_opt ::= HAVING expr",
121362  /* 165 */ "limit_opt ::=",
121363  /* 166 */ "limit_opt ::= LIMIT expr",
121364  /* 167 */ "limit_opt ::= LIMIT expr OFFSET expr",
121365  /* 168 */ "limit_opt ::= LIMIT expr COMMA expr",
121366  /* 169 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
121367  /* 170 */ "where_opt ::=",
121368  /* 171 */ "where_opt ::= WHERE expr",
121369  /* 172 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
121370  /* 173 */ "setlist ::= setlist COMMA nm EQ expr",
121371  /* 174 */ "setlist ::= nm EQ expr",
121372  /* 175 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt select",
121373  /* 176 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
121374  /* 177 */ "insert_cmd ::= INSERT orconf",
121375  /* 178 */ "insert_cmd ::= REPLACE",
121376  /* 179 */ "inscollist_opt ::=",
121377  /* 180 */ "inscollist_opt ::= LP idlist RP",
121378  /* 181 */ "idlist ::= idlist COMMA nm",
121379  /* 182 */ "idlist ::= nm",
121380  /* 183 */ "expr ::= term",
121381  /* 184 */ "expr ::= LP expr RP",
121382  /* 185 */ "term ::= NULL",
121383  /* 186 */ "expr ::= ID|INDEXED",
121384  /* 187 */ "expr ::= JOIN_KW",
121385  /* 188 */ "expr ::= nm DOT nm",
121386  /* 189 */ "expr ::= nm DOT nm DOT nm",
121387  /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
121388  /* 191 */ "term ::= STRING",
121389  /* 192 */ "expr ::= VARIABLE",
121390  /* 193 */ "expr ::= expr COLLATE ID|STRING",
121391  /* 194 */ "expr ::= CAST LP expr AS typetoken RP",
121392  /* 195 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
121393  /* 196 */ "expr ::= ID|INDEXED LP STAR RP",
121394  /* 197 */ "term ::= CTIME_KW",
121395  /* 198 */ "expr ::= expr AND expr",
121396  /* 199 */ "expr ::= expr OR expr",
121397  /* 200 */ "expr ::= expr LT|GT|GE|LE expr",
121398  /* 201 */ "expr ::= expr EQ|NE expr",
121399  /* 202 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
121400  /* 203 */ "expr ::= expr PLUS|MINUS expr",
121401  /* 204 */ "expr ::= expr STAR|SLASH|REM expr",
121402  /* 205 */ "expr ::= expr CONCAT expr",
121403  /* 206 */ "likeop ::= LIKE_KW|MATCH",
121404  /* 207 */ "likeop ::= NOT LIKE_KW|MATCH",
121405  /* 208 */ "expr ::= expr likeop expr",
121406  /* 209 */ "expr ::= expr likeop expr ESCAPE expr",
121407  /* 210 */ "expr ::= expr ISNULL|NOTNULL",
121408  /* 211 */ "expr ::= expr NOT NULL",
121409  /* 212 */ "expr ::= expr IS expr",
121410  /* 213 */ "expr ::= expr IS NOT expr",
121411  /* 214 */ "expr ::= NOT expr",
121412  /* 215 */ "expr ::= BITNOT expr",
121413  /* 216 */ "expr ::= MINUS expr",
121414  /* 217 */ "expr ::= PLUS expr",
121415  /* 218 */ "between_op ::= BETWEEN",
121416  /* 219 */ "between_op ::= NOT BETWEEN",
121417  /* 220 */ "expr ::= expr between_op expr AND expr",
121418  /* 221 */ "in_op ::= IN",
121419  /* 222 */ "in_op ::= NOT IN",
121420  /* 223 */ "expr ::= expr in_op LP exprlist RP",
121421  /* 224 */ "expr ::= LP select RP",
121422  /* 225 */ "expr ::= expr in_op LP select RP",
121423  /* 226 */ "expr ::= expr in_op nm dbnm",
121424  /* 227 */ "expr ::= EXISTS LP select RP",
121425  /* 228 */ "expr ::= CASE case_operand case_exprlist case_else END",
121426  /* 229 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
121427  /* 230 */ "case_exprlist ::= WHEN expr THEN expr",
121428  /* 231 */ "case_else ::= ELSE expr",
121429  /* 232 */ "case_else ::=",
121430  /* 233 */ "case_operand ::= expr",
121431  /* 234 */ "case_operand ::=",
121432  /* 235 */ "exprlist ::= nexprlist",
121433  /* 236 */ "exprlist ::=",
121434  /* 237 */ "nexprlist ::= nexprlist COMMA expr",
121435  /* 238 */ "nexprlist ::= expr",
121436  /* 239 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt",
121437  /* 240 */ "uniqueflag ::= UNIQUE",
121438  /* 241 */ "uniqueflag ::=",
121439  /* 242 */ "idxlist_opt ::=",
121440  /* 243 */ "idxlist_opt ::= LP idxlist RP",
121441  /* 244 */ "idxlist ::= idxlist COMMA nm collate sortorder",
121442  /* 245 */ "idxlist ::= nm collate sortorder",
121443  /* 246 */ "collate ::=",
121444  /* 247 */ "collate ::= COLLATE ID|STRING",
121445  /* 248 */ "cmd ::= DROP INDEX ifexists fullname",
121446  /* 249 */ "cmd ::= VACUUM",
121447  /* 250 */ "cmd ::= VACUUM nm",
121448  /* 251 */ "cmd ::= PRAGMA nm dbnm",
121449  /* 252 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
121450  /* 253 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
121451  /* 254 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
121452  /* 255 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
121453  /* 256 */ "nmnum ::= plus_num",
121454  /* 257 */ "nmnum ::= nm",
121455  /* 258 */ "nmnum ::= ON",
121456  /* 259 */ "nmnum ::= DELETE",
121457  /* 260 */ "nmnum ::= DEFAULT",
121458  /* 261 */ "plus_num ::= PLUS INTEGER|FLOAT",
121459  /* 262 */ "plus_num ::= INTEGER|FLOAT",
121460  /* 263 */ "minus_num ::= MINUS INTEGER|FLOAT",
121461  /* 264 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
121462  /* 265 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
121463  /* 266 */ "trigger_time ::= BEFORE",
121464  /* 267 */ "trigger_time ::= AFTER",
121465  /* 268 */ "trigger_time ::= INSTEAD OF",
121466  /* 269 */ "trigger_time ::=",
121467  /* 270 */ "trigger_event ::= DELETE|INSERT",
121468  /* 271 */ "trigger_event ::= UPDATE",
121469  /* 272 */ "trigger_event ::= UPDATE OF idlist",
121470  /* 273 */ "foreach_clause ::=",
121471  /* 274 */ "foreach_clause ::= FOR EACH ROW",
121472  /* 275 */ "when_clause ::=",
121473  /* 276 */ "when_clause ::= WHEN expr",
121474  /* 277 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
121475  /* 278 */ "trigger_cmd_list ::= trigger_cmd SEMI",
121476  /* 279 */ "trnm ::= nm",
121477  /* 280 */ "trnm ::= nm DOT nm",
121478  /* 281 */ "tridxby ::=",
121479  /* 282 */ "tridxby ::= INDEXED BY nm",
121480  /* 283 */ "tridxby ::= NOT INDEXED",
121481  /* 284 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
121482  /* 285 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
121483  /* 286 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
121484  /* 287 */ "trigger_cmd ::= select",
121485  /* 288 */ "expr ::= RAISE LP IGNORE RP",
121486  /* 289 */ "expr ::= RAISE LP raisetype COMMA nm RP",
121487  /* 290 */ "raisetype ::= ROLLBACK",
121488  /* 291 */ "raisetype ::= ABORT",
121489  /* 292 */ "raisetype ::= FAIL",
121490  /* 293 */ "cmd ::= DROP TRIGGER ifexists fullname",
121491  /* 294 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
121492  /* 295 */ "cmd ::= DETACH database_kw_opt expr",
121493  /* 296 */ "key_opt ::=",
121494  /* 297 */ "key_opt ::= KEY expr",
121495  /* 298 */ "database_kw_opt ::= DATABASE",
121496  /* 299 */ "database_kw_opt ::=",
121497  /* 300 */ "cmd ::= REINDEX",
121498  /* 301 */ "cmd ::= REINDEX nm dbnm",
121499  /* 302 */ "cmd ::= ANALYZE",
121500  /* 303 */ "cmd ::= ANALYZE nm dbnm",
121501  /* 304 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
121502  /* 305 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
121503  /* 306 */ "add_column_fullname ::= fullname",
121504  /* 307 */ "kwcolumn_opt ::=",
121505  /* 308 */ "kwcolumn_opt ::= COLUMNKW",
121506  /* 309 */ "cmd ::= create_vtab",
121507  /* 310 */ "cmd ::= create_vtab LP vtabarglist RP",
121508  /* 311 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
121509  /* 312 */ "vtabarglist ::= vtabarg",
121510  /* 313 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
121511  /* 314 */ "vtabarg ::=",
121512  /* 315 */ "vtabarg ::= vtabarg vtabargtoken",
121513  /* 316 */ "vtabargtoken ::= ANY",
121514  /* 317 */ "vtabargtoken ::= lp anylist RP",
121515  /* 318 */ "lp ::= LP",
121516  /* 319 */ "anylist ::=",
121517  /* 320 */ "anylist ::= anylist LP anylist RP",
121518  /* 321 */ "anylist ::= anylist ANY",
121519  /* 322 */ "with ::=",
121520  /* 323 */ "with ::= WITH wqlist",
121521  /* 324 */ "with ::= WITH RECURSIVE wqlist",
121522  /* 325 */ "wqlist ::= nm idxlist_opt AS LP select RP",
121523  /* 326 */ "wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP",
121524 };
121525 #endif /* NDEBUG */
121526 
121527 
121528 #if YYSTACKDEPTH<=0
121529 /*
121530 ** Try to increase the size of the parser stack.
121531 */
121532 static void yyGrowStack(yyParser *p){
121533   int newSize;
121534   yyStackEntry *pNew;
121535 
121536   newSize = p->yystksz*2 + 100;
121537   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
121538   if( pNew ){
121539     p->yystack = pNew;
121540     p->yystksz = newSize;
121541 #ifndef NDEBUG
121542     if( yyTraceFILE ){
121543       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
121544               yyTracePrompt, p->yystksz);
121545     }
121546 #endif
121547   }
121548 }
121549 #endif
121550 
121551 /*
121552 ** This function allocates a new parser.
121553 ** The only argument is a pointer to a function which works like
121554 ** malloc.
121555 **
121556 ** Inputs:
121557 ** A pointer to the function used to allocate memory.
121558 **
121559 ** Outputs:
121560 ** A pointer to a parser.  This pointer is used in subsequent calls
121561 ** to sqlite3Parser and sqlite3ParserFree.
121562 */
121563 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(u64)){
121564   yyParser *pParser;
121565   pParser = (yyParser*)(*mallocProc)( (u64)sizeof(yyParser) );
121566   if( pParser ){
121567     pParser->yyidx = -1;
121568 #ifdef YYTRACKMAXSTACKDEPTH
121569     pParser->yyidxMax = 0;
121570 #endif
121571 #if YYSTACKDEPTH<=0
121572     pParser->yystack = NULL;
121573     pParser->yystksz = 0;
121574     yyGrowStack(pParser);
121575 #endif
121576   }
121577   return pParser;
121578 }
121579 
121580 /* The following function deletes the value associated with a
121581 ** symbol.  The symbol can be either a terminal or nonterminal.
121582 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
121583 ** the value.
121584 */
121585 static void yy_destructor(
121586   yyParser *yypParser,    /* The parser */
121587   YYCODETYPE yymajor,     /* Type code for object to destroy */
121588   YYMINORTYPE *yypminor   /* The object to be destroyed */
121589 ){
121590   sqlite3ParserARG_FETCH;
121591   switch( yymajor ){
121592     /* Here is inserted the actions which take place when a
121593     ** terminal or non-terminal is destroyed.  This can happen
121594     ** when the symbol is popped from the stack during a
121595     ** reduce or during error processing or when a parser is
121596     ** being destroyed before it is finished parsing.
121597     **
121598     ** Note: during a reduce, the only symbols destroyed are those
121599     ** which appear on the RHS of the rule, but which are not used
121600     ** inside the C code.
121601     */
121602     case 163: /* select */
121603     case 195: /* selectnowith */
121604     case 196: /* oneselect */
121605     case 207: /* values */
121606 {
121607 sqlite3SelectDelete(pParse->db, (yypminor->yy3));
121608 }
121609       break;
121610     case 174: /* term */
121611     case 175: /* expr */
121612 {
121613 sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
121614 }
121615       break;
121616     case 179: /* idxlist_opt */
121617     case 188: /* idxlist */
121618     case 200: /* selcollist */
121619     case 203: /* groupby_opt */
121620     case 205: /* orderby_opt */
121621     case 208: /* nexprlist */
121622     case 209: /* exprlist */
121623     case 210: /* sclp */
121624     case 220: /* sortlist */
121625     case 221: /* setlist */
121626     case 228: /* case_exprlist */
121627 {
121628 sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
121629 }
121630       break;
121631     case 194: /* fullname */
121632     case 201: /* from */
121633     case 212: /* seltablist */
121634     case 213: /* stl_prefix */
121635 {
121636 sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
121637 }
121638       break;
121639     case 197: /* with */
121640     case 252: /* wqlist */
121641 {
121642 sqlite3WithDelete(pParse->db, (yypminor->yy59));
121643 }
121644       break;
121645     case 202: /* where_opt */
121646     case 204: /* having_opt */
121647     case 216: /* on_opt */
121648     case 227: /* case_operand */
121649     case 229: /* case_else */
121650     case 238: /* when_clause */
121651     case 243: /* key_opt */
121652 {
121653 sqlite3ExprDelete(pParse->db, (yypminor->yy132));
121654 }
121655       break;
121656     case 217: /* using_opt */
121657     case 219: /* idlist */
121658     case 223: /* inscollist_opt */
121659 {
121660 sqlite3IdListDelete(pParse->db, (yypminor->yy408));
121661 }
121662       break;
121663     case 234: /* trigger_cmd_list */
121664     case 239: /* trigger_cmd */
121665 {
121666 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
121667 }
121668       break;
121669     case 236: /* trigger_event */
121670 {
121671 sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
121672 }
121673       break;
121674     default:  break;   /* If no destructor action specified: do nothing */
121675   }
121676 }
121677 
121678 /*
121679 ** Pop the parser's stack once.
121680 **
121681 ** If there is a destructor routine associated with the token which
121682 ** is popped from the stack, then call it.
121683 **
121684 ** Return the major token number for the symbol popped.
121685 */
121686 static int yy_pop_parser_stack(yyParser *pParser){
121687   YYCODETYPE yymajor;
121688   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
121689 
121690   /* There is no mechanism by which the parser stack can be popped below
121691   ** empty in SQLite.  */
121692   if( NEVER(pParser->yyidx<0) ) return 0;
121693 #ifndef NDEBUG
121694   if( yyTraceFILE && pParser->yyidx>=0 ){
121695     fprintf(yyTraceFILE,"%sPopping %s\n",
121696       yyTracePrompt,
121697       yyTokenName[yytos->major]);
121698   }
121699 #endif
121700   yymajor = yytos->major;
121701   yy_destructor(pParser, yymajor, &yytos->minor);
121702   pParser->yyidx--;
121703   return yymajor;
121704 }
121705 
121706 /*
121707 ** Deallocate and destroy a parser.  Destructors are all called for
121708 ** all stack elements before shutting the parser down.
121709 **
121710 ** Inputs:
121711 ** <ul>
121712 ** <li>  A pointer to the parser.  This should be a pointer
121713 **       obtained from sqlite3ParserAlloc.
121714 ** <li>  A pointer to a function used to reclaim memory obtained
121715 **       from malloc.
121716 ** </ul>
121717 */
121718 SQLITE_PRIVATE void sqlite3ParserFree(
121719   void *p,                    /* The parser to be deleted */
121720   void (*freeProc)(void*)     /* Function used to reclaim memory */
121721 ){
121722   yyParser *pParser = (yyParser*)p;
121723   /* In SQLite, we never try to destroy a parser that was not successfully
121724   ** created in the first place. */
121725   if( NEVER(pParser==0) ) return;
121726   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
121727 #if YYSTACKDEPTH<=0
121728   free(pParser->yystack);
121729 #endif
121730   (*freeProc)((void*)pParser);
121731 }
121732 
121733 /*
121734 ** Return the peak depth of the stack for a parser.
121735 */
121736 #ifdef YYTRACKMAXSTACKDEPTH
121737 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
121738   yyParser *pParser = (yyParser*)p;
121739   return pParser->yyidxMax;
121740 }
121741 #endif
121742 
121743 /*
121744 ** Find the appropriate action for a parser given the terminal
121745 ** look-ahead token iLookAhead.
121746 **
121747 ** If the look-ahead token is YYNOCODE, then check to see if the action is
121748 ** independent of the look-ahead.  If it is, return the action, otherwise
121749 ** return YY_NO_ACTION.
121750 */
121751 static int yy_find_shift_action(
121752   yyParser *pParser,        /* The parser */
121753   YYCODETYPE iLookAhead     /* The look-ahead token */
121754 ){
121755   int i;
121756   int stateno = pParser->yystack[pParser->yyidx].stateno;
121757 
121758   if( stateno>YY_SHIFT_COUNT
121759    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
121760     return yy_default[stateno];
121761   }
121762   assert( iLookAhead!=YYNOCODE );
121763   i += iLookAhead;
121764   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
121765     if( iLookAhead>0 ){
121766 #ifdef YYFALLBACK
121767       YYCODETYPE iFallback;            /* Fallback token */
121768       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
121769              && (iFallback = yyFallback[iLookAhead])!=0 ){
121770 #ifndef NDEBUG
121771         if( yyTraceFILE ){
121772           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
121773              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
121774         }
121775 #endif
121776         return yy_find_shift_action(pParser, iFallback);
121777       }
121778 #endif
121779 #ifdef YYWILDCARD
121780       {
121781         int j = i - iLookAhead + YYWILDCARD;
121782         if(
121783 #if YY_SHIFT_MIN+YYWILDCARD<0
121784           j>=0 &&
121785 #endif
121786 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
121787           j<YY_ACTTAB_COUNT &&
121788 #endif
121789           yy_lookahead[j]==YYWILDCARD
121790         ){
121791 #ifndef NDEBUG
121792           if( yyTraceFILE ){
121793             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
121794                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
121795           }
121796 #endif /* NDEBUG */
121797           return yy_action[j];
121798         }
121799       }
121800 #endif /* YYWILDCARD */
121801     }
121802     return yy_default[stateno];
121803   }else{
121804     return yy_action[i];
121805   }
121806 }
121807 
121808 /*
121809 ** Find the appropriate action for a parser given the non-terminal
121810 ** look-ahead token iLookAhead.
121811 **
121812 ** If the look-ahead token is YYNOCODE, then check to see if the action is
121813 ** independent of the look-ahead.  If it is, return the action, otherwise
121814 ** return YY_NO_ACTION.
121815 */
121816 static int yy_find_reduce_action(
121817   int stateno,              /* Current state number */
121818   YYCODETYPE iLookAhead     /* The look-ahead token */
121819 ){
121820   int i;
121821 #ifdef YYERRORSYMBOL
121822   if( stateno>YY_REDUCE_COUNT ){
121823     return yy_default[stateno];
121824   }
121825 #else
121826   assert( stateno<=YY_REDUCE_COUNT );
121827 #endif
121828   i = yy_reduce_ofst[stateno];
121829   assert( i!=YY_REDUCE_USE_DFLT );
121830   assert( iLookAhead!=YYNOCODE );
121831   i += iLookAhead;
121832 #ifdef YYERRORSYMBOL
121833   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
121834     return yy_default[stateno];
121835   }
121836 #else
121837   assert( i>=0 && i<YY_ACTTAB_COUNT );
121838   assert( yy_lookahead[i]==iLookAhead );
121839 #endif
121840   return yy_action[i];
121841 }
121842 
121843 /*
121844 ** The following routine is called if the stack overflows.
121845 */
121846 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
121847    sqlite3ParserARG_FETCH;
121848    yypParser->yyidx--;
121849 #ifndef NDEBUG
121850    if( yyTraceFILE ){
121851      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
121852    }
121853 #endif
121854    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
121855    /* Here code is inserted which will execute if the parser
121856    ** stack every overflows */
121857 
121858   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
121859   sqlite3ErrorMsg(pParse, "parser stack overflow");
121860    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
121861 }
121862 
121863 /*
121864 ** Perform a shift action.
121865 */
121866 static void yy_shift(
121867   yyParser *yypParser,          /* The parser to be shifted */
121868   int yyNewState,               /* The new state to shift in */
121869   int yyMajor,                  /* The major token to shift in */
121870   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
121871 ){
121872   yyStackEntry *yytos;
121873   yypParser->yyidx++;
121874 #ifdef YYTRACKMAXSTACKDEPTH
121875   if( yypParser->yyidx>yypParser->yyidxMax ){
121876     yypParser->yyidxMax = yypParser->yyidx;
121877   }
121878 #endif
121879 #if YYSTACKDEPTH>0
121880   if( yypParser->yyidx>=YYSTACKDEPTH ){
121881     yyStackOverflow(yypParser, yypMinor);
121882     return;
121883   }
121884 #else
121885   if( yypParser->yyidx>=yypParser->yystksz ){
121886     yyGrowStack(yypParser);
121887     if( yypParser->yyidx>=yypParser->yystksz ){
121888       yyStackOverflow(yypParser, yypMinor);
121889       return;
121890     }
121891   }
121892 #endif
121893   yytos = &yypParser->yystack[yypParser->yyidx];
121894   yytos->stateno = (YYACTIONTYPE)yyNewState;
121895   yytos->major = (YYCODETYPE)yyMajor;
121896   yytos->minor = *yypMinor;
121897 #ifndef NDEBUG
121898   if( yyTraceFILE && yypParser->yyidx>0 ){
121899     int i;
121900     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
121901     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
121902     for(i=1; i<=yypParser->yyidx; i++)
121903       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
121904     fprintf(yyTraceFILE,"\n");
121905   }
121906 #endif
121907 }
121908 
121909 /* The following table contains information about every rule that
121910 ** is used during the reduce.
121911 */
121912 static const struct {
121913   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
121914   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
121915 } yyRuleInfo[] = {
121916   { 144, 1 },
121917   { 145, 2 },
121918   { 145, 1 },
121919   { 146, 1 },
121920   { 146, 3 },
121921   { 147, 0 },
121922   { 147, 1 },
121923   { 147, 3 },
121924   { 148, 1 },
121925   { 149, 3 },
121926   { 151, 0 },
121927   { 151, 1 },
121928   { 151, 2 },
121929   { 150, 0 },
121930   { 150, 1 },
121931   { 150, 1 },
121932   { 150, 1 },
121933   { 149, 2 },
121934   { 149, 2 },
121935   { 149, 2 },
121936   { 153, 1 },
121937   { 153, 0 },
121938   { 149, 2 },
121939   { 149, 3 },
121940   { 149, 5 },
121941   { 149, 2 },
121942   { 154, 6 },
121943   { 156, 1 },
121944   { 158, 0 },
121945   { 158, 3 },
121946   { 157, 1 },
121947   { 157, 0 },
121948   { 155, 5 },
121949   { 155, 2 },
121950   { 162, 0 },
121951   { 162, 2 },
121952   { 160, 3 },
121953   { 160, 1 },
121954   { 164, 3 },
121955   { 165, 1 },
121956   { 152, 1 },
121957   { 152, 1 },
121958   { 152, 1 },
121959   { 166, 0 },
121960   { 166, 1 },
121961   { 168, 1 },
121962   { 168, 4 },
121963   { 168, 6 },
121964   { 169, 1 },
121965   { 169, 2 },
121966   { 170, 1 },
121967   { 170, 1 },
121968   { 167, 2 },
121969   { 167, 0 },
121970   { 173, 2 },
121971   { 173, 2 },
121972   { 173, 4 },
121973   { 173, 3 },
121974   { 173, 3 },
121975   { 173, 2 },
121976   { 173, 2 },
121977   { 173, 3 },
121978   { 173, 5 },
121979   { 173, 2 },
121980   { 173, 4 },
121981   { 173, 4 },
121982   { 173, 1 },
121983   { 173, 2 },
121984   { 178, 0 },
121985   { 178, 1 },
121986   { 180, 0 },
121987   { 180, 2 },
121988   { 182, 2 },
121989   { 182, 3 },
121990   { 182, 3 },
121991   { 182, 3 },
121992   { 183, 2 },
121993   { 183, 2 },
121994   { 183, 1 },
121995   { 183, 1 },
121996   { 183, 2 },
121997   { 181, 3 },
121998   { 181, 2 },
121999   { 184, 0 },
122000   { 184, 2 },
122001   { 184, 2 },
122002   { 161, 0 },
122003   { 161, 2 },
122004   { 185, 3 },
122005   { 185, 1 },
122006   { 186, 1 },
122007   { 186, 0 },
122008   { 187, 2 },
122009   { 187, 7 },
122010   { 187, 5 },
122011   { 187, 5 },
122012   { 187, 10 },
122013   { 189, 0 },
122014   { 189, 1 },
122015   { 176, 0 },
122016   { 176, 3 },
122017   { 190, 0 },
122018   { 190, 2 },
122019   { 191, 1 },
122020   { 191, 1 },
122021   { 191, 1 },
122022   { 149, 4 },
122023   { 193, 2 },
122024   { 193, 0 },
122025   { 149, 8 },
122026   { 149, 4 },
122027   { 149, 1 },
122028   { 163, 2 },
122029   { 195, 1 },
122030   { 195, 3 },
122031   { 198, 1 },
122032   { 198, 2 },
122033   { 198, 1 },
122034   { 196, 9 },
122035   { 196, 1 },
122036   { 207, 4 },
122037   { 207, 5 },
122038   { 199, 1 },
122039   { 199, 1 },
122040   { 199, 0 },
122041   { 210, 2 },
122042   { 210, 0 },
122043   { 200, 3 },
122044   { 200, 2 },
122045   { 200, 4 },
122046   { 211, 2 },
122047   { 211, 1 },
122048   { 211, 0 },
122049   { 201, 0 },
122050   { 201, 2 },
122051   { 213, 2 },
122052   { 213, 0 },
122053   { 212, 7 },
122054   { 212, 7 },
122055   { 212, 7 },
122056   { 159, 0 },
122057   { 159, 2 },
122058   { 194, 2 },
122059   { 214, 1 },
122060   { 214, 2 },
122061   { 214, 3 },
122062   { 214, 4 },
122063   { 216, 2 },
122064   { 216, 0 },
122065   { 215, 0 },
122066   { 215, 3 },
122067   { 215, 2 },
122068   { 217, 4 },
122069   { 217, 0 },
122070   { 205, 0 },
122071   { 205, 3 },
122072   { 220, 4 },
122073   { 220, 2 },
122074   { 177, 1 },
122075   { 177, 1 },
122076   { 177, 0 },
122077   { 203, 0 },
122078   { 203, 3 },
122079   { 204, 0 },
122080   { 204, 2 },
122081   { 206, 0 },
122082   { 206, 2 },
122083   { 206, 4 },
122084   { 206, 4 },
122085   { 149, 6 },
122086   { 202, 0 },
122087   { 202, 2 },
122088   { 149, 8 },
122089   { 221, 5 },
122090   { 221, 3 },
122091   { 149, 6 },
122092   { 149, 7 },
122093   { 222, 2 },
122094   { 222, 1 },
122095   { 223, 0 },
122096   { 223, 3 },
122097   { 219, 3 },
122098   { 219, 1 },
122099   { 175, 1 },
122100   { 175, 3 },
122101   { 174, 1 },
122102   { 175, 1 },
122103   { 175, 1 },
122104   { 175, 3 },
122105   { 175, 5 },
122106   { 174, 1 },
122107   { 174, 1 },
122108   { 175, 1 },
122109   { 175, 3 },
122110   { 175, 6 },
122111   { 175, 5 },
122112   { 175, 4 },
122113   { 174, 1 },
122114   { 175, 3 },
122115   { 175, 3 },
122116   { 175, 3 },
122117   { 175, 3 },
122118   { 175, 3 },
122119   { 175, 3 },
122120   { 175, 3 },
122121   { 175, 3 },
122122   { 224, 1 },
122123   { 224, 2 },
122124   { 175, 3 },
122125   { 175, 5 },
122126   { 175, 2 },
122127   { 175, 3 },
122128   { 175, 3 },
122129   { 175, 4 },
122130   { 175, 2 },
122131   { 175, 2 },
122132   { 175, 2 },
122133   { 175, 2 },
122134   { 225, 1 },
122135   { 225, 2 },
122136   { 175, 5 },
122137   { 226, 1 },
122138   { 226, 2 },
122139   { 175, 5 },
122140   { 175, 3 },
122141   { 175, 5 },
122142   { 175, 4 },
122143   { 175, 4 },
122144   { 175, 5 },
122145   { 228, 5 },
122146   { 228, 4 },
122147   { 229, 2 },
122148   { 229, 0 },
122149   { 227, 1 },
122150   { 227, 0 },
122151   { 209, 1 },
122152   { 209, 0 },
122153   { 208, 3 },
122154   { 208, 1 },
122155   { 149, 12 },
122156   { 230, 1 },
122157   { 230, 0 },
122158   { 179, 0 },
122159   { 179, 3 },
122160   { 188, 5 },
122161   { 188, 3 },
122162   { 231, 0 },
122163   { 231, 2 },
122164   { 149, 4 },
122165   { 149, 1 },
122166   { 149, 2 },
122167   { 149, 3 },
122168   { 149, 5 },
122169   { 149, 6 },
122170   { 149, 5 },
122171   { 149, 6 },
122172   { 232, 1 },
122173   { 232, 1 },
122174   { 232, 1 },
122175   { 232, 1 },
122176   { 232, 1 },
122177   { 171, 2 },
122178   { 171, 1 },
122179   { 172, 2 },
122180   { 149, 5 },
122181   { 233, 11 },
122182   { 235, 1 },
122183   { 235, 1 },
122184   { 235, 2 },
122185   { 235, 0 },
122186   { 236, 1 },
122187   { 236, 1 },
122188   { 236, 3 },
122189   { 237, 0 },
122190   { 237, 3 },
122191   { 238, 0 },
122192   { 238, 2 },
122193   { 234, 3 },
122194   { 234, 2 },
122195   { 240, 1 },
122196   { 240, 3 },
122197   { 241, 0 },
122198   { 241, 3 },
122199   { 241, 2 },
122200   { 239, 7 },
122201   { 239, 5 },
122202   { 239, 5 },
122203   { 239, 1 },
122204   { 175, 4 },
122205   { 175, 6 },
122206   { 192, 1 },
122207   { 192, 1 },
122208   { 192, 1 },
122209   { 149, 4 },
122210   { 149, 6 },
122211   { 149, 3 },
122212   { 243, 0 },
122213   { 243, 2 },
122214   { 242, 1 },
122215   { 242, 0 },
122216   { 149, 1 },
122217   { 149, 3 },
122218   { 149, 1 },
122219   { 149, 3 },
122220   { 149, 6 },
122221   { 149, 6 },
122222   { 244, 1 },
122223   { 245, 0 },
122224   { 245, 1 },
122225   { 149, 1 },
122226   { 149, 4 },
122227   { 246, 8 },
122228   { 247, 1 },
122229   { 247, 3 },
122230   { 248, 0 },
122231   { 248, 2 },
122232   { 249, 1 },
122233   { 249, 3 },
122234   { 250, 1 },
122235   { 251, 0 },
122236   { 251, 4 },
122237   { 251, 2 },
122238   { 197, 0 },
122239   { 197, 2 },
122240   { 197, 3 },
122241   { 252, 6 },
122242   { 252, 8 },
122243 };
122244 
122245 static void yy_accept(yyParser*);  /* Forward Declaration */
122246 
122247 /*
122248 ** Perform a reduce action and the shift that must immediately
122249 ** follow the reduce.
122250 */
122251 static void yy_reduce(
122252   yyParser *yypParser,         /* The parser */
122253   int yyruleno                 /* Number of the rule by which to reduce */
122254 ){
122255   int yygoto;                     /* The next state */
122256   int yyact;                      /* The next action */
122257   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
122258   yyStackEntry *yymsp;            /* The top of the parser's stack */
122259   int yysize;                     /* Amount to pop the stack */
122260   sqlite3ParserARG_FETCH;
122261   yymsp = &yypParser->yystack[yypParser->yyidx];
122262 #ifndef NDEBUG
122263   if( yyTraceFILE && yyruleno>=0
122264         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
122265     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
122266       yyRuleName[yyruleno]);
122267   }
122268 #endif /* NDEBUG */
122269 
122270   /* Silence complaints from purify about yygotominor being uninitialized
122271   ** in some cases when it is copied into the stack after the following
122272   ** switch.  yygotominor is uninitialized when a rule reduces that does
122273   ** not set the value of its left-hand side nonterminal.  Leaving the
122274   ** value of the nonterminal uninitialized is utterly harmless as long
122275   ** as the value is never used.  So really the only thing this code
122276   ** accomplishes is to quieten purify.
122277   **
122278   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
122279   ** without this code, their parser segfaults.  I'm not sure what there
122280   ** parser is doing to make this happen.  This is the second bug report
122281   ** from wireshark this week.  Clearly they are stressing Lemon in ways
122282   ** that it has not been previously stressed...  (SQLite ticket #2172)
122283   */
122284   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
122285   yygotominor = yyzerominor;
122286 
122287 
122288   switch( yyruleno ){
122289   /* Beginning here are the reduction cases.  A typical example
122290   ** follows:
122291   **   case 0:
122292   **  #line <lineno> <grammarfile>
122293   **     { ... }           // User supplied code
122294   **  #line <lineno> <thisfile>
122295   **     break;
122296   */
122297       case 5: /* explain ::= */
122298 { sqlite3BeginParse(pParse, 0); }
122299         break;
122300       case 6: /* explain ::= EXPLAIN */
122301 { sqlite3BeginParse(pParse, 1); }
122302         break;
122303       case 7: /* explain ::= EXPLAIN QUERY PLAN */
122304 { sqlite3BeginParse(pParse, 2); }
122305         break;
122306       case 8: /* cmdx ::= cmd */
122307 { sqlite3FinishCoding(pParse); }
122308         break;
122309       case 9: /* cmd ::= BEGIN transtype trans_opt */
122310 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
122311         break;
122312       case 13: /* transtype ::= */
122313 {yygotominor.yy328 = TK_DEFERRED;}
122314         break;
122315       case 14: /* transtype ::= DEFERRED */
122316       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
122317       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
122318       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
122319       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
122320 {yygotominor.yy328 = yymsp[0].major;}
122321         break;
122322       case 17: /* cmd ::= COMMIT trans_opt */
122323       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
122324 {sqlite3CommitTransaction(pParse);}
122325         break;
122326       case 19: /* cmd ::= ROLLBACK trans_opt */
122327 {sqlite3RollbackTransaction(pParse);}
122328         break;
122329       case 22: /* cmd ::= SAVEPOINT nm */
122330 {
122331   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
122332 }
122333         break;
122334       case 23: /* cmd ::= RELEASE savepoint_opt nm */
122335 {
122336   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
122337 }
122338         break;
122339       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
122340 {
122341   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
122342 }
122343         break;
122344       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
122345 {
122346    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
122347 }
122348         break;
122349       case 27: /* createkw ::= CREATE */
122350 {
122351   pParse->db->lookaside.bEnabled = 0;
122352   yygotominor.yy0 = yymsp[0].minor.yy0;
122353 }
122354         break;
122355       case 28: /* ifnotexists ::= */
122356       case 31: /* temp ::= */ yytestcase(yyruleno==31);
122357       case 68: /* autoinc ::= */ yytestcase(yyruleno==68);
122358       case 81: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==81);
122359       case 83: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==83);
122360       case 85: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==85);
122361       case 97: /* defer_subclause_opt ::= */ yytestcase(yyruleno==97);
122362       case 108: /* ifexists ::= */ yytestcase(yyruleno==108);
122363       case 218: /* between_op ::= BETWEEN */ yytestcase(yyruleno==218);
122364       case 221: /* in_op ::= IN */ yytestcase(yyruleno==221);
122365 {yygotominor.yy328 = 0;}
122366         break;
122367       case 29: /* ifnotexists ::= IF NOT EXISTS */
122368       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
122369       case 69: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==69);
122370       case 84: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==84);
122371       case 107: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==107);
122372       case 219: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==219);
122373       case 222: /* in_op ::= NOT IN */ yytestcase(yyruleno==222);
122374 {yygotominor.yy328 = 1;}
122375         break;
122376       case 32: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
122377 {
122378   sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy186,0);
122379 }
122380         break;
122381       case 33: /* create_table_args ::= AS select */
122382 {
122383   sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy3);
122384   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
122385 }
122386         break;
122387       case 34: /* table_options ::= */
122388 {yygotominor.yy186 = 0;}
122389         break;
122390       case 35: /* table_options ::= WITHOUT nm */
122391 {
122392   if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
122393     yygotominor.yy186 = TF_WithoutRowid;
122394   }else{
122395     yygotominor.yy186 = 0;
122396     sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
122397   }
122398 }
122399         break;
122400       case 38: /* column ::= columnid type carglist */
122401 {
122402   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
122403   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
122404 }
122405         break;
122406       case 39: /* columnid ::= nm */
122407 {
122408   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
122409   yygotominor.yy0 = yymsp[0].minor.yy0;
122410   pParse->constraintName.n = 0;
122411 }
122412         break;
122413       case 40: /* nm ::= ID|INDEXED */
122414       case 41: /* nm ::= STRING */ yytestcase(yyruleno==41);
122415       case 42: /* nm ::= JOIN_KW */ yytestcase(yyruleno==42);
122416       case 45: /* typetoken ::= typename */ yytestcase(yyruleno==45);
122417       case 48: /* typename ::= ID|STRING */ yytestcase(yyruleno==48);
122418       case 130: /* as ::= AS nm */ yytestcase(yyruleno==130);
122419       case 131: /* as ::= ID|STRING */ yytestcase(yyruleno==131);
122420       case 141: /* dbnm ::= DOT nm */ yytestcase(yyruleno==141);
122421       case 150: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==150);
122422       case 247: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==247);
122423       case 256: /* nmnum ::= plus_num */ yytestcase(yyruleno==256);
122424       case 257: /* nmnum ::= nm */ yytestcase(yyruleno==257);
122425       case 258: /* nmnum ::= ON */ yytestcase(yyruleno==258);
122426       case 259: /* nmnum ::= DELETE */ yytestcase(yyruleno==259);
122427       case 260: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==260);
122428       case 261: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==261);
122429       case 262: /* plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==262);
122430       case 263: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==263);
122431       case 279: /* trnm ::= nm */ yytestcase(yyruleno==279);
122432 {yygotominor.yy0 = yymsp[0].minor.yy0;}
122433         break;
122434       case 44: /* type ::= typetoken */
122435 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
122436         break;
122437       case 46: /* typetoken ::= typename LP signed RP */
122438 {
122439   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
122440   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
122441 }
122442         break;
122443       case 47: /* typetoken ::= typename LP signed COMMA signed RP */
122444 {
122445   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
122446   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
122447 }
122448         break;
122449       case 49: /* typename ::= typename ID|STRING */
122450 {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);}
122451         break;
122452       case 54: /* ccons ::= CONSTRAINT nm */
122453       case 92: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==92);
122454 {pParse->constraintName = yymsp[0].minor.yy0;}
122455         break;
122456       case 55: /* ccons ::= DEFAULT term */
122457       case 57: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==57);
122458 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
122459         break;
122460       case 56: /* ccons ::= DEFAULT LP expr RP */
122461 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
122462         break;
122463       case 58: /* ccons ::= DEFAULT MINUS term */
122464 {
122465   ExprSpan v;
122466   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
122467   v.zStart = yymsp[-1].minor.yy0.z;
122468   v.zEnd = yymsp[0].minor.yy346.zEnd;
122469   sqlite3AddDefaultValue(pParse,&v);
122470 }
122471         break;
122472       case 59: /* ccons ::= DEFAULT ID|INDEXED */
122473 {
122474   ExprSpan v;
122475   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
122476   sqlite3AddDefaultValue(pParse,&v);
122477 }
122478         break;
122479       case 61: /* ccons ::= NOT NULL onconf */
122480 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
122481         break;
122482       case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
122483 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
122484         break;
122485       case 63: /* ccons ::= UNIQUE onconf */
122486 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
122487         break;
122488       case 64: /* ccons ::= CHECK LP expr RP */
122489 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
122490         break;
122491       case 65: /* ccons ::= REFERENCES nm idxlist_opt refargs */
122492 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
122493         break;
122494       case 66: /* ccons ::= defer_subclause */
122495 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
122496         break;
122497       case 67: /* ccons ::= COLLATE ID|STRING */
122498 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
122499         break;
122500       case 70: /* refargs ::= */
122501 { yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
122502         break;
122503       case 71: /* refargs ::= refargs refarg */
122504 { yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
122505         break;
122506       case 72: /* refarg ::= MATCH nm */
122507       case 73: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==73);
122508 { yygotominor.yy429.value = 0;     yygotominor.yy429.mask = 0x000000; }
122509         break;
122510       case 74: /* refarg ::= ON DELETE refact */
122511 { yygotominor.yy429.value = yymsp[0].minor.yy328;     yygotominor.yy429.mask = 0x0000ff; }
122512         break;
122513       case 75: /* refarg ::= ON UPDATE refact */
122514 { yygotominor.yy429.value = yymsp[0].minor.yy328<<8;  yygotominor.yy429.mask = 0x00ff00; }
122515         break;
122516       case 76: /* refact ::= SET NULL */
122517 { yygotominor.yy328 = OE_SetNull;  /* EV: R-33326-45252 */}
122518         break;
122519       case 77: /* refact ::= SET DEFAULT */
122520 { yygotominor.yy328 = OE_SetDflt;  /* EV: R-33326-45252 */}
122521         break;
122522       case 78: /* refact ::= CASCADE */
122523 { yygotominor.yy328 = OE_Cascade;  /* EV: R-33326-45252 */}
122524         break;
122525       case 79: /* refact ::= RESTRICT */
122526 { yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
122527         break;
122528       case 80: /* refact ::= NO ACTION */
122529 { yygotominor.yy328 = OE_None;     /* EV: R-33326-45252 */}
122530         break;
122531       case 82: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
122532       case 98: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==98);
122533       case 100: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==100);
122534       case 103: /* resolvetype ::= raisetype */ yytestcase(yyruleno==103);
122535 {yygotominor.yy328 = yymsp[0].minor.yy328;}
122536         break;
122537       case 86: /* conslist_opt ::= */
122538 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
122539         break;
122540       case 87: /* conslist_opt ::= COMMA conslist */
122541 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
122542         break;
122543       case 90: /* tconscomma ::= COMMA */
122544 {pParse->constraintName.n = 0;}
122545         break;
122546       case 93: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
122547 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
122548         break;
122549       case 94: /* tcons ::= UNIQUE LP idxlist RP onconf */
122550 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
122551         break;
122552       case 95: /* tcons ::= CHECK LP expr RP onconf */
122553 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
122554         break;
122555       case 96: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
122556 {
122557     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
122558     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
122559 }
122560         break;
122561       case 99: /* onconf ::= */
122562 {yygotominor.yy328 = OE_Default;}
122563         break;
122564       case 101: /* orconf ::= */
122565 {yygotominor.yy186 = OE_Default;}
122566         break;
122567       case 102: /* orconf ::= OR resolvetype */
122568 {yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
122569         break;
122570       case 104: /* resolvetype ::= IGNORE */
122571 {yygotominor.yy328 = OE_Ignore;}
122572         break;
122573       case 105: /* resolvetype ::= REPLACE */
122574 {yygotominor.yy328 = OE_Replace;}
122575         break;
122576       case 106: /* cmd ::= DROP TABLE ifexists fullname */
122577 {
122578   sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
122579 }
122580         break;
122581       case 109: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
122582 {
122583   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);
122584 }
122585         break;
122586       case 110: /* cmd ::= DROP VIEW ifexists fullname */
122587 {
122588   sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
122589 }
122590         break;
122591       case 111: /* cmd ::= select */
122592 {
122593   SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
122594   sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
122595   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
122596 }
122597         break;
122598       case 112: /* select ::= with selectnowith */
122599 {
122600   Select *p = yymsp[0].minor.yy3, *pNext, *pLoop;
122601   if( p ){
122602     int cnt = 0, mxSelect;
122603     p->pWith = yymsp[-1].minor.yy59;
122604     if( p->pPrior ){
122605       pNext = 0;
122606       for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
122607         pLoop->pNext = pNext;
122608         pLoop->selFlags |= SF_Compound;
122609       }
122610       mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
122611       if( mxSelect && cnt>mxSelect ){
122612         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
122613       }
122614     }
122615   }else{
122616     sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy59);
122617   }
122618   yygotominor.yy3 = p;
122619 }
122620         break;
122621       case 113: /* selectnowith ::= oneselect */
122622       case 119: /* oneselect ::= values */ yytestcase(yyruleno==119);
122623 {yygotominor.yy3 = yymsp[0].minor.yy3;}
122624         break;
122625       case 114: /* selectnowith ::= selectnowith multiselect_op oneselect */
122626 {
122627   Select *pRhs = yymsp[0].minor.yy3;
122628   if( pRhs && pRhs->pPrior ){
122629     SrcList *pFrom;
122630     Token x;
122631     x.n = 0;
122632     pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
122633     pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
122634   }
122635   if( pRhs ){
122636     pRhs->op = (u8)yymsp[-1].minor.yy328;
122637     pRhs->pPrior = yymsp[-2].minor.yy3;
122638     if( yymsp[-1].minor.yy328!=TK_ALL ) pParse->hasCompound = 1;
122639   }else{
122640     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy3);
122641   }
122642   yygotominor.yy3 = pRhs;
122643 }
122644         break;
122645       case 116: /* multiselect_op ::= UNION ALL */
122646 {yygotominor.yy328 = TK_ALL;}
122647         break;
122648       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
122649 {
122650   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);
122651 #if SELECTTRACE_ENABLED
122652   /* Populate the Select.zSelName[] string that is used to help with
122653   ** query planner debugging, to differentiate between multiple Select
122654   ** objects in a complex query.
122655   **
122656   ** If the SELECT keyword is immediately followed by a C-style comment
122657   ** then extract the first few alphanumeric characters from within that
122658   ** comment to be the zSelName value.  Otherwise, the label is #N where
122659   ** is an integer that is incremented with each SELECT statement seen.
122660   */
122661   if( yygotominor.yy3!=0 ){
122662     const char *z = yymsp[-8].minor.yy0.z+6;
122663     int i;
122664     sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "#%d",
122665                      ++pParse->nSelect);
122666     while( z[0]==' ' ) z++;
122667     if( z[0]=='/' && z[1]=='*' ){
122668       z += 2;
122669       while( z[0]==' ' ) z++;
122670       for(i=0; sqlite3Isalnum(z[i]); i++){}
122671       sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "%.*s", i, z);
122672     }
122673   }
122674 #endif /* SELECTRACE_ENABLED */
122675 }
122676         break;
122677       case 120: /* values ::= VALUES LP nexprlist RP */
122678 {
122679   yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
122680 }
122681         break;
122682       case 121: /* values ::= values COMMA LP exprlist RP */
122683 {
122684   Select *pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
122685   if( pRight ){
122686     pRight->op = TK_ALL;
122687     pRight->pPrior = yymsp[-4].minor.yy3;
122688     yygotominor.yy3 = pRight;
122689   }else{
122690     yygotominor.yy3 = yymsp[-4].minor.yy3;
122691   }
122692 }
122693         break;
122694       case 122: /* distinct ::= DISTINCT */
122695 {yygotominor.yy381 = SF_Distinct;}
122696         break;
122697       case 123: /* distinct ::= ALL */
122698       case 124: /* distinct ::= */ yytestcase(yyruleno==124);
122699 {yygotominor.yy381 = 0;}
122700         break;
122701       case 125: /* sclp ::= selcollist COMMA */
122702       case 243: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==243);
122703 {yygotominor.yy14 = yymsp[-1].minor.yy14;}
122704         break;
122705       case 126: /* sclp ::= */
122706       case 154: /* orderby_opt ::= */ yytestcase(yyruleno==154);
122707       case 161: /* groupby_opt ::= */ yytestcase(yyruleno==161);
122708       case 236: /* exprlist ::= */ yytestcase(yyruleno==236);
122709       case 242: /* idxlist_opt ::= */ yytestcase(yyruleno==242);
122710 {yygotominor.yy14 = 0;}
122711         break;
122712       case 127: /* selcollist ::= sclp expr as */
122713 {
122714    yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
122715    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
122716    sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
122717 }
122718         break;
122719       case 128: /* selcollist ::= sclp STAR */
122720 {
122721   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
122722   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
122723 }
122724         break;
122725       case 129: /* selcollist ::= sclp nm DOT STAR */
122726 {
122727   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
122728   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
122729   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
122730   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
122731 }
122732         break;
122733       case 132: /* as ::= */
122734 {yygotominor.yy0.n = 0;}
122735         break;
122736       case 133: /* from ::= */
122737 {yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
122738         break;
122739       case 134: /* from ::= FROM seltablist */
122740 {
122741   yygotominor.yy65 = yymsp[0].minor.yy65;
122742   sqlite3SrcListShiftJoinType(yygotominor.yy65);
122743 }
122744         break;
122745       case 135: /* stl_prefix ::= seltablist joinop */
122746 {
122747    yygotominor.yy65 = yymsp[-1].minor.yy65;
122748    if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
122749 }
122750         break;
122751       case 136: /* stl_prefix ::= */
122752 {yygotominor.yy65 = 0;}
122753         break;
122754       case 137: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
122755 {
122756   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);
122757   sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
122758 }
122759         break;
122760       case 138: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
122761 {
122762     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);
122763   }
122764         break;
122765       case 139: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
122766 {
122767     if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
122768       yygotominor.yy65 = yymsp[-4].minor.yy65;
122769     }else if( yymsp[-4].minor.yy65->nSrc==1 ){
122770       yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
122771       if( yygotominor.yy65 ){
122772         struct SrcList_item *pNew = &yygotominor.yy65->a[yygotominor.yy65->nSrc-1];
122773         struct SrcList_item *pOld = yymsp[-4].minor.yy65->a;
122774         pNew->zName = pOld->zName;
122775         pNew->zDatabase = pOld->zDatabase;
122776         pNew->pSelect = pOld->pSelect;
122777         pOld->zName = pOld->zDatabase = 0;
122778         pOld->pSelect = 0;
122779       }
122780       sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy65);
122781     }else{
122782       Select *pSubquery;
122783       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
122784       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,SF_NestedFrom,0,0);
122785       yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
122786     }
122787   }
122788         break;
122789       case 140: /* dbnm ::= */
122790       case 149: /* indexed_opt ::= */ yytestcase(yyruleno==149);
122791 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
122792         break;
122793       case 142: /* fullname ::= nm dbnm */
122794 {yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
122795         break;
122796       case 143: /* joinop ::= COMMA|JOIN */
122797 { yygotominor.yy328 = JT_INNER; }
122798         break;
122799       case 144: /* joinop ::= JOIN_KW JOIN */
122800 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
122801         break;
122802       case 145: /* joinop ::= JOIN_KW nm JOIN */
122803 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
122804         break;
122805       case 146: /* joinop ::= JOIN_KW nm nm JOIN */
122806 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
122807         break;
122808       case 147: /* on_opt ::= ON expr */
122809       case 164: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==164);
122810       case 171: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==171);
122811       case 231: /* case_else ::= ELSE expr */ yytestcase(yyruleno==231);
122812       case 233: /* case_operand ::= expr */ yytestcase(yyruleno==233);
122813 {yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
122814         break;
122815       case 148: /* on_opt ::= */
122816       case 163: /* having_opt ::= */ yytestcase(yyruleno==163);
122817       case 170: /* where_opt ::= */ yytestcase(yyruleno==170);
122818       case 232: /* case_else ::= */ yytestcase(yyruleno==232);
122819       case 234: /* case_operand ::= */ yytestcase(yyruleno==234);
122820 {yygotominor.yy132 = 0;}
122821         break;
122822       case 151: /* indexed_opt ::= NOT INDEXED */
122823 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
122824         break;
122825       case 152: /* using_opt ::= USING LP idlist RP */
122826       case 180: /* inscollist_opt ::= LP idlist RP */ yytestcase(yyruleno==180);
122827 {yygotominor.yy408 = yymsp[-1].minor.yy408;}
122828         break;
122829       case 153: /* using_opt ::= */
122830       case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
122831 {yygotominor.yy408 = 0;}
122832         break;
122833       case 155: /* orderby_opt ::= ORDER BY sortlist */
122834       case 162: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==162);
122835       case 235: /* exprlist ::= nexprlist */ yytestcase(yyruleno==235);
122836 {yygotominor.yy14 = yymsp[0].minor.yy14;}
122837         break;
122838       case 156: /* sortlist ::= sortlist COMMA expr sortorder */
122839 {
122840   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy346.pExpr);
122841   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
122842 }
122843         break;
122844       case 157: /* sortlist ::= expr sortorder */
122845 {
122846   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy346.pExpr);
122847   if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
122848 }
122849         break;
122850       case 158: /* sortorder ::= ASC */
122851       case 160: /* sortorder ::= */ yytestcase(yyruleno==160);
122852 {yygotominor.yy328 = SQLITE_SO_ASC;}
122853         break;
122854       case 159: /* sortorder ::= DESC */
122855 {yygotominor.yy328 = SQLITE_SO_DESC;}
122856         break;
122857       case 165: /* limit_opt ::= */
122858 {yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
122859         break;
122860       case 166: /* limit_opt ::= LIMIT expr */
122861 {yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
122862         break;
122863       case 167: /* limit_opt ::= LIMIT expr OFFSET expr */
122864 {yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
122865         break;
122866       case 168: /* limit_opt ::= LIMIT expr COMMA expr */
122867 {yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
122868         break;
122869       case 169: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
122870 {
122871   sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
122872   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
122873   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
122874 }
122875         break;
122876       case 172: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
122877 {
122878   sqlite3WithPush(pParse, yymsp[-7].minor.yy59, 1);
122879   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
122880   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list");
122881   sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
122882 }
122883         break;
122884       case 173: /* setlist ::= setlist COMMA nm EQ expr */
122885 {
122886   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
122887   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
122888 }
122889         break;
122890       case 174: /* setlist ::= nm EQ expr */
122891 {
122892   yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
122893   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
122894 }
122895         break;
122896       case 175: /* cmd ::= with insert_cmd INTO fullname inscollist_opt select */
122897 {
122898   sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
122899   sqlite3Insert(pParse, yymsp[-2].minor.yy65, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);
122900 }
122901         break;
122902       case 176: /* cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
122903 {
122904   sqlite3WithPush(pParse, yymsp[-6].minor.yy59, 1);
122905   sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);
122906 }
122907         break;
122908       case 177: /* insert_cmd ::= INSERT orconf */
122909 {yygotominor.yy186 = yymsp[0].minor.yy186;}
122910         break;
122911       case 178: /* insert_cmd ::= REPLACE */
122912 {yygotominor.yy186 = OE_Replace;}
122913         break;
122914       case 181: /* idlist ::= idlist COMMA nm */
122915 {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
122916         break;
122917       case 182: /* idlist ::= nm */
122918 {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
122919         break;
122920       case 183: /* expr ::= term */
122921 {yygotominor.yy346 = yymsp[0].minor.yy346;}
122922         break;
122923       case 184: /* expr ::= LP expr RP */
122924 {yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
122925         break;
122926       case 185: /* term ::= NULL */
122927       case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
122928       case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
122929 {spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
122930         break;
122931       case 186: /* expr ::= ID|INDEXED */
122932       case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
122933 {spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
122934         break;
122935       case 188: /* expr ::= nm DOT nm */
122936 {
122937   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
122938   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
122939   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
122940   spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
122941 }
122942         break;
122943       case 189: /* expr ::= nm DOT nm DOT nm */
122944 {
122945   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
122946   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
122947   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
122948   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
122949   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
122950   spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
122951 }
122952         break;
122953       case 192: /* expr ::= VARIABLE */
122954 {
122955   if( yymsp[0].minor.yy0.n>=2 && yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1]) ){
122956     /* When doing a nested parse, one can include terms in an expression
122957     ** that look like this:   #1 #2 ...  These terms refer to registers
122958     ** in the virtual machine.  #N is the N-th register. */
122959     if( pParse->nested==0 ){
122960       sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
122961       yygotominor.yy346.pExpr = 0;
122962     }else{
122963       yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
122964       if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
122965     }
122966   }else{
122967     spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
122968     sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
122969   }
122970   spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
122971 }
122972         break;
122973       case 193: /* expr ::= expr COLLATE ID|STRING */
122974 {
122975   yygotominor.yy346.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0);
122976   yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
122977   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
122978 }
122979         break;
122980       case 194: /* expr ::= CAST LP expr AS typetoken RP */
122981 {
122982   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
122983   spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
122984 }
122985         break;
122986       case 195: /* expr ::= ID|INDEXED LP distinct exprlist RP */
122987 {
122988   if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
122989     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
122990   }
122991   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
122992   spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
122993   if( yymsp[-2].minor.yy381 && yygotominor.yy346.pExpr ){
122994     yygotominor.yy346.pExpr->flags |= EP_Distinct;
122995   }
122996 }
122997         break;
122998       case 196: /* expr ::= ID|INDEXED LP STAR RP */
122999 {
123000   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
123001   spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
123002 }
123003         break;
123004       case 197: /* term ::= CTIME_KW */
123005 {
123006   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
123007   spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
123008 }
123009         break;
123010       case 198: /* expr ::= expr AND expr */
123011       case 199: /* expr ::= expr OR expr */ yytestcase(yyruleno==199);
123012       case 200: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==200);
123013       case 201: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==201);
123014       case 202: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==202);
123015       case 203: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==203);
123016       case 204: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==204);
123017       case 205: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==205);
123018 {spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
123019         break;
123020       case 206: /* likeop ::= LIKE_KW|MATCH */
123021 {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 0;}
123022         break;
123023       case 207: /* likeop ::= NOT LIKE_KW|MATCH */
123024 {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 1;}
123025         break;
123026       case 208: /* expr ::= expr likeop expr */
123027 {
123028   ExprList *pList;
123029   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy346.pExpr);
123030   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy346.pExpr);
123031   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy96.eOperator);
123032   if( yymsp[-1].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
123033   yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
123034   yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
123035   if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
123036 }
123037         break;
123038       case 209: /* expr ::= expr likeop expr ESCAPE expr */
123039 {
123040   ExprList *pList;
123041   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
123042   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy346.pExpr);
123043   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
123044   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy96.eOperator);
123045   if( yymsp[-3].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
123046   yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
123047   yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
123048   if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
123049 }
123050         break;
123051       case 210: /* expr ::= expr ISNULL|NOTNULL */
123052 {spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
123053         break;
123054       case 211: /* expr ::= expr NOT NULL */
123055 {spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
123056         break;
123057       case 212: /* expr ::= expr IS expr */
123058 {
123059   spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
123060   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
123061 }
123062         break;
123063       case 213: /* expr ::= expr IS NOT expr */
123064 {
123065   spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
123066   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
123067 }
123068         break;
123069       case 214: /* expr ::= NOT expr */
123070       case 215: /* expr ::= BITNOT expr */ yytestcase(yyruleno==215);
123071 {spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
123072         break;
123073       case 216: /* expr ::= MINUS expr */
123074 {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
123075         break;
123076       case 217: /* expr ::= PLUS expr */
123077 {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
123078         break;
123079       case 220: /* expr ::= expr between_op expr AND expr */
123080 {
123081   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
123082   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
123083   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
123084   if( yygotominor.yy346.pExpr ){
123085     yygotominor.yy346.pExpr->x.pList = pList;
123086   }else{
123087     sqlite3ExprListDelete(pParse->db, pList);
123088   }
123089   if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
123090   yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
123091   yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
123092 }
123093         break;
123094       case 223: /* expr ::= expr in_op LP exprlist RP */
123095 {
123096     if( yymsp[-1].minor.yy14==0 ){
123097       /* Expressions of the form
123098       **
123099       **      expr1 IN ()
123100       **      expr1 NOT IN ()
123101       **
123102       ** simplify to constants 0 (false) and 1 (true), respectively,
123103       ** regardless of the value of expr1.
123104       */
123105       yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy328]);
123106       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy346.pExpr);
123107     }else if( yymsp[-1].minor.yy14->nExpr==1 ){
123108       /* Expressions of the form:
123109       **
123110       **      expr1 IN (?1)
123111       **      expr1 NOT IN (?2)
123112       **
123113       ** with exactly one value on the RHS can be simplified to something
123114       ** like this:
123115       **
123116       **      expr1 == ?1
123117       **      expr1 <> ?2
123118       **
123119       ** But, the RHS of the == or <> is marked with the EP_Generic flag
123120       ** so that it may not contribute to the computation of comparison
123121       ** affinity or the collating sequence to use for comparison.  Otherwise,
123122       ** the semantics would be subtly different from IN or NOT IN.
123123       */
123124       Expr *pRHS = yymsp[-1].minor.yy14->a[0].pExpr;
123125       yymsp[-1].minor.yy14->a[0].pExpr = 0;
123126       sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
123127       /* pRHS cannot be NULL because a malloc error would have been detected
123128       ** before now and control would have never reached this point */
123129       if( ALWAYS(pRHS) ){
123130         pRHS->flags &= ~EP_Collate;
123131         pRHS->flags |= EP_Generic;
123132       }
123133       yygotominor.yy346.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy328 ? TK_NE : TK_EQ, yymsp[-4].minor.yy346.pExpr, pRHS, 0);
123134     }else{
123135       yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
123136       if( yygotominor.yy346.pExpr ){
123137         yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
123138         sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
123139       }else{
123140         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
123141       }
123142       if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
123143     }
123144     yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
123145     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
123146   }
123147         break;
123148       case 224: /* expr ::= LP select RP */
123149 {
123150     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
123151     if( yygotominor.yy346.pExpr ){
123152       yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
123153       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
123154       sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
123155     }else{
123156       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
123157     }
123158     yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
123159     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
123160   }
123161         break;
123162       case 225: /* expr ::= expr in_op LP select RP */
123163 {
123164     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
123165     if( yygotominor.yy346.pExpr ){
123166       yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
123167       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
123168       sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
123169     }else{
123170       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
123171     }
123172     if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
123173     yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
123174     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
123175   }
123176         break;
123177       case 226: /* expr ::= expr in_op nm dbnm */
123178 {
123179     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
123180     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
123181     if( yygotominor.yy346.pExpr ){
123182       yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
123183       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
123184       sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
123185     }else{
123186       sqlite3SrcListDelete(pParse->db, pSrc);
123187     }
123188     if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
123189     yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
123190     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];
123191   }
123192         break;
123193       case 227: /* expr ::= EXISTS LP select RP */
123194 {
123195     Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
123196     if( p ){
123197       p->x.pSelect = yymsp[-1].minor.yy3;
123198       ExprSetProperty(p, EP_xIsSelect);
123199       sqlite3ExprSetHeight(pParse, p);
123200     }else{
123201       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
123202     }
123203     yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
123204     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
123205   }
123206         break;
123207       case 228: /* expr ::= CASE case_operand case_exprlist case_else END */
123208 {
123209   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, 0, 0);
123210   if( yygotominor.yy346.pExpr ){
123211     yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy132 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[-1].minor.yy132) : yymsp[-2].minor.yy14;
123212     sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
123213   }else{
123214     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
123215     sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy132);
123216   }
123217   yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
123218   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
123219 }
123220         break;
123221       case 229: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
123222 {
123223   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
123224   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
123225 }
123226         break;
123227       case 230: /* case_exprlist ::= WHEN expr THEN expr */
123228 {
123229   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
123230   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
123231 }
123232         break;
123233       case 237: /* nexprlist ::= nexprlist COMMA expr */
123234 {yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
123235         break;
123236       case 238: /* nexprlist ::= expr */
123237 {yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
123238         break;
123239       case 239: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt */
123240 {
123241   sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
123242                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy14, yymsp[-10].minor.yy328,
123243                       &yymsp[-11].minor.yy0, yymsp[0].minor.yy132, SQLITE_SO_ASC, yymsp[-8].minor.yy328);
123244 }
123245         break;
123246       case 240: /* uniqueflag ::= UNIQUE */
123247       case 291: /* raisetype ::= ABORT */ yytestcase(yyruleno==291);
123248 {yygotominor.yy328 = OE_Abort;}
123249         break;
123250       case 241: /* uniqueflag ::= */
123251 {yygotominor.yy328 = OE_None;}
123252         break;
123253       case 244: /* idxlist ::= idxlist COMMA nm collate sortorder */
123254 {
123255   Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
123256   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
123257   sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
123258   sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
123259   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
123260 }
123261         break;
123262       case 245: /* idxlist ::= nm collate sortorder */
123263 {
123264   Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
123265   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
123266   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
123267   sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
123268   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
123269 }
123270         break;
123271       case 246: /* collate ::= */
123272 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
123273         break;
123274       case 248: /* cmd ::= DROP INDEX ifexists fullname */
123275 {sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
123276         break;
123277       case 249: /* cmd ::= VACUUM */
123278       case 250: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==250);
123279 {sqlite3Vacuum(pParse);}
123280         break;
123281       case 251: /* cmd ::= PRAGMA nm dbnm */
123282 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
123283         break;
123284       case 252: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
123285 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
123286         break;
123287       case 253: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
123288 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
123289         break;
123290       case 254: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
123291 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
123292         break;
123293       case 255: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
123294 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
123295         break;
123296       case 264: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
123297 {
123298   Token all;
123299   all.z = yymsp[-3].minor.yy0.z;
123300   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
123301   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
123302 }
123303         break;
123304       case 265: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
123305 {
123306   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);
123307   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
123308 }
123309         break;
123310       case 266: /* trigger_time ::= BEFORE */
123311       case 269: /* trigger_time ::= */ yytestcase(yyruleno==269);
123312 { yygotominor.yy328 = TK_BEFORE; }
123313         break;
123314       case 267: /* trigger_time ::= AFTER */
123315 { yygotominor.yy328 = TK_AFTER;  }
123316         break;
123317       case 268: /* trigger_time ::= INSTEAD OF */
123318 { yygotominor.yy328 = TK_INSTEAD;}
123319         break;
123320       case 270: /* trigger_event ::= DELETE|INSERT */
123321       case 271: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==271);
123322 {yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
123323         break;
123324       case 272: /* trigger_event ::= UPDATE OF idlist */
123325 {yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
123326         break;
123327       case 275: /* when_clause ::= */
123328       case 296: /* key_opt ::= */ yytestcase(yyruleno==296);
123329 { yygotominor.yy132 = 0; }
123330         break;
123331       case 276: /* when_clause ::= WHEN expr */
123332       case 297: /* key_opt ::= KEY expr */ yytestcase(yyruleno==297);
123333 { yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
123334         break;
123335       case 277: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
123336 {
123337   assert( yymsp[-2].minor.yy473!=0 );
123338   yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
123339   yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
123340   yygotominor.yy473 = yymsp[-2].minor.yy473;
123341 }
123342         break;
123343       case 278: /* trigger_cmd_list ::= trigger_cmd SEMI */
123344 {
123345   assert( yymsp[-1].minor.yy473!=0 );
123346   yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
123347   yygotominor.yy473 = yymsp[-1].minor.yy473;
123348 }
123349         break;
123350       case 280: /* trnm ::= nm DOT nm */
123351 {
123352   yygotominor.yy0 = yymsp[0].minor.yy0;
123353   sqlite3ErrorMsg(pParse,
123354         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
123355         "statements within triggers");
123356 }
123357         break;
123358       case 282: /* tridxby ::= INDEXED BY nm */
123359 {
123360   sqlite3ErrorMsg(pParse,
123361         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
123362         "within triggers");
123363 }
123364         break;
123365       case 283: /* tridxby ::= NOT INDEXED */
123366 {
123367   sqlite3ErrorMsg(pParse,
123368         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
123369         "within triggers");
123370 }
123371         break;
123372       case 284: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
123373 { yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
123374         break;
123375       case 285: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
123376 {yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
123377         break;
123378       case 286: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
123379 {yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
123380         break;
123381       case 287: /* trigger_cmd ::= select */
123382 {yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
123383         break;
123384       case 288: /* expr ::= RAISE LP IGNORE RP */
123385 {
123386   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
123387   if( yygotominor.yy346.pExpr ){
123388     yygotominor.yy346.pExpr->affinity = OE_Ignore;
123389   }
123390   yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
123391   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
123392 }
123393         break;
123394       case 289: /* expr ::= RAISE LP raisetype COMMA nm RP */
123395 {
123396   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
123397   if( yygotominor.yy346.pExpr ) {
123398     yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
123399   }
123400   yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
123401   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
123402 }
123403         break;
123404       case 290: /* raisetype ::= ROLLBACK */
123405 {yygotominor.yy328 = OE_Rollback;}
123406         break;
123407       case 292: /* raisetype ::= FAIL */
123408 {yygotominor.yy328 = OE_Fail;}
123409         break;
123410       case 293: /* cmd ::= DROP TRIGGER ifexists fullname */
123411 {
123412   sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
123413 }
123414         break;
123415       case 294: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
123416 {
123417   sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
123418 }
123419         break;
123420       case 295: /* cmd ::= DETACH database_kw_opt expr */
123421 {
123422   sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
123423 }
123424         break;
123425       case 300: /* cmd ::= REINDEX */
123426 {sqlite3Reindex(pParse, 0, 0);}
123427         break;
123428       case 301: /* cmd ::= REINDEX nm dbnm */
123429 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
123430         break;
123431       case 302: /* cmd ::= ANALYZE */
123432 {sqlite3Analyze(pParse, 0, 0);}
123433         break;
123434       case 303: /* cmd ::= ANALYZE nm dbnm */
123435 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
123436         break;
123437       case 304: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
123438 {
123439   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
123440 }
123441         break;
123442       case 305: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
123443 {
123444   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
123445 }
123446         break;
123447       case 306: /* add_column_fullname ::= fullname */
123448 {
123449   pParse->db->lookaside.bEnabled = 0;
123450   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
123451 }
123452         break;
123453       case 309: /* cmd ::= create_vtab */
123454 {sqlite3VtabFinishParse(pParse,0);}
123455         break;
123456       case 310: /* cmd ::= create_vtab LP vtabarglist RP */
123457 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
123458         break;
123459       case 311: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
123460 {
123461     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy328);
123462 }
123463         break;
123464       case 314: /* vtabarg ::= */
123465 {sqlite3VtabArgInit(pParse);}
123466         break;
123467       case 316: /* vtabargtoken ::= ANY */
123468       case 317: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==317);
123469       case 318: /* lp ::= LP */ yytestcase(yyruleno==318);
123470 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
123471         break;
123472       case 322: /* with ::= */
123473 {yygotominor.yy59 = 0;}
123474         break;
123475       case 323: /* with ::= WITH wqlist */
123476       case 324: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==324);
123477 { yygotominor.yy59 = yymsp[0].minor.yy59; }
123478         break;
123479       case 325: /* wqlist ::= nm idxlist_opt AS LP select RP */
123480 {
123481   yygotominor.yy59 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
123482 }
123483         break;
123484       case 326: /* wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP */
123485 {
123486   yygotominor.yy59 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy59, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
123487 }
123488         break;
123489       default:
123490       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
123491       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
123492       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
123493       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
123494       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
123495       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
123496       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
123497       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
123498       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
123499       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
123500       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
123501       /* (36) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==36);
123502       /* (37) columnlist ::= column */ yytestcase(yyruleno==37);
123503       /* (43) type ::= */ yytestcase(yyruleno==43);
123504       /* (50) signed ::= plus_num */ yytestcase(yyruleno==50);
123505       /* (51) signed ::= minus_num */ yytestcase(yyruleno==51);
123506       /* (52) carglist ::= carglist ccons */ yytestcase(yyruleno==52);
123507       /* (53) carglist ::= */ yytestcase(yyruleno==53);
123508       /* (60) ccons ::= NULL onconf */ yytestcase(yyruleno==60);
123509       /* (88) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==88);
123510       /* (89) conslist ::= tcons */ yytestcase(yyruleno==89);
123511       /* (91) tconscomma ::= */ yytestcase(yyruleno==91);
123512       /* (273) foreach_clause ::= */ yytestcase(yyruleno==273);
123513       /* (274) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==274);
123514       /* (281) tridxby ::= */ yytestcase(yyruleno==281);
123515       /* (298) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==298);
123516       /* (299) database_kw_opt ::= */ yytestcase(yyruleno==299);
123517       /* (307) kwcolumn_opt ::= */ yytestcase(yyruleno==307);
123518       /* (308) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==308);
123519       /* (312) vtabarglist ::= vtabarg */ yytestcase(yyruleno==312);
123520       /* (313) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==313);
123521       /* (315) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==315);
123522       /* (319) anylist ::= */ yytestcase(yyruleno==319);
123523       /* (320) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==320);
123524       /* (321) anylist ::= anylist ANY */ yytestcase(yyruleno==321);
123525         break;
123526   };
123527   assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
123528   yygoto = yyRuleInfo[yyruleno].lhs;
123529   yysize = yyRuleInfo[yyruleno].nrhs;
123530   yypParser->yyidx -= yysize;
123531   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
123532   if( yyact < YYNSTATE ){
123533 #ifdef NDEBUG
123534     /* If we are not debugging and the reduce action popped at least
123535     ** one element off the stack, then we can push the new element back
123536     ** onto the stack here, and skip the stack overflow test in yy_shift().
123537     ** That gives a significant speed improvement. */
123538     if( yysize ){
123539       yypParser->yyidx++;
123540       yymsp -= yysize-1;
123541       yymsp->stateno = (YYACTIONTYPE)yyact;
123542       yymsp->major = (YYCODETYPE)yygoto;
123543       yymsp->minor = yygotominor;
123544     }else
123545 #endif
123546     {
123547       yy_shift(yypParser,yyact,yygoto,&yygotominor);
123548     }
123549   }else{
123550     assert( yyact == YYNSTATE + YYNRULE + 1 );
123551     yy_accept(yypParser);
123552   }
123553 }
123554 
123555 /*
123556 ** The following code executes when the parse fails
123557 */
123558 #ifndef YYNOERRORRECOVERY
123559 static void yy_parse_failed(
123560   yyParser *yypParser           /* The parser */
123561 ){
123562   sqlite3ParserARG_FETCH;
123563 #ifndef NDEBUG
123564   if( yyTraceFILE ){
123565     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
123566   }
123567 #endif
123568   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
123569   /* Here code is inserted which will be executed whenever the
123570   ** parser fails */
123571   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
123572 }
123573 #endif /* YYNOERRORRECOVERY */
123574 
123575 /*
123576 ** The following code executes when a syntax error first occurs.
123577 */
123578 static void yy_syntax_error(
123579   yyParser *yypParser,           /* The parser */
123580   int yymajor,                   /* The major type of the error token */
123581   YYMINORTYPE yyminor            /* The minor type of the error token */
123582 ){
123583   sqlite3ParserARG_FETCH;
123584 #define TOKEN (yyminor.yy0)
123585 
123586   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
123587   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
123588   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
123589   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
123590 }
123591 
123592 /*
123593 ** The following is executed when the parser accepts
123594 */
123595 static void yy_accept(
123596   yyParser *yypParser           /* The parser */
123597 ){
123598   sqlite3ParserARG_FETCH;
123599 #ifndef NDEBUG
123600   if( yyTraceFILE ){
123601     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
123602   }
123603 #endif
123604   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
123605   /* Here code is inserted which will be executed whenever the
123606   ** parser accepts */
123607   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
123608 }
123609 
123610 /* The main parser program.
123611 ** The first argument is a pointer to a structure obtained from
123612 ** "sqlite3ParserAlloc" which describes the current state of the parser.
123613 ** The second argument is the major token number.  The third is
123614 ** the minor token.  The fourth optional argument is whatever the
123615 ** user wants (and specified in the grammar) and is available for
123616 ** use by the action routines.
123617 **
123618 ** Inputs:
123619 ** <ul>
123620 ** <li> A pointer to the parser (an opaque structure.)
123621 ** <li> The major token number.
123622 ** <li> The minor token number.
123623 ** <li> An option argument of a grammar-specified type.
123624 ** </ul>
123625 **
123626 ** Outputs:
123627 ** None.
123628 */
123629 SQLITE_PRIVATE void sqlite3Parser(
123630   void *yyp,                   /* The parser */
123631   int yymajor,                 /* The major token code number */
123632   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
123633   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
123634 ){
123635   YYMINORTYPE yyminorunion;
123636   int yyact;            /* The parser action. */
123637 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
123638   int yyendofinput;     /* True if we are at the end of input */
123639 #endif
123640 #ifdef YYERRORSYMBOL
123641   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
123642 #endif
123643   yyParser *yypParser;  /* The parser */
123644 
123645   /* (re)initialize the parser, if necessary */
123646   yypParser = (yyParser*)yyp;
123647   if( yypParser->yyidx<0 ){
123648 #if YYSTACKDEPTH<=0
123649     if( yypParser->yystksz <=0 ){
123650       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
123651       yyminorunion = yyzerominor;
123652       yyStackOverflow(yypParser, &yyminorunion);
123653       return;
123654     }
123655 #endif
123656     yypParser->yyidx = 0;
123657     yypParser->yyerrcnt = -1;
123658     yypParser->yystack[0].stateno = 0;
123659     yypParser->yystack[0].major = 0;
123660   }
123661   yyminorunion.yy0 = yyminor;
123662 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
123663   yyendofinput = (yymajor==0);
123664 #endif
123665   sqlite3ParserARG_STORE;
123666 
123667 #ifndef NDEBUG
123668   if( yyTraceFILE ){
123669     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
123670   }
123671 #endif
123672 
123673   do{
123674     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
123675     if( yyact<YYNSTATE ){
123676       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
123677       yypParser->yyerrcnt--;
123678       yymajor = YYNOCODE;
123679     }else if( yyact < YYNSTATE + YYNRULE ){
123680       yy_reduce(yypParser,yyact-YYNSTATE);
123681     }else{
123682       assert( yyact == YY_ERROR_ACTION );
123683 #ifdef YYERRORSYMBOL
123684       int yymx;
123685 #endif
123686 #ifndef NDEBUG
123687       if( yyTraceFILE ){
123688         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
123689       }
123690 #endif
123691 #ifdef YYERRORSYMBOL
123692       /* A syntax error has occurred.
123693       ** The response to an error depends upon whether or not the
123694       ** grammar defines an error token "ERROR".
123695       **
123696       ** This is what we do if the grammar does define ERROR:
123697       **
123698       **  * Call the %syntax_error function.
123699       **
123700       **  * Begin popping the stack until we enter a state where
123701       **    it is legal to shift the error symbol, then shift
123702       **    the error symbol.
123703       **
123704       **  * Set the error count to three.
123705       **
123706       **  * Begin accepting and shifting new tokens.  No new error
123707       **    processing will occur until three tokens have been
123708       **    shifted successfully.
123709       **
123710       */
123711       if( yypParser->yyerrcnt<0 ){
123712         yy_syntax_error(yypParser,yymajor,yyminorunion);
123713       }
123714       yymx = yypParser->yystack[yypParser->yyidx].major;
123715       if( yymx==YYERRORSYMBOL || yyerrorhit ){
123716 #ifndef NDEBUG
123717         if( yyTraceFILE ){
123718           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
123719              yyTracePrompt,yyTokenName[yymajor]);
123720         }
123721 #endif
123722         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
123723         yymajor = YYNOCODE;
123724       }else{
123725          while(
123726           yypParser->yyidx >= 0 &&
123727           yymx != YYERRORSYMBOL &&
123728           (yyact = yy_find_reduce_action(
123729                         yypParser->yystack[yypParser->yyidx].stateno,
123730                         YYERRORSYMBOL)) >= YYNSTATE
123731         ){
123732           yy_pop_parser_stack(yypParser);
123733         }
123734         if( yypParser->yyidx < 0 || yymajor==0 ){
123735           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
123736           yy_parse_failed(yypParser);
123737           yymajor = YYNOCODE;
123738         }else if( yymx!=YYERRORSYMBOL ){
123739           YYMINORTYPE u2;
123740           u2.YYERRSYMDT = 0;
123741           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
123742         }
123743       }
123744       yypParser->yyerrcnt = 3;
123745       yyerrorhit = 1;
123746 #elif defined(YYNOERRORRECOVERY)
123747       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
123748       ** do any kind of error recovery.  Instead, simply invoke the syntax
123749       ** error routine and continue going as if nothing had happened.
123750       **
123751       ** Applications can set this macro (for example inside %include) if
123752       ** they intend to abandon the parse upon the first syntax error seen.
123753       */
123754       yy_syntax_error(yypParser,yymajor,yyminorunion);
123755       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
123756       yymajor = YYNOCODE;
123757 
123758 #else  /* YYERRORSYMBOL is not defined */
123759       /* This is what we do if the grammar does not define ERROR:
123760       **
123761       **  * Report an error message, and throw away the input token.
123762       **
123763       **  * If the input token is $, then fail the parse.
123764       **
123765       ** As before, subsequent error messages are suppressed until
123766       ** three input tokens have been successfully shifted.
123767       */
123768       if( yypParser->yyerrcnt<=0 ){
123769         yy_syntax_error(yypParser,yymajor,yyminorunion);
123770       }
123771       yypParser->yyerrcnt = 3;
123772       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
123773       if( yyendofinput ){
123774         yy_parse_failed(yypParser);
123775       }
123776       yymajor = YYNOCODE;
123777 #endif
123778     }
123779   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
123780   return;
123781 }
123782 
123783 /************** End of parse.c ***********************************************/
123784 /************** Begin file tokenize.c ****************************************/
123785 /*
123786 ** 2001 September 15
123787 **
123788 ** The author disclaims copyright to this source code.  In place of
123789 ** a legal notice, here is a blessing:
123790 **
123791 **    May you do good and not evil.
123792 **    May you find forgiveness for yourself and forgive others.
123793 **    May you share freely, never taking more than you give.
123794 **
123795 *************************************************************************
123796 ** An tokenizer for SQL
123797 **
123798 ** This file contains C code that splits an SQL input string up into
123799 ** individual tokens and sends those tokens one-by-one over to the
123800 ** parser for analysis.
123801 */
123802 /* #include <stdlib.h> */
123803 
123804 /*
123805 ** The charMap() macro maps alphabetic characters into their
123806 ** lower-case ASCII equivalent.  On ASCII machines, this is just
123807 ** an upper-to-lower case map.  On EBCDIC machines we also need
123808 ** to adjust the encoding.  Only alphabetic characters and underscores
123809 ** need to be translated.
123810 */
123811 #ifdef SQLITE_ASCII
123812 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
123813 #endif
123814 #ifdef SQLITE_EBCDIC
123815 # define charMap(X) ebcdicToAscii[(unsigned char)X]
123816 const unsigned char ebcdicToAscii[] = {
123817 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
123818    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
123819    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
123820    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
123821    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
123822    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
123823    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
123824    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
123825    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
123826    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
123827    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
123828    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
123829    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
123830    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
123831    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
123832    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
123833    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
123834 };
123835 #endif
123836 
123837 /*
123838 ** The sqlite3KeywordCode function looks up an identifier to determine if
123839 ** it is a keyword.  If it is a keyword, the token code of that keyword is
123840 ** returned.  If the input is not a keyword, TK_ID is returned.
123841 **
123842 ** The implementation of this routine was generated by a program,
123843 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
123844 ** The output of the mkkeywordhash.c program is written into a file
123845 ** named keywordhash.h and then included into this source file by
123846 ** the #include below.
123847 */
123848 /************** Include keywordhash.h in the middle of tokenize.c ************/
123849 /************** Begin file keywordhash.h *************************************/
123850 /***** This file contains automatically generated code ******
123851 **
123852 ** The code in this file has been automatically generated by
123853 **
123854 **   sqlite/tool/mkkeywordhash.c
123855 **
123856 ** The code in this file implements a function that determines whether
123857 ** or not a given identifier is really an SQL keyword.  The same thing
123858 ** might be implemented more directly using a hand-written hash table.
123859 ** But by using this automatically generated code, the size of the code
123860 ** is substantially reduced.  This is important for embedded applications
123861 ** on platforms with limited memory.
123862 */
123863 /* Hash score: 182 */
123864 static int keywordCode(const char *z, int n){
123865   /* zText[] encodes 834 bytes of keywords in 554 bytes */
123866   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
123867   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
123868   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
123869   /*   UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE         */
123870   /*   BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH     */
123871   /*   IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN     */
123872   /*   WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT         */
123873   /*   CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL        */
123874   /*   FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING        */
123875   /*   VACUUMVIEWINITIALLY                                                */
123876   static const char zText[553] = {
123877     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
123878     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
123879     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
123880     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
123881     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
123882     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
123883     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
123884     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
123885     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
123886     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
123887     'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
123888     'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
123889     'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
123890     'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
123891     'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
123892     'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
123893     'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
123894     'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
123895     'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
123896     'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
123897     'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
123898     'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
123899     'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
123900     'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
123901     'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
123902     'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
123903     'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
123904     'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
123905     'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
123906     'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
123907     'V','I','E','W','I','N','I','T','I','A','L','L','Y',
123908   };
123909   static const unsigned char aHash[127] = {
123910       76, 105, 117,  74,   0,  45,   0,   0,  82,   0,  77,   0,   0,
123911       42,  12,  78,  15,   0, 116,  85,  54, 112,   0,  19,   0,   0,
123912      121,   0, 119, 115,   0,  22,  93,   0,   9,   0,   0,  70,  71,
123913        0,  69,   6,   0,  48,  90, 102,   0, 118, 101,   0,   0,  44,
123914        0, 103,  24,   0,  17,   0, 122,  53,  23,   0,   5, 110,  25,
123915       96,   0,   0, 124, 106,  60, 123,  57,  28,  55,   0,  91,   0,
123916      100,  26,   0,  99,   0,   0,   0,  95,  92,  97,  88, 109,  14,
123917       39, 108,   0,  81,   0,  18,  89, 111,  32,   0, 120,  80, 113,
123918       62,  46,  84,   0,   0,  94,  40,  59, 114,   0,  36,   0,   0,
123919       29,   0,  86,  63,  64,   0,  20,  61,   0,  56,
123920   };
123921   static const unsigned char aNext[124] = {
123922        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
123923        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
123924        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
123925        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,   0,   0,  50,
123926        0,  43,   3,  47,   0,   0,   0,   0,  30,   0,  58,   0,  38,
123927        0,   0,   0,   1,  66,   0,   0,  67,   0,  41,   0,   0,   0,
123928        0,   0,   0,  49,  65,   0,   0,   0,   0,  31,  52,  16,  34,
123929       10,   0,   0,   0,   0,   0,   0,   0,  11,  72,  79,   0,   8,
123930        0, 104,  98,   0, 107,   0,  87,   0,  75,  51,   0,  27,  37,
123931       73,  83,   0,  35,  68,   0,   0,
123932   };
123933   static const unsigned char aLen[124] = {
123934        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
123935        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
123936       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
123937        4,   6,   2,   3,   9,   4,   2,   6,   5,   7,   4,   5,   7,
123938        6,   6,   5,   6,   5,   5,   9,   7,   7,   3,   2,   4,   4,
123939        7,   3,   6,   4,   7,   6,  12,   6,   9,   4,   6,   5,   4,
123940        7,   6,   5,   6,   7,   5,   4,   5,   6,   5,   7,   3,   7,
123941       13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   8,   8,
123942        2,   4,   4,   4,   4,   4,   2,   2,   6,   5,   8,   5,   8,
123943        3,   5,   5,   6,   4,   9,   3,
123944   };
123945   static const unsigned short int aOffset[124] = {
123946        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
123947       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
123948       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
123949      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
123950      199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
123951      250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
123952      320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
123953      387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
123954      460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
123955      521, 524, 529, 534, 540, 544, 549,
123956   };
123957   static const unsigned char aCode[124] = {
123958     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
123959     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
123960     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
123961     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
123962     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
123963     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
123964     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
123965     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
123966     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
123967     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_WITHOUT,    TK_WITH,
123968     TK_JOIN_KW,    TK_RELEASE,    TK_ATTACH,     TK_HAVING,     TK_GROUP,
123969     TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RECURSIVE,  TK_BETWEEN,
123970     TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       TK_LIKE_KW,
123971     TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       TK_COLLATE,
123972     TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  TK_JOIN,
123973     TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    TK_PRAGMA,
123974     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      TK_WHEN,
123975     TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    TK_AND,
123976     TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         TK_CAST,
123977     TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    TK_CTIME_KW,
123978     TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   TK_IS,
123979     TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    TK_LIKE_KW,
123980     TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      TK_RESTRICT,
123981     TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        TK_UNION,      TK_USING,
123982     TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  TK_ALL,
123983   };
123984   int h, i;
123985   if( n<2 ) return TK_ID;
123986   h = ((charMap(z[0])*4) ^
123987       (charMap(z[n-1])*3) ^
123988       n) % 127;
123989   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
123990     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
123991       testcase( i==0 ); /* REINDEX */
123992       testcase( i==1 ); /* INDEXED */
123993       testcase( i==2 ); /* INDEX */
123994       testcase( i==3 ); /* DESC */
123995       testcase( i==4 ); /* ESCAPE */
123996       testcase( i==5 ); /* EACH */
123997       testcase( i==6 ); /* CHECK */
123998       testcase( i==7 ); /* KEY */
123999       testcase( i==8 ); /* BEFORE */
124000       testcase( i==9 ); /* FOREIGN */
124001       testcase( i==10 ); /* FOR */
124002       testcase( i==11 ); /* IGNORE */
124003       testcase( i==12 ); /* REGEXP */
124004       testcase( i==13 ); /* EXPLAIN */
124005       testcase( i==14 ); /* INSTEAD */
124006       testcase( i==15 ); /* ADD */
124007       testcase( i==16 ); /* DATABASE */
124008       testcase( i==17 ); /* AS */
124009       testcase( i==18 ); /* SELECT */
124010       testcase( i==19 ); /* TABLE */
124011       testcase( i==20 ); /* LEFT */
124012       testcase( i==21 ); /* THEN */
124013       testcase( i==22 ); /* END */
124014       testcase( i==23 ); /* DEFERRABLE */
124015       testcase( i==24 ); /* ELSE */
124016       testcase( i==25 ); /* EXCEPT */
124017       testcase( i==26 ); /* TRANSACTION */
124018       testcase( i==27 ); /* ACTION */
124019       testcase( i==28 ); /* ON */
124020       testcase( i==29 ); /* NATURAL */
124021       testcase( i==30 ); /* ALTER */
124022       testcase( i==31 ); /* RAISE */
124023       testcase( i==32 ); /* EXCLUSIVE */
124024       testcase( i==33 ); /* EXISTS */
124025       testcase( i==34 ); /* SAVEPOINT */
124026       testcase( i==35 ); /* INTERSECT */
124027       testcase( i==36 ); /* TRIGGER */
124028       testcase( i==37 ); /* REFERENCES */
124029       testcase( i==38 ); /* CONSTRAINT */
124030       testcase( i==39 ); /* INTO */
124031       testcase( i==40 ); /* OFFSET */
124032       testcase( i==41 ); /* OF */
124033       testcase( i==42 ); /* SET */
124034       testcase( i==43 ); /* TEMPORARY */
124035       testcase( i==44 ); /* TEMP */
124036       testcase( i==45 ); /* OR */
124037       testcase( i==46 ); /* UNIQUE */
124038       testcase( i==47 ); /* QUERY */
124039       testcase( i==48 ); /* WITHOUT */
124040       testcase( i==49 ); /* WITH */
124041       testcase( i==50 ); /* OUTER */
124042       testcase( i==51 ); /* RELEASE */
124043       testcase( i==52 ); /* ATTACH */
124044       testcase( i==53 ); /* HAVING */
124045       testcase( i==54 ); /* GROUP */
124046       testcase( i==55 ); /* UPDATE */
124047       testcase( i==56 ); /* BEGIN */
124048       testcase( i==57 ); /* INNER */
124049       testcase( i==58 ); /* RECURSIVE */
124050       testcase( i==59 ); /* BETWEEN */
124051       testcase( i==60 ); /* NOTNULL */
124052       testcase( i==61 ); /* NOT */
124053       testcase( i==62 ); /* NO */
124054       testcase( i==63 ); /* NULL */
124055       testcase( i==64 ); /* LIKE */
124056       testcase( i==65 ); /* CASCADE */
124057       testcase( i==66 ); /* ASC */
124058       testcase( i==67 ); /* DELETE */
124059       testcase( i==68 ); /* CASE */
124060       testcase( i==69 ); /* COLLATE */
124061       testcase( i==70 ); /* CREATE */
124062       testcase( i==71 ); /* CURRENT_DATE */
124063       testcase( i==72 ); /* DETACH */
124064       testcase( i==73 ); /* IMMEDIATE */
124065       testcase( i==74 ); /* JOIN */
124066       testcase( i==75 ); /* INSERT */
124067       testcase( i==76 ); /* MATCH */
124068       testcase( i==77 ); /* PLAN */
124069       testcase( i==78 ); /* ANALYZE */
124070       testcase( i==79 ); /* PRAGMA */
124071       testcase( i==80 ); /* ABORT */
124072       testcase( i==81 ); /* VALUES */
124073       testcase( i==82 ); /* VIRTUAL */
124074       testcase( i==83 ); /* LIMIT */
124075       testcase( i==84 ); /* WHEN */
124076       testcase( i==85 ); /* WHERE */
124077       testcase( i==86 ); /* RENAME */
124078       testcase( i==87 ); /* AFTER */
124079       testcase( i==88 ); /* REPLACE */
124080       testcase( i==89 ); /* AND */
124081       testcase( i==90 ); /* DEFAULT */
124082       testcase( i==91 ); /* AUTOINCREMENT */
124083       testcase( i==92 ); /* TO */
124084       testcase( i==93 ); /* IN */
124085       testcase( i==94 ); /* CAST */
124086       testcase( i==95 ); /* COLUMN */
124087       testcase( i==96 ); /* COMMIT */
124088       testcase( i==97 ); /* CONFLICT */
124089       testcase( i==98 ); /* CROSS */
124090       testcase( i==99 ); /* CURRENT_TIMESTAMP */
124091       testcase( i==100 ); /* CURRENT_TIME */
124092       testcase( i==101 ); /* PRIMARY */
124093       testcase( i==102 ); /* DEFERRED */
124094       testcase( i==103 ); /* DISTINCT */
124095       testcase( i==104 ); /* IS */
124096       testcase( i==105 ); /* DROP */
124097       testcase( i==106 ); /* FAIL */
124098       testcase( i==107 ); /* FROM */
124099       testcase( i==108 ); /* FULL */
124100       testcase( i==109 ); /* GLOB */
124101       testcase( i==110 ); /* BY */
124102       testcase( i==111 ); /* IF */
124103       testcase( i==112 ); /* ISNULL */
124104       testcase( i==113 ); /* ORDER */
124105       testcase( i==114 ); /* RESTRICT */
124106       testcase( i==115 ); /* RIGHT */
124107       testcase( i==116 ); /* ROLLBACK */
124108       testcase( i==117 ); /* ROW */
124109       testcase( i==118 ); /* UNION */
124110       testcase( i==119 ); /* USING */
124111       testcase( i==120 ); /* VACUUM */
124112       testcase( i==121 ); /* VIEW */
124113       testcase( i==122 ); /* INITIALLY */
124114       testcase( i==123 ); /* ALL */
124115       return aCode[i];
124116     }
124117   }
124118   return TK_ID;
124119 }
124120 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
124121   return keywordCode((char*)z, n);
124122 }
124123 #define SQLITE_N_KEYWORD 124
124124 
124125 /************** End of keywordhash.h *****************************************/
124126 /************** Continuing where we left off in tokenize.c *******************/
124127 
124128 
124129 /*
124130 ** If X is a character that can be used in an identifier then
124131 ** IdChar(X) will be true.  Otherwise it is false.
124132 **
124133 ** For ASCII, any character with the high-order bit set is
124134 ** allowed in an identifier.  For 7-bit characters,
124135 ** sqlite3IsIdChar[X] must be 1.
124136 **
124137 ** For EBCDIC, the rules are more complex but have the same
124138 ** end result.
124139 **
124140 ** Ticket #1066.  the SQL standard does not allow '$' in the
124141 ** middle of identifiers.  But many SQL implementations do.
124142 ** SQLite will allow '$' in identifiers for compatibility.
124143 ** But the feature is undocumented.
124144 */
124145 #ifdef SQLITE_ASCII
124146 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
124147 #endif
124148 #ifdef SQLITE_EBCDIC
124149 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
124150 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
124151     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
124152     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
124153     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
124154     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
124155     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
124156     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
124157     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
124158     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
124159     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
124160     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
124161     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
124162     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
124163 };
124164 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
124165 #endif
124166 SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
124167 
124168 
124169 /*
124170 ** Return the length of the token that begins at z[0].
124171 ** Store the token type in *tokenType before returning.
124172 */
124173 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
124174   int i, c;
124175   switch( *z ){
124176     case ' ': case '\t': case '\n': case '\f': case '\r': {
124177       testcase( z[0]==' ' );
124178       testcase( z[0]=='\t' );
124179       testcase( z[0]=='\n' );
124180       testcase( z[0]=='\f' );
124181       testcase( z[0]=='\r' );
124182       for(i=1; sqlite3Isspace(z[i]); i++){}
124183       *tokenType = TK_SPACE;
124184       return i;
124185     }
124186     case '-': {
124187       if( z[1]=='-' ){
124188         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
124189         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
124190         return i;
124191       }
124192       *tokenType = TK_MINUS;
124193       return 1;
124194     }
124195     case '(': {
124196       *tokenType = TK_LP;
124197       return 1;
124198     }
124199     case ')': {
124200       *tokenType = TK_RP;
124201       return 1;
124202     }
124203     case ';': {
124204       *tokenType = TK_SEMI;
124205       return 1;
124206     }
124207     case '+': {
124208       *tokenType = TK_PLUS;
124209       return 1;
124210     }
124211     case '*': {
124212       *tokenType = TK_STAR;
124213       return 1;
124214     }
124215     case '/': {
124216       if( z[1]!='*' || z[2]==0 ){
124217         *tokenType = TK_SLASH;
124218         return 1;
124219       }
124220       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
124221       if( c ) i++;
124222       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
124223       return i;
124224     }
124225     case '%': {
124226       *tokenType = TK_REM;
124227       return 1;
124228     }
124229     case '=': {
124230       *tokenType = TK_EQ;
124231       return 1 + (z[1]=='=');
124232     }
124233     case '<': {
124234       if( (c=z[1])=='=' ){
124235         *tokenType = TK_LE;
124236         return 2;
124237       }else if( c=='>' ){
124238         *tokenType = TK_NE;
124239         return 2;
124240       }else if( c=='<' ){
124241         *tokenType = TK_LSHIFT;
124242         return 2;
124243       }else{
124244         *tokenType = TK_LT;
124245         return 1;
124246       }
124247     }
124248     case '>': {
124249       if( (c=z[1])=='=' ){
124250         *tokenType = TK_GE;
124251         return 2;
124252       }else if( c=='>' ){
124253         *tokenType = TK_RSHIFT;
124254         return 2;
124255       }else{
124256         *tokenType = TK_GT;
124257         return 1;
124258       }
124259     }
124260     case '!': {
124261       if( z[1]!='=' ){
124262         *tokenType = TK_ILLEGAL;
124263         return 2;
124264       }else{
124265         *tokenType = TK_NE;
124266         return 2;
124267       }
124268     }
124269     case '|': {
124270       if( z[1]!='|' ){
124271         *tokenType = TK_BITOR;
124272         return 1;
124273       }else{
124274         *tokenType = TK_CONCAT;
124275         return 2;
124276       }
124277     }
124278     case ',': {
124279       *tokenType = TK_COMMA;
124280       return 1;
124281     }
124282     case '&': {
124283       *tokenType = TK_BITAND;
124284       return 1;
124285     }
124286     case '~': {
124287       *tokenType = TK_BITNOT;
124288       return 1;
124289     }
124290     case '`':
124291     case '\'':
124292     case '"': {
124293       int delim = z[0];
124294       testcase( delim=='`' );
124295       testcase( delim=='\'' );
124296       testcase( delim=='"' );
124297       for(i=1; (c=z[i])!=0; i++){
124298         if( c==delim ){
124299           if( z[i+1]==delim ){
124300             i++;
124301           }else{
124302             break;
124303           }
124304         }
124305       }
124306       if( c=='\'' ){
124307         *tokenType = TK_STRING;
124308         return i+1;
124309       }else if( c!=0 ){
124310         *tokenType = TK_ID;
124311         return i+1;
124312       }else{
124313         *tokenType = TK_ILLEGAL;
124314         return i;
124315       }
124316     }
124317     case '.': {
124318 #ifndef SQLITE_OMIT_FLOATING_POINT
124319       if( !sqlite3Isdigit(z[1]) )
124320 #endif
124321       {
124322         *tokenType = TK_DOT;
124323         return 1;
124324       }
124325       /* If the next character is a digit, this is a floating point
124326       ** number that begins with ".".  Fall thru into the next case */
124327     }
124328     case '0': case '1': case '2': case '3': case '4':
124329     case '5': case '6': case '7': case '8': case '9': {
124330       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
124331       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
124332       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
124333       testcase( z[0]=='9' );
124334       *tokenType = TK_INTEGER;
124335 #ifndef SQLITE_OMIT_HEX_INTEGER
124336       if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
124337         for(i=3; sqlite3Isxdigit(z[i]); i++){}
124338         return i;
124339       }
124340 #endif
124341       for(i=0; sqlite3Isdigit(z[i]); i++){}
124342 #ifndef SQLITE_OMIT_FLOATING_POINT
124343       if( z[i]=='.' ){
124344         i++;
124345         while( sqlite3Isdigit(z[i]) ){ i++; }
124346         *tokenType = TK_FLOAT;
124347       }
124348       if( (z[i]=='e' || z[i]=='E') &&
124349            ( sqlite3Isdigit(z[i+1])
124350             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
124351            )
124352       ){
124353         i += 2;
124354         while( sqlite3Isdigit(z[i]) ){ i++; }
124355         *tokenType = TK_FLOAT;
124356       }
124357 #endif
124358       while( IdChar(z[i]) ){
124359         *tokenType = TK_ILLEGAL;
124360         i++;
124361       }
124362       return i;
124363     }
124364     case '[': {
124365       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
124366       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
124367       return i;
124368     }
124369     case '?': {
124370       *tokenType = TK_VARIABLE;
124371       for(i=1; sqlite3Isdigit(z[i]); i++){}
124372       return i;
124373     }
124374 #ifndef SQLITE_OMIT_TCL_VARIABLE
124375     case '$':
124376 #endif
124377     case '@':  /* For compatibility with MS SQL Server */
124378     case '#':
124379     case ':': {
124380       int n = 0;
124381       testcase( z[0]=='$' );  testcase( z[0]=='@' );
124382       testcase( z[0]==':' );  testcase( z[0]=='#' );
124383       *tokenType = TK_VARIABLE;
124384       for(i=1; (c=z[i])!=0; i++){
124385         if( IdChar(c) ){
124386           n++;
124387 #ifndef SQLITE_OMIT_TCL_VARIABLE
124388         }else if( c=='(' && n>0 ){
124389           do{
124390             i++;
124391           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
124392           if( c==')' ){
124393             i++;
124394           }else{
124395             *tokenType = TK_ILLEGAL;
124396           }
124397           break;
124398         }else if( c==':' && z[i+1]==':' ){
124399           i++;
124400 #endif
124401         }else{
124402           break;
124403         }
124404       }
124405       if( n==0 ) *tokenType = TK_ILLEGAL;
124406       return i;
124407     }
124408 #ifndef SQLITE_OMIT_BLOB_LITERAL
124409     case 'x': case 'X': {
124410       testcase( z[0]=='x' ); testcase( z[0]=='X' );
124411       if( z[1]=='\'' ){
124412         *tokenType = TK_BLOB;
124413         for(i=2; sqlite3Isxdigit(z[i]); i++){}
124414         if( z[i]!='\'' || i%2 ){
124415           *tokenType = TK_ILLEGAL;
124416           while( z[i] && z[i]!='\'' ){ i++; }
124417         }
124418         if( z[i] ) i++;
124419         return i;
124420       }
124421       /* Otherwise fall through to the next case */
124422     }
124423 #endif
124424     default: {
124425       if( !IdChar(*z) ){
124426         break;
124427       }
124428       for(i=1; IdChar(z[i]); i++){}
124429       *tokenType = keywordCode((char*)z, i);
124430       return i;
124431     }
124432   }
124433   *tokenType = TK_ILLEGAL;
124434   return 1;
124435 }
124436 
124437 /*
124438 ** Run the parser on the given SQL string.  The parser structure is
124439 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
124440 ** then an and attempt is made to write an error message into
124441 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
124442 ** error message.
124443 */
124444 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
124445   int nErr = 0;                   /* Number of errors encountered */
124446   int i;                          /* Loop counter */
124447   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
124448   int tokenType;                  /* type of the next token */
124449   int lastTokenParsed = -1;       /* type of the previous token */
124450   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
124451   sqlite3 *db = pParse->db;       /* The database connection */
124452   int mxSqlLen;                   /* Max length of an SQL string */
124453 
124454 
124455   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
124456   if( db->nVdbeActive==0 ){
124457     db->u1.isInterrupted = 0;
124458   }
124459   pParse->rc = SQLITE_OK;
124460   pParse->zTail = zSql;
124461   i = 0;
124462   assert( pzErrMsg!=0 );
124463   pEngine = sqlite3ParserAlloc(sqlite3Malloc);
124464   if( pEngine==0 ){
124465     db->mallocFailed = 1;
124466     return SQLITE_NOMEM;
124467   }
124468   assert( pParse->pNewTable==0 );
124469   assert( pParse->pNewTrigger==0 );
124470   assert( pParse->nVar==0 );
124471   assert( pParse->nzVar==0 );
124472   assert( pParse->azVar==0 );
124473   enableLookaside = db->lookaside.bEnabled;
124474   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
124475   while( !db->mallocFailed && zSql[i]!=0 ){
124476     assert( i>=0 );
124477     pParse->sLastToken.z = &zSql[i];
124478     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
124479     i += pParse->sLastToken.n;
124480     if( i>mxSqlLen ){
124481       pParse->rc = SQLITE_TOOBIG;
124482       break;
124483     }
124484     switch( tokenType ){
124485       case TK_SPACE: {
124486         if( db->u1.isInterrupted ){
124487           sqlite3ErrorMsg(pParse, "interrupt");
124488           pParse->rc = SQLITE_INTERRUPT;
124489           goto abort_parse;
124490         }
124491         break;
124492       }
124493       case TK_ILLEGAL: {
124494         sqlite3DbFree(db, *pzErrMsg);
124495         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
124496                         &pParse->sLastToken);
124497         nErr++;
124498         goto abort_parse;
124499       }
124500       case TK_SEMI: {
124501         pParse->zTail = &zSql[i];
124502         /* Fall thru into the default case */
124503       }
124504       default: {
124505         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
124506         lastTokenParsed = tokenType;
124507         if( pParse->rc!=SQLITE_OK ){
124508           goto abort_parse;
124509         }
124510         break;
124511       }
124512     }
124513   }
124514 abort_parse:
124515   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
124516     if( lastTokenParsed!=TK_SEMI ){
124517       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
124518       pParse->zTail = &zSql[i];
124519     }
124520     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
124521   }
124522 #ifdef YYTRACKMAXSTACKDEPTH
124523   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
124524       sqlite3ParserStackPeak(pEngine)
124525   );
124526 #endif /* YYDEBUG */
124527   sqlite3ParserFree(pEngine, sqlite3_free);
124528   db->lookaside.bEnabled = enableLookaside;
124529   if( db->mallocFailed ){
124530     pParse->rc = SQLITE_NOMEM;
124531   }
124532   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
124533     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
124534   }
124535   assert( pzErrMsg!=0 );
124536   if( pParse->zErrMsg ){
124537     *pzErrMsg = pParse->zErrMsg;
124538     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
124539     pParse->zErrMsg = 0;
124540     nErr++;
124541   }
124542   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
124543     sqlite3VdbeDelete(pParse->pVdbe);
124544     pParse->pVdbe = 0;
124545   }
124546 #ifndef SQLITE_OMIT_SHARED_CACHE
124547   if( pParse->nested==0 ){
124548     sqlite3DbFree(db, pParse->aTableLock);
124549     pParse->aTableLock = 0;
124550     pParse->nTableLock = 0;
124551   }
124552 #endif
124553 #ifndef SQLITE_OMIT_VIRTUALTABLE
124554   sqlite3_free(pParse->apVtabLock);
124555 #endif
124556 
124557   if( !IN_DECLARE_VTAB ){
124558     /* If the pParse->declareVtab flag is set, do not delete any table
124559     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
124560     ** will take responsibility for freeing the Table structure.
124561     */
124562     sqlite3DeleteTable(db, pParse->pNewTable);
124563   }
124564 
124565   if( pParse->bFreeWith ) sqlite3WithDelete(db, pParse->pWith);
124566   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
124567   for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
124568   sqlite3DbFree(db, pParse->azVar);
124569   while( pParse->pAinc ){
124570     AutoincInfo *p = pParse->pAinc;
124571     pParse->pAinc = p->pNext;
124572     sqlite3DbFree(db, p);
124573   }
124574   while( pParse->pZombieTab ){
124575     Table *p = pParse->pZombieTab;
124576     pParse->pZombieTab = p->pNextZombie;
124577     sqlite3DeleteTable(db, p);
124578   }
124579   if( nErr>0 && pParse->rc==SQLITE_OK ){
124580     pParse->rc = SQLITE_ERROR;
124581   }
124582   return nErr;
124583 }
124584 
124585 /************** End of tokenize.c ********************************************/
124586 /************** Begin file complete.c ****************************************/
124587 /*
124588 ** 2001 September 15
124589 **
124590 ** The author disclaims copyright to this source code.  In place of
124591 ** a legal notice, here is a blessing:
124592 **
124593 **    May you do good and not evil.
124594 **    May you find forgiveness for yourself and forgive others.
124595 **    May you share freely, never taking more than you give.
124596 **
124597 *************************************************************************
124598 ** An tokenizer for SQL
124599 **
124600 ** This file contains C code that implements the sqlite3_complete() API.
124601 ** This code used to be part of the tokenizer.c source file.  But by
124602 ** separating it out, the code will be automatically omitted from
124603 ** static links that do not use it.
124604 */
124605 #ifndef SQLITE_OMIT_COMPLETE
124606 
124607 /*
124608 ** This is defined in tokenize.c.  We just have to import the definition.
124609 */
124610 #ifndef SQLITE_AMALGAMATION
124611 #ifdef SQLITE_ASCII
124612 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
124613 #endif
124614 #ifdef SQLITE_EBCDIC
124615 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
124616 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
124617 #endif
124618 #endif /* SQLITE_AMALGAMATION */
124619 
124620 
124621 /*
124622 ** Token types used by the sqlite3_complete() routine.  See the header
124623 ** comments on that procedure for additional information.
124624 */
124625 #define tkSEMI    0
124626 #define tkWS      1
124627 #define tkOTHER   2
124628 #ifndef SQLITE_OMIT_TRIGGER
124629 #define tkEXPLAIN 3
124630 #define tkCREATE  4
124631 #define tkTEMP    5
124632 #define tkTRIGGER 6
124633 #define tkEND     7
124634 #endif
124635 
124636 /*
124637 ** Return TRUE if the given SQL string ends in a semicolon.
124638 **
124639 ** Special handling is require for CREATE TRIGGER statements.
124640 ** Whenever the CREATE TRIGGER keywords are seen, the statement
124641 ** must end with ";END;".
124642 **
124643 ** This implementation uses a state machine with 8 states:
124644 **
124645 **   (0) INVALID   We have not yet seen a non-whitespace character.
124646 **
124647 **   (1) START     At the beginning or end of an SQL statement.  This routine
124648 **                 returns 1 if it ends in the START state and 0 if it ends
124649 **                 in any other state.
124650 **
124651 **   (2) NORMAL    We are in the middle of statement which ends with a single
124652 **                 semicolon.
124653 **
124654 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
124655 **                 a statement.
124656 **
124657 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
124658 **                 statement, possibly preceded by EXPLAIN and/or followed by
124659 **                 TEMP or TEMPORARY
124660 **
124661 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
124662 **                 ended by a semicolon, the keyword END, and another semicolon.
124663 **
124664 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
124665 **                 the end of a trigger definition.
124666 **
124667 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
124668 **                 of a trigger definition.
124669 **
124670 ** Transitions between states above are determined by tokens extracted
124671 ** from the input.  The following tokens are significant:
124672 **
124673 **   (0) tkSEMI      A semicolon.
124674 **   (1) tkWS        Whitespace.
124675 **   (2) tkOTHER     Any other SQL token.
124676 **   (3) tkEXPLAIN   The "explain" keyword.
124677 **   (4) tkCREATE    The "create" keyword.
124678 **   (5) tkTEMP      The "temp" or "temporary" keyword.
124679 **   (6) tkTRIGGER   The "trigger" keyword.
124680 **   (7) tkEND       The "end" keyword.
124681 **
124682 ** Whitespace never causes a state transition and is always ignored.
124683 ** This means that a SQL string of all whitespace is invalid.
124684 **
124685 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
124686 ** to recognize the end of a trigger can be omitted.  All we have to do
124687 ** is look for a semicolon that is not part of an string or comment.
124688 */
124689 SQLITE_API int sqlite3_complete(const char *zSql){
124690   u8 state = 0;   /* Current state, using numbers defined in header comment */
124691   u8 token;       /* Value of the next token */
124692 
124693 #ifndef SQLITE_OMIT_TRIGGER
124694   /* A complex statement machine used to detect the end of a CREATE TRIGGER
124695   ** statement.  This is the normal case.
124696   */
124697   static const u8 trans[8][8] = {
124698                      /* Token:                                                */
124699      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
124700      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
124701      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
124702      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
124703      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
124704      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
124705      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
124706      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
124707      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
124708   };
124709 #else
124710   /* If triggers are not supported by this compile then the statement machine
124711   ** used to detect the end of a statement is much simpler
124712   */
124713   static const u8 trans[3][3] = {
124714                      /* Token:           */
124715      /* State:       **  SEMI  WS  OTHER */
124716      /* 0 INVALID: */ {    1,  0,     2, },
124717      /* 1   START: */ {    1,  1,     2, },
124718      /* 2  NORMAL: */ {    1,  2,     2, },
124719   };
124720 #endif /* SQLITE_OMIT_TRIGGER */
124721 
124722   while( *zSql ){
124723     switch( *zSql ){
124724       case ';': {  /* A semicolon */
124725         token = tkSEMI;
124726         break;
124727       }
124728       case ' ':
124729       case '\r':
124730       case '\t':
124731       case '\n':
124732       case '\f': {  /* White space is ignored */
124733         token = tkWS;
124734         break;
124735       }
124736       case '/': {   /* C-style comments */
124737         if( zSql[1]!='*' ){
124738           token = tkOTHER;
124739           break;
124740         }
124741         zSql += 2;
124742         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
124743         if( zSql[0]==0 ) return 0;
124744         zSql++;
124745         token = tkWS;
124746         break;
124747       }
124748       case '-': {   /* SQL-style comments from "--" to end of line */
124749         if( zSql[1]!='-' ){
124750           token = tkOTHER;
124751           break;
124752         }
124753         while( *zSql && *zSql!='\n' ){ zSql++; }
124754         if( *zSql==0 ) return state==1;
124755         token = tkWS;
124756         break;
124757       }
124758       case '[': {   /* Microsoft-style identifiers in [...] */
124759         zSql++;
124760         while( *zSql && *zSql!=']' ){ zSql++; }
124761         if( *zSql==0 ) return 0;
124762         token = tkOTHER;
124763         break;
124764       }
124765       case '`':     /* Grave-accent quoted symbols used by MySQL */
124766       case '"':     /* single- and double-quoted strings */
124767       case '\'': {
124768         int c = *zSql;
124769         zSql++;
124770         while( *zSql && *zSql!=c ){ zSql++; }
124771         if( *zSql==0 ) return 0;
124772         token = tkOTHER;
124773         break;
124774       }
124775       default: {
124776 #ifdef SQLITE_EBCDIC
124777         unsigned char c;
124778 #endif
124779         if( IdChar((u8)*zSql) ){
124780           /* Keywords and unquoted identifiers */
124781           int nId;
124782           for(nId=1; IdChar(zSql[nId]); nId++){}
124783 #ifdef SQLITE_OMIT_TRIGGER
124784           token = tkOTHER;
124785 #else
124786           switch( *zSql ){
124787             case 'c': case 'C': {
124788               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
124789                 token = tkCREATE;
124790               }else{
124791                 token = tkOTHER;
124792               }
124793               break;
124794             }
124795             case 't': case 'T': {
124796               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
124797                 token = tkTRIGGER;
124798               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
124799                 token = tkTEMP;
124800               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
124801                 token = tkTEMP;
124802               }else{
124803                 token = tkOTHER;
124804               }
124805               break;
124806             }
124807             case 'e':  case 'E': {
124808               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
124809                 token = tkEND;
124810               }else
124811 #ifndef SQLITE_OMIT_EXPLAIN
124812               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
124813                 token = tkEXPLAIN;
124814               }else
124815 #endif
124816               {
124817                 token = tkOTHER;
124818               }
124819               break;
124820             }
124821             default: {
124822               token = tkOTHER;
124823               break;
124824             }
124825           }
124826 #endif /* SQLITE_OMIT_TRIGGER */
124827           zSql += nId-1;
124828         }else{
124829           /* Operators and special symbols */
124830           token = tkOTHER;
124831         }
124832         break;
124833       }
124834     }
124835     state = trans[state][token];
124836     zSql++;
124837   }
124838   return state==1;
124839 }
124840 
124841 #ifndef SQLITE_OMIT_UTF16
124842 /*
124843 ** This routine is the same as the sqlite3_complete() routine described
124844 ** above, except that the parameter is required to be UTF-16 encoded, not
124845 ** UTF-8.
124846 */
124847 SQLITE_API int sqlite3_complete16(const void *zSql){
124848   sqlite3_value *pVal;
124849   char const *zSql8;
124850   int rc = SQLITE_NOMEM;
124851 
124852 #ifndef SQLITE_OMIT_AUTOINIT
124853   rc = sqlite3_initialize();
124854   if( rc ) return rc;
124855 #endif
124856   pVal = sqlite3ValueNew(0);
124857   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
124858   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
124859   if( zSql8 ){
124860     rc = sqlite3_complete(zSql8);
124861   }else{
124862     rc = SQLITE_NOMEM;
124863   }
124864   sqlite3ValueFree(pVal);
124865   return sqlite3ApiExit(0, rc);
124866 }
124867 #endif /* SQLITE_OMIT_UTF16 */
124868 #endif /* SQLITE_OMIT_COMPLETE */
124869 
124870 /************** End of complete.c ********************************************/
124871 /************** Begin file main.c ********************************************/
124872 /*
124873 ** 2001 September 15
124874 **
124875 ** The author disclaims copyright to this source code.  In place of
124876 ** a legal notice, here is a blessing:
124877 **
124878 **    May you do good and not evil.
124879 **    May you find forgiveness for yourself and forgive others.
124880 **    May you share freely, never taking more than you give.
124881 **
124882 *************************************************************************
124883 ** Main file for the SQLite library.  The routines in this file
124884 ** implement the programmer interface to the library.  Routines in
124885 ** other files are for internal use by SQLite and should not be
124886 ** accessed by users of the library.
124887 */
124888 
124889 #ifdef SQLITE_ENABLE_FTS3
124890 /************** Include fts3.h in the middle of main.c ***********************/
124891 /************** Begin file fts3.h ********************************************/
124892 /*
124893 ** 2006 Oct 10
124894 **
124895 ** The author disclaims copyright to this source code.  In place of
124896 ** a legal notice, here is a blessing:
124897 **
124898 **    May you do good and not evil.
124899 **    May you find forgiveness for yourself and forgive others.
124900 **    May you share freely, never taking more than you give.
124901 **
124902 ******************************************************************************
124903 **
124904 ** This header file is used by programs that want to link against the
124905 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
124906 */
124907 
124908 #if 0
124909 extern "C" {
124910 #endif  /* __cplusplus */
124911 
124912 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
124913 
124914 #if 0
124915 }  /* extern "C" */
124916 #endif  /* __cplusplus */
124917 
124918 /************** End of fts3.h ************************************************/
124919 /************** Continuing where we left off in main.c ***********************/
124920 #endif
124921 #ifdef SQLITE_ENABLE_RTREE
124922 /************** Include rtree.h in the middle of main.c **********************/
124923 /************** Begin file rtree.h *******************************************/
124924 /*
124925 ** 2008 May 26
124926 **
124927 ** The author disclaims copyright to this source code.  In place of
124928 ** a legal notice, here is a blessing:
124929 **
124930 **    May you do good and not evil.
124931 **    May you find forgiveness for yourself and forgive others.
124932 **    May you share freely, never taking more than you give.
124933 **
124934 ******************************************************************************
124935 **
124936 ** This header file is used by programs that want to link against the
124937 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
124938 */
124939 
124940 #if 0
124941 extern "C" {
124942 #endif  /* __cplusplus */
124943 
124944 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
124945 
124946 #if 0
124947 }  /* extern "C" */
124948 #endif  /* __cplusplus */
124949 
124950 /************** End of rtree.h ***********************************************/
124951 /************** Continuing where we left off in main.c ***********************/
124952 #endif
124953 #ifdef SQLITE_ENABLE_ICU
124954 /************** Include sqliteicu.h in the middle of main.c ******************/
124955 /************** Begin file sqliteicu.h ***************************************/
124956 /*
124957 ** 2008 May 26
124958 **
124959 ** The author disclaims copyright to this source code.  In place of
124960 ** a legal notice, here is a blessing:
124961 **
124962 **    May you do good and not evil.
124963 **    May you find forgiveness for yourself and forgive others.
124964 **    May you share freely, never taking more than you give.
124965 **
124966 ******************************************************************************
124967 **
124968 ** This header file is used by programs that want to link against the
124969 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
124970 */
124971 
124972 #if 0
124973 extern "C" {
124974 #endif  /* __cplusplus */
124975 
124976 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
124977 
124978 #if 0
124979 }  /* extern "C" */
124980 #endif  /* __cplusplus */
124981 
124982 
124983 /************** End of sqliteicu.h *******************************************/
124984 /************** Continuing where we left off in main.c ***********************/
124985 #endif
124986 
124987 #ifndef SQLITE_AMALGAMATION
124988 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
124989 ** contains the text of SQLITE_VERSION macro.
124990 */
124991 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
124992 #endif
124993 
124994 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
124995 ** a pointer to the to the sqlite3_version[] string constant.
124996 */
124997 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
124998 
124999 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
125000 ** pointer to a string constant whose value is the same as the
125001 ** SQLITE_SOURCE_ID C preprocessor macro.
125002 */
125003 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
125004 
125005 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
125006 ** returns an integer equal to SQLITE_VERSION_NUMBER.
125007 */
125008 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
125009 
125010 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
125011 ** zero if and only if SQLite was compiled with mutexing code omitted due to
125012 ** the SQLITE_THREADSAFE compile-time option being set to 0.
125013 */
125014 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
125015 
125016 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
125017 /*
125018 ** If the following function pointer is not NULL and if
125019 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
125020 ** I/O active are written using this function.  These messages
125021 ** are intended for debugging activity only.
125022 */
125023 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
125024 #endif
125025 
125026 /*
125027 ** If the following global variable points to a string which is the
125028 ** name of a directory, then that directory will be used to store
125029 ** temporary files.
125030 **
125031 ** See also the "PRAGMA temp_store_directory" SQL command.
125032 */
125033 SQLITE_API char *sqlite3_temp_directory = 0;
125034 
125035 /*
125036 ** If the following global variable points to a string which is the
125037 ** name of a directory, then that directory will be used to store
125038 ** all database files specified with a relative pathname.
125039 **
125040 ** See also the "PRAGMA data_store_directory" SQL command.
125041 */
125042 SQLITE_API char *sqlite3_data_directory = 0;
125043 
125044 /*
125045 ** Initialize SQLite.
125046 **
125047 ** This routine must be called to initialize the memory allocation,
125048 ** VFS, and mutex subsystems prior to doing any serious work with
125049 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
125050 ** this routine will be called automatically by key routines such as
125051 ** sqlite3_open().
125052 **
125053 ** This routine is a no-op except on its very first call for the process,
125054 ** or for the first call after a call to sqlite3_shutdown.
125055 **
125056 ** The first thread to call this routine runs the initialization to
125057 ** completion.  If subsequent threads call this routine before the first
125058 ** thread has finished the initialization process, then the subsequent
125059 ** threads must block until the first thread finishes with the initialization.
125060 **
125061 ** The first thread might call this routine recursively.  Recursive
125062 ** calls to this routine should not block, of course.  Otherwise the
125063 ** initialization process would never complete.
125064 **
125065 ** Let X be the first thread to enter this routine.  Let Y be some other
125066 ** thread.  Then while the initial invocation of this routine by X is
125067 ** incomplete, it is required that:
125068 **
125069 **    *  Calls to this routine from Y must block until the outer-most
125070 **       call by X completes.
125071 **
125072 **    *  Recursive calls to this routine from thread X return immediately
125073 **       without blocking.
125074 */
125075 SQLITE_API int sqlite3_initialize(void){
125076   MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
125077   int rc;                                      /* Result code */
125078 #ifdef SQLITE_EXTRA_INIT
125079   int bRunExtraInit = 0;                       /* Extra initialization needed */
125080 #endif
125081 
125082 #ifdef SQLITE_OMIT_WSD
125083   rc = sqlite3_wsd_init(4096, 24);
125084   if( rc!=SQLITE_OK ){
125085     return rc;
125086   }
125087 #endif
125088 
125089   /* If SQLite is already completely initialized, then this call
125090   ** to sqlite3_initialize() should be a no-op.  But the initialization
125091   ** must be complete.  So isInit must not be set until the very end
125092   ** of this routine.
125093   */
125094   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
125095 
125096   /* Make sure the mutex subsystem is initialized.  If unable to
125097   ** initialize the mutex subsystem, return early with the error.
125098   ** If the system is so sick that we are unable to allocate a mutex,
125099   ** there is not much SQLite is going to be able to do.
125100   **
125101   ** The mutex subsystem must take care of serializing its own
125102   ** initialization.
125103   */
125104   rc = sqlite3MutexInit();
125105   if( rc ) return rc;
125106 
125107   /* Initialize the malloc() system and the recursive pInitMutex mutex.
125108   ** This operation is protected by the STATIC_MASTER mutex.  Note that
125109   ** MutexAlloc() is called for a static mutex prior to initializing the
125110   ** malloc subsystem - this implies that the allocation of a static
125111   ** mutex must not require support from the malloc subsystem.
125112   */
125113   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
125114   sqlite3_mutex_enter(pMaster);
125115   sqlite3GlobalConfig.isMutexInit = 1;
125116   if( !sqlite3GlobalConfig.isMallocInit ){
125117     rc = sqlite3MallocInit();
125118   }
125119   if( rc==SQLITE_OK ){
125120     sqlite3GlobalConfig.isMallocInit = 1;
125121     if( !sqlite3GlobalConfig.pInitMutex ){
125122       sqlite3GlobalConfig.pInitMutex =
125123            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
125124       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
125125         rc = SQLITE_NOMEM;
125126       }
125127     }
125128   }
125129   if( rc==SQLITE_OK ){
125130     sqlite3GlobalConfig.nRefInitMutex++;
125131   }
125132   sqlite3_mutex_leave(pMaster);
125133 
125134   /* If rc is not SQLITE_OK at this point, then either the malloc
125135   ** subsystem could not be initialized or the system failed to allocate
125136   ** the pInitMutex mutex. Return an error in either case.  */
125137   if( rc!=SQLITE_OK ){
125138     return rc;
125139   }
125140 
125141   /* Do the rest of the initialization under the recursive mutex so
125142   ** that we will be able to handle recursive calls into
125143   ** sqlite3_initialize().  The recursive calls normally come through
125144   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
125145   ** recursive calls might also be possible.
125146   **
125147   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
125148   ** to the xInit method, so the xInit method need not be threadsafe.
125149   **
125150   ** The following mutex is what serializes access to the appdef pcache xInit
125151   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
125152   ** call to sqlite3PcacheInitialize().
125153   */
125154   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
125155   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
125156     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
125157     sqlite3GlobalConfig.inProgress = 1;
125158     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
125159     sqlite3RegisterGlobalFunctions();
125160     if( sqlite3GlobalConfig.isPCacheInit==0 ){
125161       rc = sqlite3PcacheInitialize();
125162     }
125163     if( rc==SQLITE_OK ){
125164       sqlite3GlobalConfig.isPCacheInit = 1;
125165       rc = sqlite3OsInit();
125166     }
125167     if( rc==SQLITE_OK ){
125168       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
125169           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
125170       sqlite3GlobalConfig.isInit = 1;
125171 #ifdef SQLITE_EXTRA_INIT
125172       bRunExtraInit = 1;
125173 #endif
125174     }
125175     sqlite3GlobalConfig.inProgress = 0;
125176   }
125177   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
125178 
125179   /* Go back under the static mutex and clean up the recursive
125180   ** mutex to prevent a resource leak.
125181   */
125182   sqlite3_mutex_enter(pMaster);
125183   sqlite3GlobalConfig.nRefInitMutex--;
125184   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
125185     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
125186     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
125187     sqlite3GlobalConfig.pInitMutex = 0;
125188   }
125189   sqlite3_mutex_leave(pMaster);
125190 
125191   /* The following is just a sanity check to make sure SQLite has
125192   ** been compiled correctly.  It is important to run this code, but
125193   ** we don't want to run it too often and soak up CPU cycles for no
125194   ** reason.  So we run it once during initialization.
125195   */
125196 #ifndef NDEBUG
125197 #ifndef SQLITE_OMIT_FLOATING_POINT
125198   /* This section of code's only "output" is via assert() statements. */
125199   if ( rc==SQLITE_OK ){
125200     u64 x = (((u64)1)<<63)-1;
125201     double y;
125202     assert(sizeof(x)==8);
125203     assert(sizeof(x)==sizeof(y));
125204     memcpy(&y, &x, 8);
125205     assert( sqlite3IsNaN(y) );
125206   }
125207 #endif
125208 #endif
125209 
125210   /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
125211   ** compile-time option.
125212   */
125213 #ifdef SQLITE_EXTRA_INIT
125214   if( bRunExtraInit ){
125215     int SQLITE_EXTRA_INIT(const char*);
125216     rc = SQLITE_EXTRA_INIT(0);
125217   }
125218 #endif
125219 
125220   return rc;
125221 }
125222 
125223 /*
125224 ** Undo the effects of sqlite3_initialize().  Must not be called while
125225 ** there are outstanding database connections or memory allocations or
125226 ** while any part of SQLite is otherwise in use in any thread.  This
125227 ** routine is not threadsafe.  But it is safe to invoke this routine
125228 ** on when SQLite is already shut down.  If SQLite is already shut down
125229 ** when this routine is invoked, then this routine is a harmless no-op.
125230 */
125231 SQLITE_API int sqlite3_shutdown(void){
125232   if( sqlite3GlobalConfig.isInit ){
125233 #ifdef SQLITE_EXTRA_SHUTDOWN
125234     void SQLITE_EXTRA_SHUTDOWN(void);
125235     SQLITE_EXTRA_SHUTDOWN();
125236 #endif
125237     sqlite3_os_end();
125238     sqlite3_reset_auto_extension();
125239     sqlite3GlobalConfig.isInit = 0;
125240   }
125241   if( sqlite3GlobalConfig.isPCacheInit ){
125242     sqlite3PcacheShutdown();
125243     sqlite3GlobalConfig.isPCacheInit = 0;
125244   }
125245   if( sqlite3GlobalConfig.isMallocInit ){
125246     sqlite3MallocEnd();
125247     sqlite3GlobalConfig.isMallocInit = 0;
125248 
125249 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
125250     /* The heap subsystem has now been shutdown and these values are supposed
125251     ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
125252     ** which would rely on that heap subsystem; therefore, make sure these
125253     ** values cannot refer to heap memory that was just invalidated when the
125254     ** heap subsystem was shutdown.  This is only done if the current call to
125255     ** this function resulted in the heap subsystem actually being shutdown.
125256     */
125257     sqlite3_data_directory = 0;
125258     sqlite3_temp_directory = 0;
125259 #endif
125260   }
125261   if( sqlite3GlobalConfig.isMutexInit ){
125262     sqlite3MutexEnd();
125263     sqlite3GlobalConfig.isMutexInit = 0;
125264   }
125265 
125266   return SQLITE_OK;
125267 }
125268 
125269 /*
125270 ** This API allows applications to modify the global configuration of
125271 ** the SQLite library at run-time.
125272 **
125273 ** This routine should only be called when there are no outstanding
125274 ** database connections or memory allocations.  This routine is not
125275 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
125276 ** behavior.
125277 */
125278 SQLITE_API int sqlite3_config(int op, ...){
125279   va_list ap;
125280   int rc = SQLITE_OK;
125281 
125282   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
125283   ** the SQLite library is in use. */
125284   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
125285 
125286   va_start(ap, op);
125287   switch( op ){
125288 
125289     /* Mutex configuration options are only available in a threadsafe
125290     ** compile.
125291     */
125292 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
125293     case SQLITE_CONFIG_SINGLETHREAD: {
125294       /* Disable all mutexing */
125295       sqlite3GlobalConfig.bCoreMutex = 0;
125296       sqlite3GlobalConfig.bFullMutex = 0;
125297       break;
125298     }
125299     case SQLITE_CONFIG_MULTITHREAD: {
125300       /* Disable mutexing of database connections */
125301       /* Enable mutexing of core data structures */
125302       sqlite3GlobalConfig.bCoreMutex = 1;
125303       sqlite3GlobalConfig.bFullMutex = 0;
125304       break;
125305     }
125306     case SQLITE_CONFIG_SERIALIZED: {
125307       /* Enable all mutexing */
125308       sqlite3GlobalConfig.bCoreMutex = 1;
125309       sqlite3GlobalConfig.bFullMutex = 1;
125310       break;
125311     }
125312     case SQLITE_CONFIG_MUTEX: {
125313       /* Specify an alternative mutex implementation */
125314       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
125315       break;
125316     }
125317     case SQLITE_CONFIG_GETMUTEX: {
125318       /* Retrieve the current mutex implementation */
125319       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
125320       break;
125321     }
125322 #endif
125323 
125324 
125325     case SQLITE_CONFIG_MALLOC: {
125326       /* Specify an alternative malloc implementation */
125327       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
125328       break;
125329     }
125330     case SQLITE_CONFIG_GETMALLOC: {
125331       /* Retrieve the current malloc() implementation */
125332       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
125333       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
125334       break;
125335     }
125336     case SQLITE_CONFIG_MEMSTATUS: {
125337       /* Enable or disable the malloc status collection */
125338       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
125339       break;
125340     }
125341     case SQLITE_CONFIG_SCRATCH: {
125342       /* Designate a buffer for scratch memory space */
125343       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
125344       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
125345       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
125346       break;
125347     }
125348     case SQLITE_CONFIG_PAGECACHE: {
125349       /* Designate a buffer for page cache memory space */
125350       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
125351       sqlite3GlobalConfig.szPage = va_arg(ap, int);
125352       sqlite3GlobalConfig.nPage = va_arg(ap, int);
125353       break;
125354     }
125355 
125356     case SQLITE_CONFIG_PCACHE: {
125357       /* no-op */
125358       break;
125359     }
125360     case SQLITE_CONFIG_GETPCACHE: {
125361       /* now an error */
125362       rc = SQLITE_ERROR;
125363       break;
125364     }
125365 
125366     case SQLITE_CONFIG_PCACHE2: {
125367       /* Specify an alternative page cache implementation */
125368       sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
125369       break;
125370     }
125371     case SQLITE_CONFIG_GETPCACHE2: {
125372       if( sqlite3GlobalConfig.pcache2.xInit==0 ){
125373         sqlite3PCacheSetDefault();
125374       }
125375       *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
125376       break;
125377     }
125378 
125379 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
125380     case SQLITE_CONFIG_HEAP: {
125381       /* Designate a buffer for heap memory space */
125382       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
125383       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
125384       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
125385 
125386       if( sqlite3GlobalConfig.mnReq<1 ){
125387         sqlite3GlobalConfig.mnReq = 1;
125388       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
125389         /* cap min request size at 2^12 */
125390         sqlite3GlobalConfig.mnReq = (1<<12);
125391       }
125392 
125393       if( sqlite3GlobalConfig.pHeap==0 ){
125394         /* If the heap pointer is NULL, then restore the malloc implementation
125395         ** back to NULL pointers too.  This will cause the malloc to go
125396         ** back to its default implementation when sqlite3_initialize() is
125397         ** run.
125398         */
125399         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
125400       }else{
125401         /* The heap pointer is not NULL, then install one of the
125402         ** mem5.c/mem3.c methods.  The enclosing #if guarantees at
125403         ** least one of these methods is currently enabled.
125404         */
125405 #ifdef SQLITE_ENABLE_MEMSYS3
125406         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
125407 #endif
125408 #ifdef SQLITE_ENABLE_MEMSYS5
125409         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
125410 #endif
125411       }
125412       break;
125413     }
125414 #endif
125415 
125416     case SQLITE_CONFIG_LOOKASIDE: {
125417       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
125418       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
125419       break;
125420     }
125421 
125422     /* Record a pointer to the logger function and its first argument.
125423     ** The default is NULL.  Logging is disabled if the function pointer is
125424     ** NULL.
125425     */
125426     case SQLITE_CONFIG_LOG: {
125427       /* MSVC is picky about pulling func ptrs from va lists.
125428       ** http://support.microsoft.com/kb/47961
125429       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
125430       */
125431       typedef void(*LOGFUNC_t)(void*,int,const char*);
125432       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
125433       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
125434       break;
125435     }
125436 
125437     /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
125438     ** can be changed at start-time using the
125439     ** sqlite3_config(SQLITE_CONFIG_URI,1) or
125440     ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
125441     */
125442     case SQLITE_CONFIG_URI: {
125443       sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
125444       break;
125445     }
125446 
125447     case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
125448       sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
125449       break;
125450     }
125451 
125452 #ifdef SQLITE_ENABLE_SQLLOG
125453     case SQLITE_CONFIG_SQLLOG: {
125454       typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
125455       sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
125456       sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
125457       break;
125458     }
125459 #endif
125460 
125461     case SQLITE_CONFIG_MMAP_SIZE: {
125462       sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
125463       sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
125464       if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
125465         mxMmap = SQLITE_MAX_MMAP_SIZE;
125466       }
125467       sqlite3GlobalConfig.mxMmap = mxMmap;
125468       if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
125469       if( szMmap>mxMmap) szMmap = mxMmap;
125470       sqlite3GlobalConfig.szMmap = szMmap;
125471       break;
125472     }
125473 
125474 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC)
125475     case SQLITE_CONFIG_WIN32_HEAPSIZE: {
125476       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
125477       break;
125478     }
125479 #endif
125480 
125481     default: {
125482       rc = SQLITE_ERROR;
125483       break;
125484     }
125485   }
125486   va_end(ap);
125487   return rc;
125488 }
125489 
125490 /*
125491 ** Set up the lookaside buffers for a database connection.
125492 ** Return SQLITE_OK on success.
125493 ** If lookaside is already active, return SQLITE_BUSY.
125494 **
125495 ** The sz parameter is the number of bytes in each lookaside slot.
125496 ** The cnt parameter is the number of slots.  If pStart is NULL the
125497 ** space for the lookaside memory is obtained from sqlite3_malloc().
125498 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
125499 ** the lookaside memory.
125500 */
125501 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
125502   void *pStart;
125503   if( db->lookaside.nOut ){
125504     return SQLITE_BUSY;
125505   }
125506   /* Free any existing lookaside buffer for this handle before
125507   ** allocating a new one so we don't have to have space for
125508   ** both at the same time.
125509   */
125510   if( db->lookaside.bMalloced ){
125511     sqlite3_free(db->lookaside.pStart);
125512   }
125513   /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
125514   ** than a pointer to be useful.
125515   */
125516   sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
125517   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
125518   if( cnt<0 ) cnt = 0;
125519   if( sz==0 || cnt==0 ){
125520     sz = 0;
125521     pStart = 0;
125522   }else if( pBuf==0 ){
125523     sqlite3BeginBenignMalloc();
125524     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
125525     sqlite3EndBenignMalloc();
125526     if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
125527   }else{
125528     pStart = pBuf;
125529   }
125530   db->lookaside.pStart = pStart;
125531   db->lookaside.pFree = 0;
125532   db->lookaside.sz = (u16)sz;
125533   if( pStart ){
125534     int i;
125535     LookasideSlot *p;
125536     assert( sz > (int)sizeof(LookasideSlot*) );
125537     p = (LookasideSlot*)pStart;
125538     for(i=cnt-1; i>=0; i--){
125539       p->pNext = db->lookaside.pFree;
125540       db->lookaside.pFree = p;
125541       p = (LookasideSlot*)&((u8*)p)[sz];
125542     }
125543     db->lookaside.pEnd = p;
125544     db->lookaside.bEnabled = 1;
125545     db->lookaside.bMalloced = pBuf==0 ?1:0;
125546   }else{
125547     db->lookaside.pStart = db;
125548     db->lookaside.pEnd = db;
125549     db->lookaside.bEnabled = 0;
125550     db->lookaside.bMalloced = 0;
125551   }
125552   return SQLITE_OK;
125553 }
125554 
125555 /*
125556 ** Return the mutex associated with a database connection.
125557 */
125558 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
125559   return db->mutex;
125560 }
125561 
125562 /*
125563 ** Free up as much memory as we can from the given database
125564 ** connection.
125565 */
125566 SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
125567   int i;
125568   sqlite3_mutex_enter(db->mutex);
125569   sqlite3BtreeEnterAll(db);
125570   for(i=0; i<db->nDb; i++){
125571     Btree *pBt = db->aDb[i].pBt;
125572     if( pBt ){
125573       Pager *pPager = sqlite3BtreePager(pBt);
125574       sqlite3PagerShrink(pPager);
125575     }
125576   }
125577   sqlite3BtreeLeaveAll(db);
125578   sqlite3_mutex_leave(db->mutex);
125579   return SQLITE_OK;
125580 }
125581 
125582 /*
125583 ** Configuration settings for an individual database connection
125584 */
125585 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
125586   va_list ap;
125587   int rc;
125588   va_start(ap, op);
125589   switch( op ){
125590     case SQLITE_DBCONFIG_LOOKASIDE: {
125591       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
125592       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
125593       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
125594       rc = setupLookaside(db, pBuf, sz, cnt);
125595       break;
125596     }
125597     default: {
125598       static const struct {
125599         int op;      /* The opcode */
125600         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
125601       } aFlagOp[] = {
125602         { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
125603         { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
125604       };
125605       unsigned int i;
125606       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
125607       for(i=0; i<ArraySize(aFlagOp); i++){
125608         if( aFlagOp[i].op==op ){
125609           int onoff = va_arg(ap, int);
125610           int *pRes = va_arg(ap, int*);
125611           int oldFlags = db->flags;
125612           if( onoff>0 ){
125613             db->flags |= aFlagOp[i].mask;
125614           }else if( onoff==0 ){
125615             db->flags &= ~aFlagOp[i].mask;
125616           }
125617           if( oldFlags!=db->flags ){
125618             sqlite3ExpirePreparedStatements(db);
125619           }
125620           if( pRes ){
125621             *pRes = (db->flags & aFlagOp[i].mask)!=0;
125622           }
125623           rc = SQLITE_OK;
125624           break;
125625         }
125626       }
125627       break;
125628     }
125629   }
125630   va_end(ap);
125631   return rc;
125632 }
125633 
125634 
125635 /*
125636 ** Return true if the buffer z[0..n-1] contains all spaces.
125637 */
125638 static int allSpaces(const char *z, int n){
125639   while( n>0 && z[n-1]==' ' ){ n--; }
125640   return n==0;
125641 }
125642 
125643 /*
125644 ** This is the default collating function named "BINARY" which is always
125645 ** available.
125646 **
125647 ** If the padFlag argument is not NULL then space padding at the end
125648 ** of strings is ignored.  This implements the RTRIM collation.
125649 */
125650 static int binCollFunc(
125651   void *padFlag,
125652   int nKey1, const void *pKey1,
125653   int nKey2, const void *pKey2
125654 ){
125655   int rc, n;
125656   n = nKey1<nKey2 ? nKey1 : nKey2;
125657   rc = memcmp(pKey1, pKey2, n);
125658   if( rc==0 ){
125659     if( padFlag
125660      && allSpaces(((char*)pKey1)+n, nKey1-n)
125661      && allSpaces(((char*)pKey2)+n, nKey2-n)
125662     ){
125663       /* Leave rc unchanged at 0 */
125664     }else{
125665       rc = nKey1 - nKey2;
125666     }
125667   }
125668   return rc;
125669 }
125670 
125671 /*
125672 ** Another built-in collating sequence: NOCASE.
125673 **
125674 ** This collating sequence is intended to be used for "case independent
125675 ** comparison". SQLite's knowledge of upper and lower case equivalents
125676 ** extends only to the 26 characters used in the English language.
125677 **
125678 ** At the moment there is only a UTF-8 implementation.
125679 */
125680 static int nocaseCollatingFunc(
125681   void *NotUsed,
125682   int nKey1, const void *pKey1,
125683   int nKey2, const void *pKey2
125684 ){
125685   int r = sqlite3StrNICmp(
125686       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
125687   UNUSED_PARAMETER(NotUsed);
125688   if( 0==r ){
125689     r = nKey1-nKey2;
125690   }
125691   return r;
125692 }
125693 
125694 /*
125695 ** Return the ROWID of the most recent insert
125696 */
125697 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
125698   return db->lastRowid;
125699 }
125700 
125701 /*
125702 ** Return the number of changes in the most recent call to sqlite3_exec().
125703 */
125704 SQLITE_API int sqlite3_changes(sqlite3 *db){
125705   return db->nChange;
125706 }
125707 
125708 /*
125709 ** Return the number of changes since the database handle was opened.
125710 */
125711 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
125712   return db->nTotalChange;
125713 }
125714 
125715 /*
125716 ** Close all open savepoints. This function only manipulates fields of the
125717 ** database handle object, it does not close any savepoints that may be open
125718 ** at the b-tree/pager level.
125719 */
125720 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
125721   while( db->pSavepoint ){
125722     Savepoint *pTmp = db->pSavepoint;
125723     db->pSavepoint = pTmp->pNext;
125724     sqlite3DbFree(db, pTmp);
125725   }
125726   db->nSavepoint = 0;
125727   db->nStatement = 0;
125728   db->isTransactionSavepoint = 0;
125729 }
125730 
125731 /*
125732 ** Invoke the destructor function associated with FuncDef p, if any. Except,
125733 ** if this is not the last copy of the function, do not invoke it. Multiple
125734 ** copies of a single function are created when create_function() is called
125735 ** with SQLITE_ANY as the encoding.
125736 */
125737 static void functionDestroy(sqlite3 *db, FuncDef *p){
125738   FuncDestructor *pDestructor = p->pDestructor;
125739   if( pDestructor ){
125740     pDestructor->nRef--;
125741     if( pDestructor->nRef==0 ){
125742       pDestructor->xDestroy(pDestructor->pUserData);
125743       sqlite3DbFree(db, pDestructor);
125744     }
125745   }
125746 }
125747 
125748 /*
125749 ** Disconnect all sqlite3_vtab objects that belong to database connection
125750 ** db. This is called when db is being closed.
125751 */
125752 static void disconnectAllVtab(sqlite3 *db){
125753 #ifndef SQLITE_OMIT_VIRTUALTABLE
125754   int i;
125755   sqlite3BtreeEnterAll(db);
125756   for(i=0; i<db->nDb; i++){
125757     Schema *pSchema = db->aDb[i].pSchema;
125758     if( db->aDb[i].pSchema ){
125759       HashElem *p;
125760       for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
125761         Table *pTab = (Table *)sqliteHashData(p);
125762         if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
125763       }
125764     }
125765   }
125766   sqlite3VtabUnlockList(db);
125767   sqlite3BtreeLeaveAll(db);
125768 #else
125769   UNUSED_PARAMETER(db);
125770 #endif
125771 }
125772 
125773 /*
125774 ** Return TRUE if database connection db has unfinalized prepared
125775 ** statements or unfinished sqlite3_backup objects.
125776 */
125777 static int connectionIsBusy(sqlite3 *db){
125778   int j;
125779   assert( sqlite3_mutex_held(db->mutex) );
125780   if( db->pVdbe ) return 1;
125781   for(j=0; j<db->nDb; j++){
125782     Btree *pBt = db->aDb[j].pBt;
125783     if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
125784   }
125785   return 0;
125786 }
125787 
125788 /*
125789 ** Close an existing SQLite database
125790 */
125791 static int sqlite3Close(sqlite3 *db, int forceZombie){
125792   if( !db ){
125793     /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
125794     ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
125795     return SQLITE_OK;
125796   }
125797   if( !sqlite3SafetyCheckSickOrOk(db) ){
125798     return SQLITE_MISUSE_BKPT;
125799   }
125800   sqlite3_mutex_enter(db->mutex);
125801 
125802   /* Force xDisconnect calls on all virtual tables */
125803   disconnectAllVtab(db);
125804 
125805   /* If a transaction is open, the disconnectAllVtab() call above
125806   ** will not have called the xDisconnect() method on any virtual
125807   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
125808   ** call will do so. We need to do this before the check for active
125809   ** SQL statements below, as the v-table implementation may be storing
125810   ** some prepared statements internally.
125811   */
125812   sqlite3VtabRollback(db);
125813 
125814   /* Legacy behavior (sqlite3_close() behavior) is to return
125815   ** SQLITE_BUSY if the connection can not be closed immediately.
125816   */
125817   if( !forceZombie && connectionIsBusy(db) ){
125818     sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
125819        "statements or unfinished backups");
125820     sqlite3_mutex_leave(db->mutex);
125821     return SQLITE_BUSY;
125822   }
125823 
125824 #ifdef SQLITE_ENABLE_SQLLOG
125825   if( sqlite3GlobalConfig.xSqllog ){
125826     /* Closing the handle. Fourth parameter is passed the value 2. */
125827     sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
125828   }
125829 #endif
125830 
125831   /* Convert the connection into a zombie and then close it.
125832   */
125833   db->magic = SQLITE_MAGIC_ZOMBIE;
125834   sqlite3LeaveMutexAndCloseZombie(db);
125835   return SQLITE_OK;
125836 }
125837 
125838 /*
125839 ** Two variations on the public interface for closing a database
125840 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
125841 ** leaves the connection option if there are unfinalized prepared
125842 ** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
125843 ** version forces the connection to become a zombie if there are
125844 ** unclosed resources, and arranges for deallocation when the last
125845 ** prepare statement or sqlite3_backup closes.
125846 */
125847 SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
125848 SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
125849 
125850 
125851 /*
125852 ** Close the mutex on database connection db.
125853 **
125854 ** Furthermore, if database connection db is a zombie (meaning that there
125855 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
125856 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
125857 ** finished, then free all resources.
125858 */
125859 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
125860   HashElem *i;                    /* Hash table iterator */
125861   int j;
125862 
125863   /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
125864   ** or if the connection has not yet been closed by sqlite3_close_v2(),
125865   ** then just leave the mutex and return.
125866   */
125867   if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
125868     sqlite3_mutex_leave(db->mutex);
125869     return;
125870   }
125871 
125872   /* If we reach this point, it means that the database connection has
125873   ** closed all sqlite3_stmt and sqlite3_backup objects and has been
125874   ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
125875   ** go ahead and free all resources.
125876   */
125877 
125878   /* If a transaction is open, roll it back. This also ensures that if
125879   ** any database schemas have been modified by an uncommitted transaction
125880   ** they are reset. And that the required b-tree mutex is held to make
125881   ** the pager rollback and schema reset an atomic operation. */
125882   sqlite3RollbackAll(db, SQLITE_OK);
125883 
125884   /* Free any outstanding Savepoint structures. */
125885   sqlite3CloseSavepoints(db);
125886 
125887   /* Close all database connections */
125888   for(j=0; j<db->nDb; j++){
125889     struct Db *pDb = &db->aDb[j];
125890     if( pDb->pBt ){
125891       sqlite3BtreeClose(pDb->pBt);
125892       pDb->pBt = 0;
125893       if( j!=1 ){
125894         pDb->pSchema = 0;
125895       }
125896     }
125897   }
125898   /* Clear the TEMP schema separately and last */
125899   if( db->aDb[1].pSchema ){
125900     sqlite3SchemaClear(db->aDb[1].pSchema);
125901   }
125902   sqlite3VtabUnlockList(db);
125903 
125904   /* Free up the array of auxiliary databases */
125905   sqlite3CollapseDatabaseArray(db);
125906   assert( db->nDb<=2 );
125907   assert( db->aDb==db->aDbStatic );
125908 
125909   /* Tell the code in notify.c that the connection no longer holds any
125910   ** locks and does not require any further unlock-notify callbacks.
125911   */
125912   sqlite3ConnectionClosed(db);
125913 
125914   for(j=0; j<ArraySize(db->aFunc.a); j++){
125915     FuncDef *pNext, *pHash, *p;
125916     for(p=db->aFunc.a[j]; p; p=pHash){
125917       pHash = p->pHash;
125918       while( p ){
125919         functionDestroy(db, p);
125920         pNext = p->pNext;
125921         sqlite3DbFree(db, p);
125922         p = pNext;
125923       }
125924     }
125925   }
125926   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
125927     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
125928     /* Invoke any destructors registered for collation sequence user data. */
125929     for(j=0; j<3; j++){
125930       if( pColl[j].xDel ){
125931         pColl[j].xDel(pColl[j].pUser);
125932       }
125933     }
125934     sqlite3DbFree(db, pColl);
125935   }
125936   sqlite3HashClear(&db->aCollSeq);
125937 #ifndef SQLITE_OMIT_VIRTUALTABLE
125938   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
125939     Module *pMod = (Module *)sqliteHashData(i);
125940     if( pMod->xDestroy ){
125941       pMod->xDestroy(pMod->pAux);
125942     }
125943     sqlite3DbFree(db, pMod);
125944   }
125945   sqlite3HashClear(&db->aModule);
125946 #endif
125947 
125948   sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
125949   sqlite3ValueFree(db->pErr);
125950   sqlite3CloseExtensions(db);
125951 #if SQLITE_USER_AUTHENTICATION
125952   sqlite3_free(db->auth.zAuthUser);
125953   sqlite3_free(db->auth.zAuthPW);
125954 #endif
125955 
125956   db->magic = SQLITE_MAGIC_ERROR;
125957 
125958   /* The temp-database schema is allocated differently from the other schema
125959   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
125960   ** So it needs to be freed here. Todo: Why not roll the temp schema into
125961   ** the same sqliteMalloc() as the one that allocates the database
125962   ** structure?
125963   */
125964   sqlite3DbFree(db, db->aDb[1].pSchema);
125965   sqlite3_mutex_leave(db->mutex);
125966   db->magic = SQLITE_MAGIC_CLOSED;
125967   sqlite3_mutex_free(db->mutex);
125968   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
125969   if( db->lookaside.bMalloced ){
125970     sqlite3_free(db->lookaside.pStart);
125971   }
125972   sqlite3_free(db);
125973 }
125974 
125975 /*
125976 ** Rollback all database files.  If tripCode is not SQLITE_OK, then
125977 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
125978 ** breaker") and made to return tripCode if there are any further
125979 ** attempts to use that cursor.  Read cursors remain open and valid
125980 ** but are "saved" in case the table pages are moved around.
125981 */
125982 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
125983   int i;
125984   int inTrans = 0;
125985   int schemaChange;
125986   assert( sqlite3_mutex_held(db->mutex) );
125987   sqlite3BeginBenignMalloc();
125988 
125989   /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
125990   ** This is important in case the transaction being rolled back has
125991   ** modified the database schema. If the b-tree mutexes are not taken
125992   ** here, then another shared-cache connection might sneak in between
125993   ** the database rollback and schema reset, which can cause false
125994   ** corruption reports in some cases.  */
125995   sqlite3BtreeEnterAll(db);
125996   schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
125997 
125998   for(i=0; i<db->nDb; i++){
125999     Btree *p = db->aDb[i].pBt;
126000     if( p ){
126001       if( sqlite3BtreeIsInTrans(p) ){
126002         inTrans = 1;
126003       }
126004       sqlite3BtreeRollback(p, tripCode, !schemaChange);
126005     }
126006   }
126007   sqlite3VtabRollback(db);
126008   sqlite3EndBenignMalloc();
126009 
126010   if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
126011     sqlite3ExpirePreparedStatements(db);
126012     sqlite3ResetAllSchemasOfConnection(db);
126013   }
126014   sqlite3BtreeLeaveAll(db);
126015 
126016   /* Any deferred constraint violations have now been resolved. */
126017   db->nDeferredCons = 0;
126018   db->nDeferredImmCons = 0;
126019   db->flags &= ~SQLITE_DeferFKs;
126020 
126021   /* If one has been configured, invoke the rollback-hook callback */
126022   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
126023     db->xRollbackCallback(db->pRollbackArg);
126024   }
126025 }
126026 
126027 /*
126028 ** Return a static string containing the name corresponding to the error code
126029 ** specified in the argument.
126030 */
126031 #if (defined(SQLITE_DEBUG) && SQLITE_OS_WIN) || defined(SQLITE_TEST)
126032 SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
126033   const char *zName = 0;
126034   int i, origRc = rc;
126035   for(i=0; i<2 && zName==0; i++, rc &= 0xff){
126036     switch( rc ){
126037       case SQLITE_OK:                 zName = "SQLITE_OK";                break;
126038       case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
126039       case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
126040       case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
126041       case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
126042       case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
126043       case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
126044       case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
126045       case SQLITE_BUSY_SNAPSHOT:      zName = "SQLITE_BUSY_SNAPSHOT";     break;
126046       case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
126047       case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
126048       case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
126049       case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
126050       case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
126051       case SQLITE_READONLY_CANTLOCK:  zName = "SQLITE_READONLY_CANTLOCK"; break;
126052       case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
126053       case SQLITE_READONLY_DBMOVED:   zName = "SQLITE_READONLY_DBMOVED";  break;
126054       case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
126055       case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
126056       case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
126057       case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
126058       case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
126059       case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
126060       case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
126061       case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
126062       case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
126063       case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
126064       case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
126065       case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
126066       case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
126067       case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
126068       case SQLITE_IOERR_CHECKRESERVEDLOCK:
126069                                 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
126070       case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
126071       case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
126072       case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
126073       case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
126074       case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
126075       case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
126076       case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
126077       case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
126078       case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
126079       case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
126080       case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
126081       case SQLITE_IOERR_CONVPATH:     zName = "SQLITE_IOERR_CONVPATH";    break;
126082       case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
126083       case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
126084       case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
126085       case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
126086       case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
126087       case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
126088       case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
126089       case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
126090       case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
126091       case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
126092       case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
126093       case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
126094       case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
126095       case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
126096       case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
126097       case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
126098       case SQLITE_CONSTRAINT_FOREIGNKEY:
126099                                 zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
126100       case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
126101       case SQLITE_CONSTRAINT_PRIMARYKEY:
126102                                 zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
126103       case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
126104       case SQLITE_CONSTRAINT_COMMITHOOK:
126105                                 zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
126106       case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
126107       case SQLITE_CONSTRAINT_FUNCTION:
126108                                 zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
126109       case SQLITE_CONSTRAINT_ROWID:   zName = "SQLITE_CONSTRAINT_ROWID";  break;
126110       case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
126111       case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
126112       case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
126113       case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
126114       case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
126115       case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
126116       case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
126117       case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
126118       case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
126119       case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
126120       case SQLITE_NOTICE_RECOVER_ROLLBACK:
126121                                 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
126122       case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
126123       case SQLITE_WARNING_AUTOINDEX:  zName = "SQLITE_WARNING_AUTOINDEX"; break;
126124       case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
126125     }
126126   }
126127   if( zName==0 ){
126128     static char zBuf[50];
126129     sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
126130     zName = zBuf;
126131   }
126132   return zName;
126133 }
126134 #endif
126135 
126136 /*
126137 ** Return a static string that describes the kind of error specified in the
126138 ** argument.
126139 */
126140 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
126141   static const char* const aMsg[] = {
126142     /* SQLITE_OK          */ "not an error",
126143     /* SQLITE_ERROR       */ "SQL logic error or missing database",
126144     /* SQLITE_INTERNAL    */ 0,
126145     /* SQLITE_PERM        */ "access permission denied",
126146     /* SQLITE_ABORT       */ "callback requested query abort",
126147     /* SQLITE_BUSY        */ "database is locked",
126148     /* SQLITE_LOCKED      */ "database table is locked",
126149     /* SQLITE_NOMEM       */ "out of memory",
126150     /* SQLITE_READONLY    */ "attempt to write a readonly database",
126151     /* SQLITE_INTERRUPT   */ "interrupted",
126152     /* SQLITE_IOERR       */ "disk I/O error",
126153     /* SQLITE_CORRUPT     */ "database disk image is malformed",
126154     /* SQLITE_NOTFOUND    */ "unknown operation",
126155     /* SQLITE_FULL        */ "database or disk is full",
126156     /* SQLITE_CANTOPEN    */ "unable to open database file",
126157     /* SQLITE_PROTOCOL    */ "locking protocol",
126158     /* SQLITE_EMPTY       */ "table contains no data",
126159     /* SQLITE_SCHEMA      */ "database schema has changed",
126160     /* SQLITE_TOOBIG      */ "string or blob too big",
126161     /* SQLITE_CONSTRAINT  */ "constraint failed",
126162     /* SQLITE_MISMATCH    */ "datatype mismatch",
126163     /* SQLITE_MISUSE      */ "library routine called out of sequence",
126164     /* SQLITE_NOLFS       */ "large file support is disabled",
126165     /* SQLITE_AUTH        */ "authorization denied",
126166     /* SQLITE_FORMAT      */ "auxiliary database format error",
126167     /* SQLITE_RANGE       */ "bind or column index out of range",
126168     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
126169   };
126170   const char *zErr = "unknown error";
126171   switch( rc ){
126172     case SQLITE_ABORT_ROLLBACK: {
126173       zErr = "abort due to ROLLBACK";
126174       break;
126175     }
126176     default: {
126177       rc &= 0xff;
126178       if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
126179         zErr = aMsg[rc];
126180       }
126181       break;
126182     }
126183   }
126184   return zErr;
126185 }
126186 
126187 /*
126188 ** This routine implements a busy callback that sleeps and tries
126189 ** again until a timeout value is reached.  The timeout value is
126190 ** an integer number of milliseconds passed in as the first
126191 ** argument.
126192 */
126193 static int sqliteDefaultBusyCallback(
126194  void *ptr,               /* Database connection */
126195  int count                /* Number of times table has been busy */
126196 ){
126197 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
126198   static const u8 delays[] =
126199      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
126200   static const u8 totals[] =
126201      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
126202 # define NDELAY ArraySize(delays)
126203   sqlite3 *db = (sqlite3 *)ptr;
126204   int timeout = db->busyTimeout;
126205   int delay, prior;
126206 
126207   assert( count>=0 );
126208   if( count < NDELAY ){
126209     delay = delays[count];
126210     prior = totals[count];
126211   }else{
126212     delay = delays[NDELAY-1];
126213     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
126214   }
126215   if( prior + delay > timeout ){
126216     delay = timeout - prior;
126217     if( delay<=0 ) return 0;
126218   }
126219   sqlite3OsSleep(db->pVfs, delay*1000);
126220   return 1;
126221 #else
126222   sqlite3 *db = (sqlite3 *)ptr;
126223   int timeout = ((sqlite3 *)ptr)->busyTimeout;
126224   if( (count+1)*1000 > timeout ){
126225     return 0;
126226   }
126227   sqlite3OsSleep(db->pVfs, 1000000);
126228   return 1;
126229 #endif
126230 }
126231 
126232 /*
126233 ** Invoke the given busy handler.
126234 **
126235 ** This routine is called when an operation failed with a lock.
126236 ** If this routine returns non-zero, the lock is retried.  If it
126237 ** returns 0, the operation aborts with an SQLITE_BUSY error.
126238 */
126239 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
126240   int rc;
126241   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
126242   rc = p->xFunc(p->pArg, p->nBusy);
126243   if( rc==0 ){
126244     p->nBusy = -1;
126245   }else{
126246     p->nBusy++;
126247   }
126248   return rc;
126249 }
126250 
126251 /*
126252 ** This routine sets the busy callback for an Sqlite database to the
126253 ** given callback function with the given argument.
126254 */
126255 SQLITE_API int sqlite3_busy_handler(
126256   sqlite3 *db,
126257   int (*xBusy)(void*,int),
126258   void *pArg
126259 ){
126260   sqlite3_mutex_enter(db->mutex);
126261   db->busyHandler.xFunc = xBusy;
126262   db->busyHandler.pArg = pArg;
126263   db->busyHandler.nBusy = 0;
126264   db->busyTimeout = 0;
126265   sqlite3_mutex_leave(db->mutex);
126266   return SQLITE_OK;
126267 }
126268 
126269 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
126270 /*
126271 ** This routine sets the progress callback for an Sqlite database to the
126272 ** given callback function with the given argument. The progress callback will
126273 ** be invoked every nOps opcodes.
126274 */
126275 SQLITE_API void sqlite3_progress_handler(
126276   sqlite3 *db,
126277   int nOps,
126278   int (*xProgress)(void*),
126279   void *pArg
126280 ){
126281   sqlite3_mutex_enter(db->mutex);
126282   if( nOps>0 ){
126283     db->xProgress = xProgress;
126284     db->nProgressOps = (unsigned)nOps;
126285     db->pProgressArg = pArg;
126286   }else{
126287     db->xProgress = 0;
126288     db->nProgressOps = 0;
126289     db->pProgressArg = 0;
126290   }
126291   sqlite3_mutex_leave(db->mutex);
126292 }
126293 #endif
126294 
126295 
126296 /*
126297 ** This routine installs a default busy handler that waits for the
126298 ** specified number of milliseconds before returning 0.
126299 */
126300 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
126301   if( ms>0 ){
126302     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
126303     db->busyTimeout = ms;
126304   }else{
126305     sqlite3_busy_handler(db, 0, 0);
126306   }
126307   return SQLITE_OK;
126308 }
126309 
126310 /*
126311 ** Cause any pending operation to stop at its earliest opportunity.
126312 */
126313 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
126314   db->u1.isInterrupted = 1;
126315 }
126316 
126317 
126318 /*
126319 ** This function is exactly the same as sqlite3_create_function(), except
126320 ** that it is designed to be called by internal code. The difference is
126321 ** that if a malloc() fails in sqlite3_create_function(), an error code
126322 ** is returned and the mallocFailed flag cleared.
126323 */
126324 SQLITE_PRIVATE int sqlite3CreateFunc(
126325   sqlite3 *db,
126326   const char *zFunctionName,
126327   int nArg,
126328   int enc,
126329   void *pUserData,
126330   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
126331   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
126332   void (*xFinal)(sqlite3_context*),
126333   FuncDestructor *pDestructor
126334 ){
126335   FuncDef *p;
126336   int nName;
126337   int extraFlags;
126338 
126339   assert( sqlite3_mutex_held(db->mutex) );
126340   if( zFunctionName==0 ||
126341       (xFunc && (xFinal || xStep)) ||
126342       (!xFunc && (xFinal && !xStep)) ||
126343       (!xFunc && (!xFinal && xStep)) ||
126344       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
126345       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
126346     return SQLITE_MISUSE_BKPT;
126347   }
126348 
126349   assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
126350   extraFlags = enc &  SQLITE_DETERMINISTIC;
126351   enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
126352 
126353 #ifndef SQLITE_OMIT_UTF16
126354   /* If SQLITE_UTF16 is specified as the encoding type, transform this
126355   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
126356   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
126357   **
126358   ** If SQLITE_ANY is specified, add three versions of the function
126359   ** to the hash table.
126360   */
126361   if( enc==SQLITE_UTF16 ){
126362     enc = SQLITE_UTF16NATIVE;
126363   }else if( enc==SQLITE_ANY ){
126364     int rc;
126365     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
126366          pUserData, xFunc, xStep, xFinal, pDestructor);
126367     if( rc==SQLITE_OK ){
126368       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
126369           pUserData, xFunc, xStep, xFinal, pDestructor);
126370     }
126371     if( rc!=SQLITE_OK ){
126372       return rc;
126373     }
126374     enc = SQLITE_UTF16BE;
126375   }
126376 #else
126377   enc = SQLITE_UTF8;
126378 #endif
126379 
126380   /* Check if an existing function is being overridden or deleted. If so,
126381   ** and there are active VMs, then return SQLITE_BUSY. If a function
126382   ** is being overridden/deleted but there are no active VMs, allow the
126383   ** operation to continue but invalidate all precompiled statements.
126384   */
126385   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
126386   if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
126387     if( db->nVdbeActive ){
126388       sqlite3ErrorWithMsg(db, SQLITE_BUSY,
126389         "unable to delete/modify user-function due to active statements");
126390       assert( !db->mallocFailed );
126391       return SQLITE_BUSY;
126392     }else{
126393       sqlite3ExpirePreparedStatements(db);
126394     }
126395   }
126396 
126397   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
126398   assert(p || db->mallocFailed);
126399   if( !p ){
126400     return SQLITE_NOMEM;
126401   }
126402 
126403   /* If an older version of the function with a configured destructor is
126404   ** being replaced invoke the destructor function here. */
126405   functionDestroy(db, p);
126406 
126407   if( pDestructor ){
126408     pDestructor->nRef++;
126409   }
126410   p->pDestructor = pDestructor;
126411   p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
126412   testcase( p->funcFlags & SQLITE_DETERMINISTIC );
126413   p->xFunc = xFunc;
126414   p->xStep = xStep;
126415   p->xFinalize = xFinal;
126416   p->pUserData = pUserData;
126417   p->nArg = (u16)nArg;
126418   return SQLITE_OK;
126419 }
126420 
126421 /*
126422 ** Create new user functions.
126423 */
126424 SQLITE_API int sqlite3_create_function(
126425   sqlite3 *db,
126426   const char *zFunc,
126427   int nArg,
126428   int enc,
126429   void *p,
126430   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
126431   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
126432   void (*xFinal)(sqlite3_context*)
126433 ){
126434   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
126435                                     xFinal, 0);
126436 }
126437 
126438 SQLITE_API int sqlite3_create_function_v2(
126439   sqlite3 *db,
126440   const char *zFunc,
126441   int nArg,
126442   int enc,
126443   void *p,
126444   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
126445   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
126446   void (*xFinal)(sqlite3_context*),
126447   void (*xDestroy)(void *)
126448 ){
126449   int rc = SQLITE_ERROR;
126450   FuncDestructor *pArg = 0;
126451   sqlite3_mutex_enter(db->mutex);
126452   if( xDestroy ){
126453     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
126454     if( !pArg ){
126455       xDestroy(p);
126456       goto out;
126457     }
126458     pArg->xDestroy = xDestroy;
126459     pArg->pUserData = p;
126460   }
126461   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
126462   if( pArg && pArg->nRef==0 ){
126463     assert( rc!=SQLITE_OK );
126464     xDestroy(p);
126465     sqlite3DbFree(db, pArg);
126466   }
126467 
126468  out:
126469   rc = sqlite3ApiExit(db, rc);
126470   sqlite3_mutex_leave(db->mutex);
126471   return rc;
126472 }
126473 
126474 #ifndef SQLITE_OMIT_UTF16
126475 SQLITE_API int sqlite3_create_function16(
126476   sqlite3 *db,
126477   const void *zFunctionName,
126478   int nArg,
126479   int eTextRep,
126480   void *p,
126481   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
126482   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
126483   void (*xFinal)(sqlite3_context*)
126484 ){
126485   int rc;
126486   char *zFunc8;
126487   sqlite3_mutex_enter(db->mutex);
126488   assert( !db->mallocFailed );
126489   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
126490   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
126491   sqlite3DbFree(db, zFunc8);
126492   rc = sqlite3ApiExit(db, rc);
126493   sqlite3_mutex_leave(db->mutex);
126494   return rc;
126495 }
126496 #endif
126497 
126498 
126499 /*
126500 ** Declare that a function has been overloaded by a virtual table.
126501 **
126502 ** If the function already exists as a regular global function, then
126503 ** this routine is a no-op.  If the function does not exist, then create
126504 ** a new one that always throws a run-time error.
126505 **
126506 ** When virtual tables intend to provide an overloaded function, they
126507 ** should call this routine to make sure the global function exists.
126508 ** A global function must exist in order for name resolution to work
126509 ** properly.
126510 */
126511 SQLITE_API int sqlite3_overload_function(
126512   sqlite3 *db,
126513   const char *zName,
126514   int nArg
126515 ){
126516   int nName = sqlite3Strlen30(zName);
126517   int rc = SQLITE_OK;
126518   sqlite3_mutex_enter(db->mutex);
126519   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
126520     rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
126521                            0, sqlite3InvalidFunction, 0, 0, 0);
126522   }
126523   rc = sqlite3ApiExit(db, rc);
126524   sqlite3_mutex_leave(db->mutex);
126525   return rc;
126526 }
126527 
126528 #ifndef SQLITE_OMIT_TRACE
126529 /*
126530 ** Register a trace function.  The pArg from the previously registered trace
126531 ** is returned.
126532 **
126533 ** A NULL trace function means that no tracing is executes.  A non-NULL
126534 ** trace is a pointer to a function that is invoked at the start of each
126535 ** SQL statement.
126536 */
126537 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
126538   void *pOld;
126539   sqlite3_mutex_enter(db->mutex);
126540   pOld = db->pTraceArg;
126541   db->xTrace = xTrace;
126542   db->pTraceArg = pArg;
126543   sqlite3_mutex_leave(db->mutex);
126544   return pOld;
126545 }
126546 /*
126547 ** Register a profile function.  The pArg from the previously registered
126548 ** profile function is returned.
126549 **
126550 ** A NULL profile function means that no profiling is executes.  A non-NULL
126551 ** profile is a pointer to a function that is invoked at the conclusion of
126552 ** each SQL statement that is run.
126553 */
126554 SQLITE_API void *sqlite3_profile(
126555   sqlite3 *db,
126556   void (*xProfile)(void*,const char*,sqlite_uint64),
126557   void *pArg
126558 ){
126559   void *pOld;
126560   sqlite3_mutex_enter(db->mutex);
126561   pOld = db->pProfileArg;
126562   db->xProfile = xProfile;
126563   db->pProfileArg = pArg;
126564   sqlite3_mutex_leave(db->mutex);
126565   return pOld;
126566 }
126567 #endif /* SQLITE_OMIT_TRACE */
126568 
126569 /*
126570 ** Register a function to be invoked when a transaction commits.
126571 ** If the invoked function returns non-zero, then the commit becomes a
126572 ** rollback.
126573 */
126574 SQLITE_API void *sqlite3_commit_hook(
126575   sqlite3 *db,              /* Attach the hook to this database */
126576   int (*xCallback)(void*),  /* Function to invoke on each commit */
126577   void *pArg                /* Argument to the function */
126578 ){
126579   void *pOld;
126580   sqlite3_mutex_enter(db->mutex);
126581   pOld = db->pCommitArg;
126582   db->xCommitCallback = xCallback;
126583   db->pCommitArg = pArg;
126584   sqlite3_mutex_leave(db->mutex);
126585   return pOld;
126586 }
126587 
126588 /*
126589 ** Register a callback to be invoked each time a row is updated,
126590 ** inserted or deleted using this database connection.
126591 */
126592 SQLITE_API void *sqlite3_update_hook(
126593   sqlite3 *db,              /* Attach the hook to this database */
126594   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
126595   void *pArg                /* Argument to the function */
126596 ){
126597   void *pRet;
126598   sqlite3_mutex_enter(db->mutex);
126599   pRet = db->pUpdateArg;
126600   db->xUpdateCallback = xCallback;
126601   db->pUpdateArg = pArg;
126602   sqlite3_mutex_leave(db->mutex);
126603   return pRet;
126604 }
126605 
126606 /*
126607 ** Register a callback to be invoked each time a transaction is rolled
126608 ** back by this database connection.
126609 */
126610 SQLITE_API void *sqlite3_rollback_hook(
126611   sqlite3 *db,              /* Attach the hook to this database */
126612   void (*xCallback)(void*), /* Callback function */
126613   void *pArg                /* Argument to the function */
126614 ){
126615   void *pRet;
126616   sqlite3_mutex_enter(db->mutex);
126617   pRet = db->pRollbackArg;
126618   db->xRollbackCallback = xCallback;
126619   db->pRollbackArg = pArg;
126620   sqlite3_mutex_leave(db->mutex);
126621   return pRet;
126622 }
126623 
126624 #ifndef SQLITE_OMIT_WAL
126625 /*
126626 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
126627 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
126628 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
126629 ** wal_autocheckpoint()).
126630 */
126631 SQLITE_PRIVATE int sqlite3WalDefaultHook(
126632   void *pClientData,     /* Argument */
126633   sqlite3 *db,           /* Connection */
126634   const char *zDb,       /* Database */
126635   int nFrame             /* Size of WAL */
126636 ){
126637   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
126638     sqlite3BeginBenignMalloc();
126639     sqlite3_wal_checkpoint(db, zDb);
126640     sqlite3EndBenignMalloc();
126641   }
126642   return SQLITE_OK;
126643 }
126644 #endif /* SQLITE_OMIT_WAL */
126645 
126646 /*
126647 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
126648 ** a database after committing a transaction if there are nFrame or
126649 ** more frames in the log file. Passing zero or a negative value as the
126650 ** nFrame parameter disables automatic checkpoints entirely.
126651 **
126652 ** The callback registered by this function replaces any existing callback
126653 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
126654 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
126655 ** configured by this function.
126656 */
126657 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
126658 #ifdef SQLITE_OMIT_WAL
126659   UNUSED_PARAMETER(db);
126660   UNUSED_PARAMETER(nFrame);
126661 #else
126662   if( nFrame>0 ){
126663     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
126664   }else{
126665     sqlite3_wal_hook(db, 0, 0);
126666   }
126667 #endif
126668   return SQLITE_OK;
126669 }
126670 
126671 /*
126672 ** Register a callback to be invoked each time a transaction is written
126673 ** into the write-ahead-log by this database connection.
126674 */
126675 SQLITE_API void *sqlite3_wal_hook(
126676   sqlite3 *db,                    /* Attach the hook to this db handle */
126677   int(*xCallback)(void *, sqlite3*, const char*, int),
126678   void *pArg                      /* First argument passed to xCallback() */
126679 ){
126680 #ifndef SQLITE_OMIT_WAL
126681   void *pRet;
126682   sqlite3_mutex_enter(db->mutex);
126683   pRet = db->pWalArg;
126684   db->xWalCallback = xCallback;
126685   db->pWalArg = pArg;
126686   sqlite3_mutex_leave(db->mutex);
126687   return pRet;
126688 #else
126689   return 0;
126690 #endif
126691 }
126692 
126693 /*
126694 ** Checkpoint database zDb.
126695 */
126696 SQLITE_API int sqlite3_wal_checkpoint_v2(
126697   sqlite3 *db,                    /* Database handle */
126698   const char *zDb,                /* Name of attached database (or NULL) */
126699   int eMode,                      /* SQLITE_CHECKPOINT_* value */
126700   int *pnLog,                     /* OUT: Size of WAL log in frames */
126701   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
126702 ){
126703 #ifdef SQLITE_OMIT_WAL
126704   return SQLITE_OK;
126705 #else
126706   int rc;                         /* Return code */
126707   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
126708 
126709   /* Initialize the output variables to -1 in case an error occurs. */
126710   if( pnLog ) *pnLog = -1;
126711   if( pnCkpt ) *pnCkpt = -1;
126712 
126713   assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
126714   assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
126715   assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
126716   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
126717     return SQLITE_MISUSE;
126718   }
126719 
126720   sqlite3_mutex_enter(db->mutex);
126721   if( zDb && zDb[0] ){
126722     iDb = sqlite3FindDbName(db, zDb);
126723   }
126724   if( iDb<0 ){
126725     rc = SQLITE_ERROR;
126726     sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
126727   }else{
126728     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
126729     sqlite3Error(db, rc);
126730   }
126731   rc = sqlite3ApiExit(db, rc);
126732   sqlite3_mutex_leave(db->mutex);
126733   return rc;
126734 #endif
126735 }
126736 
126737 
126738 /*
126739 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
126740 ** to contains a zero-length string, all attached databases are
126741 ** checkpointed.
126742 */
126743 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
126744   return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
126745 }
126746 
126747 #ifndef SQLITE_OMIT_WAL
126748 /*
126749 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
126750 ** not currently open in WAL mode.
126751 **
126752 ** If a transaction is open on the database being checkpointed, this
126753 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
126754 ** an error occurs while running the checkpoint, an SQLite error code is
126755 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
126756 **
126757 ** The mutex on database handle db should be held by the caller. The mutex
126758 ** associated with the specific b-tree being checkpointed is taken by
126759 ** this function while the checkpoint is running.
126760 **
126761 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
126762 ** checkpointed. If an error is encountered it is returned immediately -
126763 ** no attempt is made to checkpoint any remaining databases.
126764 **
126765 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
126766 */
126767 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
126768   int rc = SQLITE_OK;             /* Return code */
126769   int i;                          /* Used to iterate through attached dbs */
126770   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
126771 
126772   assert( sqlite3_mutex_held(db->mutex) );
126773   assert( !pnLog || *pnLog==-1 );
126774   assert( !pnCkpt || *pnCkpt==-1 );
126775 
126776   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
126777     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
126778       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
126779       pnLog = 0;
126780       pnCkpt = 0;
126781       if( rc==SQLITE_BUSY ){
126782         bBusy = 1;
126783         rc = SQLITE_OK;
126784       }
126785     }
126786   }
126787 
126788   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
126789 }
126790 #endif /* SQLITE_OMIT_WAL */
126791 
126792 /*
126793 ** This function returns true if main-memory should be used instead of
126794 ** a temporary file for transient pager files and statement journals.
126795 ** The value returned depends on the value of db->temp_store (runtime
126796 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
126797 ** following table describes the relationship between these two values
126798 ** and this functions return value.
126799 **
126800 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
126801 **   -----------------     --------------     ------------------------------
126802 **   0                     any                file      (return 0)
126803 **   1                     1                  file      (return 0)
126804 **   1                     2                  memory    (return 1)
126805 **   1                     0                  file      (return 0)
126806 **   2                     1                  file      (return 0)
126807 **   2                     2                  memory    (return 1)
126808 **   2                     0                  memory    (return 1)
126809 **   3                     any                memory    (return 1)
126810 */
126811 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
126812 #if SQLITE_TEMP_STORE==1
126813   return ( db->temp_store==2 );
126814 #endif
126815 #if SQLITE_TEMP_STORE==2
126816   return ( db->temp_store!=1 );
126817 #endif
126818 #if SQLITE_TEMP_STORE==3
126819   return 1;
126820 #endif
126821 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
126822   return 0;
126823 #endif
126824 }
126825 
126826 /*
126827 ** Return UTF-8 encoded English language explanation of the most recent
126828 ** error.
126829 */
126830 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
126831   const char *z;
126832   if( !db ){
126833     return sqlite3ErrStr(SQLITE_NOMEM);
126834   }
126835   if( !sqlite3SafetyCheckSickOrOk(db) ){
126836     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
126837   }
126838   sqlite3_mutex_enter(db->mutex);
126839   if( db->mallocFailed ){
126840     z = sqlite3ErrStr(SQLITE_NOMEM);
126841   }else{
126842     testcase( db->pErr==0 );
126843     z = (char*)sqlite3_value_text(db->pErr);
126844     assert( !db->mallocFailed );
126845     if( z==0 ){
126846       z = sqlite3ErrStr(db->errCode);
126847     }
126848   }
126849   sqlite3_mutex_leave(db->mutex);
126850   return z;
126851 }
126852 
126853 #ifndef SQLITE_OMIT_UTF16
126854 /*
126855 ** Return UTF-16 encoded English language explanation of the most recent
126856 ** error.
126857 */
126858 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
126859   static const u16 outOfMem[] = {
126860     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
126861   };
126862   static const u16 misuse[] = {
126863     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
126864     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
126865     'c', 'a', 'l', 'l', 'e', 'd', ' ',
126866     'o', 'u', 't', ' ',
126867     'o', 'f', ' ',
126868     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
126869   };
126870 
126871   const void *z;
126872   if( !db ){
126873     return (void *)outOfMem;
126874   }
126875   if( !sqlite3SafetyCheckSickOrOk(db) ){
126876     return (void *)misuse;
126877   }
126878   sqlite3_mutex_enter(db->mutex);
126879   if( db->mallocFailed ){
126880     z = (void *)outOfMem;
126881   }else{
126882     z = sqlite3_value_text16(db->pErr);
126883     if( z==0 ){
126884       sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
126885       z = sqlite3_value_text16(db->pErr);
126886     }
126887     /* A malloc() may have failed within the call to sqlite3_value_text16()
126888     ** above. If this is the case, then the db->mallocFailed flag needs to
126889     ** be cleared before returning. Do this directly, instead of via
126890     ** sqlite3ApiExit(), to avoid setting the database handle error message.
126891     */
126892     db->mallocFailed = 0;
126893   }
126894   sqlite3_mutex_leave(db->mutex);
126895   return z;
126896 }
126897 #endif /* SQLITE_OMIT_UTF16 */
126898 
126899 /*
126900 ** Return the most recent error code generated by an SQLite routine. If NULL is
126901 ** passed to this function, we assume a malloc() failed during sqlite3_open().
126902 */
126903 SQLITE_API int sqlite3_errcode(sqlite3 *db){
126904   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
126905     return SQLITE_MISUSE_BKPT;
126906   }
126907   if( !db || db->mallocFailed ){
126908     return SQLITE_NOMEM;
126909   }
126910   return db->errCode & db->errMask;
126911 }
126912 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
126913   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
126914     return SQLITE_MISUSE_BKPT;
126915   }
126916   if( !db || db->mallocFailed ){
126917     return SQLITE_NOMEM;
126918   }
126919   return db->errCode;
126920 }
126921 
126922 /*
126923 ** Return a string that describes the kind of error specified in the
126924 ** argument.  For now, this simply calls the internal sqlite3ErrStr()
126925 ** function.
126926 */
126927 SQLITE_API const char *sqlite3_errstr(int rc){
126928   return sqlite3ErrStr(rc);
126929 }
126930 
126931 /*
126932 ** Invalidate all cached KeyInfo objects for database connection "db"
126933 */
126934 static void invalidateCachedKeyInfo(sqlite3 *db){
126935   Db *pDb;                    /* A single database */
126936   int iDb;                    /* The database index number */
126937   HashElem *k;                /* For looping over tables in pDb */
126938   Table *pTab;                /* A table in the database */
126939   Index *pIdx;                /* Each index */
126940 
126941   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
126942     if( pDb->pBt==0 ) continue;
126943     sqlite3BtreeEnter(pDb->pBt);
126944     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
126945       pTab = (Table*)sqliteHashData(k);
126946       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
126947         if( pIdx->pKeyInfo && pIdx->pKeyInfo->db==db ){
126948           sqlite3KeyInfoUnref(pIdx->pKeyInfo);
126949           pIdx->pKeyInfo = 0;
126950         }
126951       }
126952     }
126953     sqlite3BtreeLeave(pDb->pBt);
126954   }
126955 }
126956 
126957 /*
126958 ** Create a new collating function for database "db".  The name is zName
126959 ** and the encoding is enc.
126960 */
126961 static int createCollation(
126962   sqlite3* db,
126963   const char *zName,
126964   u8 enc,
126965   void* pCtx,
126966   int(*xCompare)(void*,int,const void*,int,const void*),
126967   void(*xDel)(void*)
126968 ){
126969   CollSeq *pColl;
126970   int enc2;
126971 
126972   assert( sqlite3_mutex_held(db->mutex) );
126973 
126974   /* If SQLITE_UTF16 is specified as the encoding type, transform this
126975   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
126976   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
126977   */
126978   enc2 = enc;
126979   testcase( enc2==SQLITE_UTF16 );
126980   testcase( enc2==SQLITE_UTF16_ALIGNED );
126981   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
126982     enc2 = SQLITE_UTF16NATIVE;
126983   }
126984   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
126985     return SQLITE_MISUSE_BKPT;
126986   }
126987 
126988   /* Check if this call is removing or replacing an existing collation
126989   ** sequence. If so, and there are active VMs, return busy. If there
126990   ** are no active VMs, invalidate any pre-compiled statements.
126991   */
126992   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
126993   if( pColl && pColl->xCmp ){
126994     if( db->nVdbeActive ){
126995       sqlite3ErrorWithMsg(db, SQLITE_BUSY,
126996         "unable to delete/modify collation sequence due to active statements");
126997       return SQLITE_BUSY;
126998     }
126999     sqlite3ExpirePreparedStatements(db);
127000     invalidateCachedKeyInfo(db);
127001 
127002     /* If collation sequence pColl was created directly by a call to
127003     ** sqlite3_create_collation, and not generated by synthCollSeq(),
127004     ** then any copies made by synthCollSeq() need to be invalidated.
127005     ** Also, collation destructor - CollSeq.xDel() - function may need
127006     ** to be called.
127007     */
127008     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
127009       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
127010       int j;
127011       for(j=0; j<3; j++){
127012         CollSeq *p = &aColl[j];
127013         if( p->enc==pColl->enc ){
127014           if( p->xDel ){
127015             p->xDel(p->pUser);
127016           }
127017           p->xCmp = 0;
127018         }
127019       }
127020     }
127021   }
127022 
127023   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
127024   if( pColl==0 ) return SQLITE_NOMEM;
127025   pColl->xCmp = xCompare;
127026   pColl->pUser = pCtx;
127027   pColl->xDel = xDel;
127028   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
127029   sqlite3Error(db, SQLITE_OK);
127030   return SQLITE_OK;
127031 }
127032 
127033 
127034 /*
127035 ** This array defines hard upper bounds on limit values.  The
127036 ** initializer must be kept in sync with the SQLITE_LIMIT_*
127037 ** #defines in sqlite3.h.
127038 */
127039 static const int aHardLimit[] = {
127040   SQLITE_MAX_LENGTH,
127041   SQLITE_MAX_SQL_LENGTH,
127042   SQLITE_MAX_COLUMN,
127043   SQLITE_MAX_EXPR_DEPTH,
127044   SQLITE_MAX_COMPOUND_SELECT,
127045   SQLITE_MAX_VDBE_OP,
127046   SQLITE_MAX_FUNCTION_ARG,
127047   SQLITE_MAX_ATTACHED,
127048   SQLITE_MAX_LIKE_PATTERN_LENGTH,
127049   SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */
127050   SQLITE_MAX_TRIGGER_DEPTH,
127051   SQLITE_MAX_WORKER_THREADS,
127052 };
127053 
127054 /*
127055 ** Make sure the hard limits are set to reasonable values
127056 */
127057 #if SQLITE_MAX_LENGTH<100
127058 # error SQLITE_MAX_LENGTH must be at least 100
127059 #endif
127060 #if SQLITE_MAX_SQL_LENGTH<100
127061 # error SQLITE_MAX_SQL_LENGTH must be at least 100
127062 #endif
127063 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
127064 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
127065 #endif
127066 #if SQLITE_MAX_COMPOUND_SELECT<2
127067 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
127068 #endif
127069 #if SQLITE_MAX_VDBE_OP<40
127070 # error SQLITE_MAX_VDBE_OP must be at least 40
127071 #endif
127072 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
127073 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
127074 #endif
127075 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
127076 # error SQLITE_MAX_ATTACHED must be between 0 and 125
127077 #endif
127078 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
127079 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
127080 #endif
127081 #if SQLITE_MAX_COLUMN>32767
127082 # error SQLITE_MAX_COLUMN must not exceed 32767
127083 #endif
127084 #if SQLITE_MAX_TRIGGER_DEPTH<1
127085 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
127086 #endif
127087 #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
127088 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
127089 #endif
127090 
127091 
127092 /*
127093 ** Change the value of a limit.  Report the old value.
127094 ** If an invalid limit index is supplied, report -1.
127095 ** Make no changes but still report the old value if the
127096 ** new limit is negative.
127097 **
127098 ** A new lower limit does not shrink existing constructs.
127099 ** It merely prevents new constructs that exceed the limit
127100 ** from forming.
127101 */
127102 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
127103   int oldLimit;
127104 
127105 
127106   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
127107   ** there is a hard upper bound set at compile-time by a C preprocessor
127108   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
127109   ** "_MAX_".)
127110   */
127111   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
127112   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
127113   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
127114   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
127115   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
127116   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
127117   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
127118   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
127119   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
127120                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
127121   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
127122   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
127123   assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
127124   assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
127125 
127126 
127127   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
127128     return -1;
127129   }
127130   oldLimit = db->aLimit[limitId];
127131   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
127132     if( newLimit>aHardLimit[limitId] ){
127133       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
127134     }
127135     db->aLimit[limitId] = newLimit;
127136   }
127137   return oldLimit;                     /* IMP: R-53341-35419 */
127138 }
127139 
127140 /*
127141 ** This function is used to parse both URIs and non-URI filenames passed by the
127142 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
127143 ** URIs specified as part of ATTACH statements.
127144 **
127145 ** The first argument to this function is the name of the VFS to use (or
127146 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
127147 ** query parameter. The second argument contains the URI (or non-URI filename)
127148 ** itself. When this function is called the *pFlags variable should contain
127149 ** the default flags to open the database handle with. The value stored in
127150 ** *pFlags may be updated before returning if the URI filename contains
127151 ** "cache=xxx" or "mode=xxx" query parameters.
127152 **
127153 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
127154 ** the VFS that should be used to open the database file. *pzFile is set to
127155 ** point to a buffer containing the name of the file to open. It is the
127156 ** responsibility of the caller to eventually call sqlite3_free() to release
127157 ** this buffer.
127158 **
127159 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
127160 ** may be set to point to a buffer containing an English language error
127161 ** message. It is the responsibility of the caller to eventually release
127162 ** this buffer by calling sqlite3_free().
127163 */
127164 SQLITE_PRIVATE int sqlite3ParseUri(
127165   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
127166   const char *zUri,               /* Nul-terminated URI to parse */
127167   unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
127168   sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
127169   char **pzFile,                  /* OUT: Filename component of URI */
127170   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
127171 ){
127172   int rc = SQLITE_OK;
127173   unsigned int flags = *pFlags;
127174   const char *zVfs = zDefaultVfs;
127175   char *zFile;
127176   char c;
127177   int nUri = sqlite3Strlen30(zUri);
127178 
127179   assert( *pzErrMsg==0 );
127180 
127181   if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
127182    && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
127183   ){
127184     char *zOpt;
127185     int eState;                   /* Parser state when parsing URI */
127186     int iIn;                      /* Input character index */
127187     int iOut = 0;                 /* Output character index */
127188     int nByte = nUri+2;           /* Bytes of space to allocate */
127189 
127190     /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
127191     ** method that there may be extra parameters following the file-name.  */
127192     flags |= SQLITE_OPEN_URI;
127193 
127194     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
127195     zFile = sqlite3_malloc(nByte);
127196     if( !zFile ) return SQLITE_NOMEM;
127197 
127198     iIn = 5;
127199 #ifndef SQLITE_ALLOW_URI_AUTHORITY
127200     /* Discard the scheme and authority segments of the URI. */
127201     if( zUri[5]=='/' && zUri[6]=='/' ){
127202       iIn = 7;
127203       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
127204       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
127205         *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
127206             iIn-7, &zUri[7]);
127207         rc = SQLITE_ERROR;
127208         goto parse_uri_out;
127209       }
127210     }
127211 #endif
127212 
127213     /* Copy the filename and any query parameters into the zFile buffer.
127214     ** Decode %HH escape codes along the way.
127215     **
127216     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
127217     ** on the parsing context. As follows:
127218     **
127219     **   0: Parsing file-name.
127220     **   1: Parsing name section of a name=value query parameter.
127221     **   2: Parsing value section of a name=value query parameter.
127222     */
127223     eState = 0;
127224     while( (c = zUri[iIn])!=0 && c!='#' ){
127225       iIn++;
127226       if( c=='%'
127227        && sqlite3Isxdigit(zUri[iIn])
127228        && sqlite3Isxdigit(zUri[iIn+1])
127229       ){
127230         int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
127231         octet += sqlite3HexToInt(zUri[iIn++]);
127232 
127233         assert( octet>=0 && octet<256 );
127234         if( octet==0 ){
127235           /* This branch is taken when "%00" appears within the URI. In this
127236           ** case we ignore all text in the remainder of the path, name or
127237           ** value currently being parsed. So ignore the current character
127238           ** and skip to the next "?", "=" or "&", as appropriate. */
127239           while( (c = zUri[iIn])!=0 && c!='#'
127240               && (eState!=0 || c!='?')
127241               && (eState!=1 || (c!='=' && c!='&'))
127242               && (eState!=2 || c!='&')
127243           ){
127244             iIn++;
127245           }
127246           continue;
127247         }
127248         c = octet;
127249       }else if( eState==1 && (c=='&' || c=='=') ){
127250         if( zFile[iOut-1]==0 ){
127251           /* An empty option name. Ignore this option altogether. */
127252           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
127253           continue;
127254         }
127255         if( c=='&' ){
127256           zFile[iOut++] = '\0';
127257         }else{
127258           eState = 2;
127259         }
127260         c = 0;
127261       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
127262         c = 0;
127263         eState = 1;
127264       }
127265       zFile[iOut++] = c;
127266     }
127267     if( eState==1 ) zFile[iOut++] = '\0';
127268     zFile[iOut++] = '\0';
127269     zFile[iOut++] = '\0';
127270 
127271     /* Check if there were any options specified that should be interpreted
127272     ** here. Options that are interpreted here include "vfs" and those that
127273     ** correspond to flags that may be passed to the sqlite3_open_v2()
127274     ** method. */
127275     zOpt = &zFile[sqlite3Strlen30(zFile)+1];
127276     while( zOpt[0] ){
127277       int nOpt = sqlite3Strlen30(zOpt);
127278       char *zVal = &zOpt[nOpt+1];
127279       int nVal = sqlite3Strlen30(zVal);
127280 
127281       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
127282         zVfs = zVal;
127283       }else{
127284         struct OpenMode {
127285           const char *z;
127286           int mode;
127287         } *aMode = 0;
127288         char *zModeType = 0;
127289         int mask = 0;
127290         int limit = 0;
127291 
127292         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
127293           static struct OpenMode aCacheMode[] = {
127294             { "shared",  SQLITE_OPEN_SHAREDCACHE },
127295             { "private", SQLITE_OPEN_PRIVATECACHE },
127296             { 0, 0 }
127297           };
127298 
127299           mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
127300           aMode = aCacheMode;
127301           limit = mask;
127302           zModeType = "cache";
127303         }
127304         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
127305           static struct OpenMode aOpenMode[] = {
127306             { "ro",  SQLITE_OPEN_READONLY },
127307             { "rw",  SQLITE_OPEN_READWRITE },
127308             { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
127309             { "memory", SQLITE_OPEN_MEMORY },
127310             { 0, 0 }
127311           };
127312 
127313           mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
127314                    | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
127315           aMode = aOpenMode;
127316           limit = mask & flags;
127317           zModeType = "access";
127318         }
127319 
127320         if( aMode ){
127321           int i;
127322           int mode = 0;
127323           for(i=0; aMode[i].z; i++){
127324             const char *z = aMode[i].z;
127325             if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
127326               mode = aMode[i].mode;
127327               break;
127328             }
127329           }
127330           if( mode==0 ){
127331             *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
127332             rc = SQLITE_ERROR;
127333             goto parse_uri_out;
127334           }
127335           if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
127336             *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
127337                                         zModeType, zVal);
127338             rc = SQLITE_PERM;
127339             goto parse_uri_out;
127340           }
127341           flags = (flags & ~mask) | mode;
127342         }
127343       }
127344 
127345       zOpt = &zVal[nVal+1];
127346     }
127347 
127348   }else{
127349     zFile = sqlite3_malloc(nUri+2);
127350     if( !zFile ) return SQLITE_NOMEM;
127351     memcpy(zFile, zUri, nUri);
127352     zFile[nUri] = '\0';
127353     zFile[nUri+1] = '\0';
127354     flags &= ~SQLITE_OPEN_URI;
127355   }
127356 
127357   *ppVfs = sqlite3_vfs_find(zVfs);
127358   if( *ppVfs==0 ){
127359     *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
127360     rc = SQLITE_ERROR;
127361   }
127362  parse_uri_out:
127363   if( rc!=SQLITE_OK ){
127364     sqlite3_free(zFile);
127365     zFile = 0;
127366   }
127367   *pFlags = flags;
127368   *pzFile = zFile;
127369   return rc;
127370 }
127371 
127372 
127373 /*
127374 ** This routine does the work of opening a database on behalf of
127375 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
127376 ** is UTF-8 encoded.
127377 */
127378 static int openDatabase(
127379   const char *zFilename, /* Database filename UTF-8 encoded */
127380   sqlite3 **ppDb,        /* OUT: Returned database handle */
127381   unsigned int flags,    /* Operational flags */
127382   const char *zVfs       /* Name of the VFS to use */
127383 ){
127384   sqlite3 *db;                    /* Store allocated handle here */
127385   int rc;                         /* Return code */
127386   int isThreadsafe;               /* True for threadsafe connections */
127387   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
127388   char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
127389 
127390   *ppDb = 0;
127391 #ifndef SQLITE_OMIT_AUTOINIT
127392   rc = sqlite3_initialize();
127393   if( rc ) return rc;
127394 #endif
127395 
127396   /* Only allow sensible combinations of bits in the flags argument.
127397   ** Throw an error if any non-sense combination is used.  If we
127398   ** do not block illegal combinations here, it could trigger
127399   ** assert() statements in deeper layers.  Sensible combinations
127400   ** are:
127401   **
127402   **  1:  SQLITE_OPEN_READONLY
127403   **  2:  SQLITE_OPEN_READWRITE
127404   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
127405   */
127406   assert( SQLITE_OPEN_READONLY  == 0x01 );
127407   assert( SQLITE_OPEN_READWRITE == 0x02 );
127408   assert( SQLITE_OPEN_CREATE    == 0x04 );
127409   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
127410   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
127411   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
127412   if( ((1<<(flags&7)) & 0x46)==0 ){
127413     return SQLITE_MISUSE_BKPT;  /* IMP: R-65497-44594 */
127414   }
127415 
127416   if( sqlite3GlobalConfig.bCoreMutex==0 ){
127417     isThreadsafe = 0;
127418   }else if( flags & SQLITE_OPEN_NOMUTEX ){
127419     isThreadsafe = 0;
127420   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
127421     isThreadsafe = 1;
127422   }else{
127423     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
127424   }
127425   if( flags & SQLITE_OPEN_PRIVATECACHE ){
127426     flags &= ~SQLITE_OPEN_SHAREDCACHE;
127427   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
127428     flags |= SQLITE_OPEN_SHAREDCACHE;
127429   }
127430 
127431   /* Remove harmful bits from the flags parameter
127432   **
127433   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
127434   ** dealt with in the previous code block.  Besides these, the only
127435   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
127436   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
127437   ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
127438   ** off all other flags.
127439   */
127440   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
127441                SQLITE_OPEN_EXCLUSIVE |
127442                SQLITE_OPEN_MAIN_DB |
127443                SQLITE_OPEN_TEMP_DB |
127444                SQLITE_OPEN_TRANSIENT_DB |
127445                SQLITE_OPEN_MAIN_JOURNAL |
127446                SQLITE_OPEN_TEMP_JOURNAL |
127447                SQLITE_OPEN_SUBJOURNAL |
127448                SQLITE_OPEN_MASTER_JOURNAL |
127449                SQLITE_OPEN_NOMUTEX |
127450                SQLITE_OPEN_FULLMUTEX |
127451                SQLITE_OPEN_WAL
127452              );
127453 
127454   /* Allocate the sqlite data structure */
127455   db = sqlite3MallocZero( sizeof(sqlite3) );
127456   if( db==0 ) goto opendb_out;
127457   if( isThreadsafe ){
127458     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
127459     if( db->mutex==0 ){
127460       sqlite3_free(db);
127461       db = 0;
127462       goto opendb_out;
127463     }
127464   }
127465   sqlite3_mutex_enter(db->mutex);
127466   db->errMask = 0xff;
127467   db->nDb = 2;
127468   db->magic = SQLITE_MAGIC_BUSY;
127469   db->aDb = db->aDbStatic;
127470 
127471   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
127472   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
127473   db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
127474   db->autoCommit = 1;
127475   db->nextAutovac = -1;
127476   db->szMmap = sqlite3GlobalConfig.szMmap;
127477   db->nextPagesize = 0;
127478   db->nMaxSorterMmap = 0x7FFFFFFF;
127479   db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
127480 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
127481                  | SQLITE_AutoIndex
127482 #endif
127483 #if SQLITE_DEFAULT_FILE_FORMAT<4
127484                  | SQLITE_LegacyFileFmt
127485 #endif
127486 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
127487                  | SQLITE_LoadExtension
127488 #endif
127489 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
127490                  | SQLITE_RecTriggers
127491 #endif
127492 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
127493                  | SQLITE_ForeignKeys
127494 #endif
127495       ;
127496   sqlite3HashInit(&db->aCollSeq);
127497 #ifndef SQLITE_OMIT_VIRTUALTABLE
127498   sqlite3HashInit(&db->aModule);
127499 #endif
127500 
127501   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
127502   ** and UTF-16, so add a version for each to avoid any unnecessary
127503   ** conversions. The only error that can occur here is a malloc() failure.
127504   */
127505   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
127506   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
127507   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
127508   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
127509   if( db->mallocFailed ){
127510     goto opendb_out;
127511   }
127512   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
127513   assert( db->pDfltColl!=0 );
127514 
127515   /* Also add a UTF-8 case-insensitive collation sequence. */
127516   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
127517 
127518   /* Parse the filename/URI argument. */
127519   db->openFlags = flags;
127520   rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
127521   if( rc!=SQLITE_OK ){
127522     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
127523     sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
127524     sqlite3_free(zErrMsg);
127525     goto opendb_out;
127526   }
127527 
127528   /* Open the backend database driver */
127529   rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
127530                         flags | SQLITE_OPEN_MAIN_DB);
127531   if( rc!=SQLITE_OK ){
127532     if( rc==SQLITE_IOERR_NOMEM ){
127533       rc = SQLITE_NOMEM;
127534     }
127535     sqlite3Error(db, rc);
127536     goto opendb_out;
127537   }
127538   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
127539   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
127540 
127541   /* The default safety_level for the main database is 'full'; for the temp
127542   ** database it is 'NONE'. This matches the pager layer defaults.
127543   */
127544   db->aDb[0].zName = "main";
127545   db->aDb[0].safety_level = 3;
127546   db->aDb[1].zName = "temp";
127547   db->aDb[1].safety_level = 1;
127548 
127549   db->magic = SQLITE_MAGIC_OPEN;
127550   if( db->mallocFailed ){
127551     goto opendb_out;
127552   }
127553 
127554   /* Register all built-in functions, but do not attempt to read the
127555   ** database schema yet. This is delayed until the first time the database
127556   ** is accessed.
127557   */
127558   sqlite3Error(db, SQLITE_OK);
127559   sqlite3RegisterBuiltinFunctions(db);
127560 
127561   /* Load automatic extensions - extensions that have been registered
127562   ** using the sqlite3_automatic_extension() API.
127563   */
127564   rc = sqlite3_errcode(db);
127565   if( rc==SQLITE_OK ){
127566     sqlite3AutoLoadExtensions(db);
127567     rc = sqlite3_errcode(db);
127568     if( rc!=SQLITE_OK ){
127569       goto opendb_out;
127570     }
127571   }
127572 
127573 #ifdef SQLITE_ENABLE_FTS1
127574   if( !db->mallocFailed ){
127575     extern int sqlite3Fts1Init(sqlite3*);
127576     rc = sqlite3Fts1Init(db);
127577   }
127578 #endif
127579 
127580 #ifdef SQLITE_ENABLE_FTS2
127581   if( !db->mallocFailed && rc==SQLITE_OK ){
127582     extern int sqlite3Fts2Init(sqlite3*);
127583     rc = sqlite3Fts2Init(db);
127584   }
127585 #endif
127586 
127587 #ifdef SQLITE_ENABLE_FTS3
127588   if( !db->mallocFailed && rc==SQLITE_OK ){
127589     rc = sqlite3Fts3Init(db);
127590   }
127591 #endif
127592 
127593 #ifdef SQLITE_ENABLE_ICU
127594   if( !db->mallocFailed && rc==SQLITE_OK ){
127595     rc = sqlite3IcuInit(db);
127596   }
127597 #endif
127598 
127599 #ifdef SQLITE_ENABLE_RTREE
127600   if( !db->mallocFailed && rc==SQLITE_OK){
127601     rc = sqlite3RtreeInit(db);
127602   }
127603 #endif
127604 
127605   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
127606   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
127607   ** mode.  Doing nothing at all also makes NORMAL the default.
127608   */
127609 #ifdef SQLITE_DEFAULT_LOCKING_MODE
127610   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
127611   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
127612                           SQLITE_DEFAULT_LOCKING_MODE);
127613 #endif
127614 
127615   if( rc ) sqlite3Error(db, rc);
127616 
127617   /* Enable the lookaside-malloc subsystem */
127618   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
127619                         sqlite3GlobalConfig.nLookaside);
127620 
127621   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
127622 
127623 opendb_out:
127624   sqlite3_free(zOpen);
127625   if( db ){
127626     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
127627     sqlite3_mutex_leave(db->mutex);
127628   }
127629   rc = sqlite3_errcode(db);
127630   assert( db!=0 || rc==SQLITE_NOMEM );
127631   if( rc==SQLITE_NOMEM ){
127632     sqlite3_close(db);
127633     db = 0;
127634   }else if( rc!=SQLITE_OK ){
127635     db->magic = SQLITE_MAGIC_SICK;
127636   }
127637   *ppDb = db;
127638 #ifdef SQLITE_ENABLE_SQLLOG
127639   if( sqlite3GlobalConfig.xSqllog ){
127640     /* Opening a db handle. Fourth parameter is passed 0. */
127641     void *pArg = sqlite3GlobalConfig.pSqllogArg;
127642     sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
127643   }
127644 #endif
127645   return sqlite3ApiExit(0, rc);
127646 }
127647 
127648 /*
127649 ** Open a new database handle.
127650 */
127651 SQLITE_API int sqlite3_open(
127652   const char *zFilename,
127653   sqlite3 **ppDb
127654 ){
127655   return openDatabase(zFilename, ppDb,
127656                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
127657 }
127658 SQLITE_API int sqlite3_open_v2(
127659   const char *filename,   /* Database filename (UTF-8) */
127660   sqlite3 **ppDb,         /* OUT: SQLite db handle */
127661   int flags,              /* Flags */
127662   const char *zVfs        /* Name of VFS module to use */
127663 ){
127664   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
127665 }
127666 
127667 #ifndef SQLITE_OMIT_UTF16
127668 /*
127669 ** Open a new database handle.
127670 */
127671 SQLITE_API int sqlite3_open16(
127672   const void *zFilename,
127673   sqlite3 **ppDb
127674 ){
127675   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
127676   sqlite3_value *pVal;
127677   int rc;
127678 
127679   assert( zFilename );
127680   assert( ppDb );
127681   *ppDb = 0;
127682 #ifndef SQLITE_OMIT_AUTOINIT
127683   rc = sqlite3_initialize();
127684   if( rc ) return rc;
127685 #endif
127686   pVal = sqlite3ValueNew(0);
127687   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
127688   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
127689   if( zFilename8 ){
127690     rc = openDatabase(zFilename8, ppDb,
127691                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
127692     assert( *ppDb || rc==SQLITE_NOMEM );
127693     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
127694       ENC(*ppDb) = SQLITE_UTF16NATIVE;
127695     }
127696   }else{
127697     rc = SQLITE_NOMEM;
127698   }
127699   sqlite3ValueFree(pVal);
127700 
127701   return sqlite3ApiExit(0, rc);
127702 }
127703 #endif /* SQLITE_OMIT_UTF16 */
127704 
127705 /*
127706 ** Register a new collation sequence with the database handle db.
127707 */
127708 SQLITE_API int sqlite3_create_collation(
127709   sqlite3* db,
127710   const char *zName,
127711   int enc,
127712   void* pCtx,
127713   int(*xCompare)(void*,int,const void*,int,const void*)
127714 ){
127715   int rc;
127716   sqlite3_mutex_enter(db->mutex);
127717   assert( !db->mallocFailed );
127718   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
127719   rc = sqlite3ApiExit(db, rc);
127720   sqlite3_mutex_leave(db->mutex);
127721   return rc;
127722 }
127723 
127724 /*
127725 ** Register a new collation sequence with the database handle db.
127726 */
127727 SQLITE_API int sqlite3_create_collation_v2(
127728   sqlite3* db,
127729   const char *zName,
127730   int enc,
127731   void* pCtx,
127732   int(*xCompare)(void*,int,const void*,int,const void*),
127733   void(*xDel)(void*)
127734 ){
127735   int rc;
127736   sqlite3_mutex_enter(db->mutex);
127737   assert( !db->mallocFailed );
127738   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
127739   rc = sqlite3ApiExit(db, rc);
127740   sqlite3_mutex_leave(db->mutex);
127741   return rc;
127742 }
127743 
127744 #ifndef SQLITE_OMIT_UTF16
127745 /*
127746 ** Register a new collation sequence with the database handle db.
127747 */
127748 SQLITE_API int sqlite3_create_collation16(
127749   sqlite3* db,
127750   const void *zName,
127751   int enc,
127752   void* pCtx,
127753   int(*xCompare)(void*,int,const void*,int,const void*)
127754 ){
127755   int rc = SQLITE_OK;
127756   char *zName8;
127757   sqlite3_mutex_enter(db->mutex);
127758   assert( !db->mallocFailed );
127759   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
127760   if( zName8 ){
127761     rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
127762     sqlite3DbFree(db, zName8);
127763   }
127764   rc = sqlite3ApiExit(db, rc);
127765   sqlite3_mutex_leave(db->mutex);
127766   return rc;
127767 }
127768 #endif /* SQLITE_OMIT_UTF16 */
127769 
127770 /*
127771 ** Register a collation sequence factory callback with the database handle
127772 ** db. Replace any previously installed collation sequence factory.
127773 */
127774 SQLITE_API int sqlite3_collation_needed(
127775   sqlite3 *db,
127776   void *pCollNeededArg,
127777   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
127778 ){
127779   sqlite3_mutex_enter(db->mutex);
127780   db->xCollNeeded = xCollNeeded;
127781   db->xCollNeeded16 = 0;
127782   db->pCollNeededArg = pCollNeededArg;
127783   sqlite3_mutex_leave(db->mutex);
127784   return SQLITE_OK;
127785 }
127786 
127787 #ifndef SQLITE_OMIT_UTF16
127788 /*
127789 ** Register a collation sequence factory callback with the database handle
127790 ** db. Replace any previously installed collation sequence factory.
127791 */
127792 SQLITE_API int sqlite3_collation_needed16(
127793   sqlite3 *db,
127794   void *pCollNeededArg,
127795   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
127796 ){
127797   sqlite3_mutex_enter(db->mutex);
127798   db->xCollNeeded = 0;
127799   db->xCollNeeded16 = xCollNeeded16;
127800   db->pCollNeededArg = pCollNeededArg;
127801   sqlite3_mutex_leave(db->mutex);
127802   return SQLITE_OK;
127803 }
127804 #endif /* SQLITE_OMIT_UTF16 */
127805 
127806 #ifndef SQLITE_OMIT_DEPRECATED
127807 /*
127808 ** This function is now an anachronism. It used to be used to recover from a
127809 ** malloc() failure, but SQLite now does this automatically.
127810 */
127811 SQLITE_API int sqlite3_global_recover(void){
127812   return SQLITE_OK;
127813 }
127814 #endif
127815 
127816 /*
127817 ** Test to see whether or not the database connection is in autocommit
127818 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
127819 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
127820 ** by the next COMMIT or ROLLBACK.
127821 */
127822 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
127823   return db->autoCommit;
127824 }
127825 
127826 /*
127827 ** The following routines are substitutes for constants SQLITE_CORRUPT,
127828 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
127829 ** constants.  They serve two purposes:
127830 **
127831 **   1.  Serve as a convenient place to set a breakpoint in a debugger
127832 **       to detect when version error conditions occurs.
127833 **
127834 **   2.  Invoke sqlite3_log() to provide the source code location where
127835 **       a low-level error is first detected.
127836 */
127837 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
127838   testcase( sqlite3GlobalConfig.xLog!=0 );
127839   sqlite3_log(SQLITE_CORRUPT,
127840               "database corruption at line %d of [%.10s]",
127841               lineno, 20+sqlite3_sourceid());
127842   return SQLITE_CORRUPT;
127843 }
127844 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
127845   testcase( sqlite3GlobalConfig.xLog!=0 );
127846   sqlite3_log(SQLITE_MISUSE,
127847               "misuse at line %d of [%.10s]",
127848               lineno, 20+sqlite3_sourceid());
127849   return SQLITE_MISUSE;
127850 }
127851 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
127852   testcase( sqlite3GlobalConfig.xLog!=0 );
127853   sqlite3_log(SQLITE_CANTOPEN,
127854               "cannot open file at line %d of [%.10s]",
127855               lineno, 20+sqlite3_sourceid());
127856   return SQLITE_CANTOPEN;
127857 }
127858 
127859 
127860 #ifndef SQLITE_OMIT_DEPRECATED
127861 /*
127862 ** This is a convenience routine that makes sure that all thread-specific
127863 ** data for this thread has been deallocated.
127864 **
127865 ** SQLite no longer uses thread-specific data so this routine is now a
127866 ** no-op.  It is retained for historical compatibility.
127867 */
127868 SQLITE_API void sqlite3_thread_cleanup(void){
127869 }
127870 #endif
127871 
127872 /*
127873 ** Return meta information about a specific column of a database table.
127874 ** See comment in sqlite3.h (sqlite.h.in) for details.
127875 */
127876 #ifdef SQLITE_ENABLE_COLUMN_METADATA
127877 SQLITE_API int sqlite3_table_column_metadata(
127878   sqlite3 *db,                /* Connection handle */
127879   const char *zDbName,        /* Database name or NULL */
127880   const char *zTableName,     /* Table name */
127881   const char *zColumnName,    /* Column name */
127882   char const **pzDataType,    /* OUTPUT: Declared data type */
127883   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
127884   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
127885   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
127886   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
127887 ){
127888   int rc;
127889   char *zErrMsg = 0;
127890   Table *pTab = 0;
127891   Column *pCol = 0;
127892   int iCol;
127893 
127894   char const *zDataType = 0;
127895   char const *zCollSeq = 0;
127896   int notnull = 0;
127897   int primarykey = 0;
127898   int autoinc = 0;
127899 
127900   /* Ensure the database schema has been loaded */
127901   sqlite3_mutex_enter(db->mutex);
127902   sqlite3BtreeEnterAll(db);
127903   rc = sqlite3Init(db, &zErrMsg);
127904   if( SQLITE_OK!=rc ){
127905     goto error_out;
127906   }
127907 
127908   /* Locate the table in question */
127909   pTab = sqlite3FindTable(db, zTableName, zDbName);
127910   if( !pTab || pTab->pSelect ){
127911     pTab = 0;
127912     goto error_out;
127913   }
127914 
127915   /* Find the column for which info is requested */
127916   if( sqlite3IsRowid(zColumnName) ){
127917     iCol = pTab->iPKey;
127918     if( iCol>=0 ){
127919       pCol = &pTab->aCol[iCol];
127920     }
127921   }else{
127922     for(iCol=0; iCol<pTab->nCol; iCol++){
127923       pCol = &pTab->aCol[iCol];
127924       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
127925         break;
127926       }
127927     }
127928     if( iCol==pTab->nCol ){
127929       pTab = 0;
127930       goto error_out;
127931     }
127932   }
127933 
127934   /* The following block stores the meta information that will be returned
127935   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
127936   ** and autoinc. At this point there are two possibilities:
127937   **
127938   **     1. The specified column name was rowid", "oid" or "_rowid_"
127939   **        and there is no explicitly declared IPK column.
127940   **
127941   **     2. The table is not a view and the column name identified an
127942   **        explicitly declared column. Copy meta information from *pCol.
127943   */
127944   if( pCol ){
127945     zDataType = pCol->zType;
127946     zCollSeq = pCol->zColl;
127947     notnull = pCol->notNull!=0;
127948     primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
127949     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
127950   }else{
127951     zDataType = "INTEGER";
127952     primarykey = 1;
127953   }
127954   if( !zCollSeq ){
127955     zCollSeq = "BINARY";
127956   }
127957 
127958 error_out:
127959   sqlite3BtreeLeaveAll(db);
127960 
127961   /* Whether the function call succeeded or failed, set the output parameters
127962   ** to whatever their local counterparts contain. If an error did occur,
127963   ** this has the effect of zeroing all output parameters.
127964   */
127965   if( pzDataType ) *pzDataType = zDataType;
127966   if( pzCollSeq ) *pzCollSeq = zCollSeq;
127967   if( pNotNull ) *pNotNull = notnull;
127968   if( pPrimaryKey ) *pPrimaryKey = primarykey;
127969   if( pAutoinc ) *pAutoinc = autoinc;
127970 
127971   if( SQLITE_OK==rc && !pTab ){
127972     sqlite3DbFree(db, zErrMsg);
127973     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
127974         zColumnName);
127975     rc = SQLITE_ERROR;
127976   }
127977   sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
127978   sqlite3DbFree(db, zErrMsg);
127979   rc = sqlite3ApiExit(db, rc);
127980   sqlite3_mutex_leave(db->mutex);
127981   return rc;
127982 }
127983 #endif
127984 
127985 /*
127986 ** Sleep for a little while.  Return the amount of time slept.
127987 */
127988 SQLITE_API int sqlite3_sleep(int ms){
127989   sqlite3_vfs *pVfs;
127990   int rc;
127991   pVfs = sqlite3_vfs_find(0);
127992   if( pVfs==0 ) return 0;
127993 
127994   /* This function works in milliseconds, but the underlying OsSleep()
127995   ** API uses microseconds. Hence the 1000's.
127996   */
127997   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
127998   return rc;
127999 }
128000 
128001 /*
128002 ** Enable or disable the extended result codes.
128003 */
128004 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
128005   sqlite3_mutex_enter(db->mutex);
128006   db->errMask = onoff ? 0xffffffff : 0xff;
128007   sqlite3_mutex_leave(db->mutex);
128008   return SQLITE_OK;
128009 }
128010 
128011 /*
128012 ** Invoke the xFileControl method on a particular database.
128013 */
128014 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
128015   int rc = SQLITE_ERROR;
128016   Btree *pBtree;
128017 
128018   sqlite3_mutex_enter(db->mutex);
128019   pBtree = sqlite3DbNameToBtree(db, zDbName);
128020   if( pBtree ){
128021     Pager *pPager;
128022     sqlite3_file *fd;
128023     sqlite3BtreeEnter(pBtree);
128024     pPager = sqlite3BtreePager(pBtree);
128025     assert( pPager!=0 );
128026     fd = sqlite3PagerFile(pPager);
128027     assert( fd!=0 );
128028     if( op==SQLITE_FCNTL_FILE_POINTER ){
128029       *(sqlite3_file**)pArg = fd;
128030       rc = SQLITE_OK;
128031     }else if( fd->pMethods ){
128032       rc = sqlite3OsFileControl(fd, op, pArg);
128033     }else{
128034       rc = SQLITE_NOTFOUND;
128035     }
128036     sqlite3BtreeLeave(pBtree);
128037   }
128038   sqlite3_mutex_leave(db->mutex);
128039   return rc;
128040 }
128041 
128042 /*
128043 ** Interface to the testing logic.
128044 */
128045 SQLITE_API int sqlite3_test_control(int op, ...){
128046   int rc = 0;
128047 #ifndef SQLITE_OMIT_BUILTIN_TEST
128048   va_list ap;
128049   va_start(ap, op);
128050   switch( op ){
128051 
128052     /*
128053     ** Save the current state of the PRNG.
128054     */
128055     case SQLITE_TESTCTRL_PRNG_SAVE: {
128056       sqlite3PrngSaveState();
128057       break;
128058     }
128059 
128060     /*
128061     ** Restore the state of the PRNG to the last state saved using
128062     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
128063     ** this verb acts like PRNG_RESET.
128064     */
128065     case SQLITE_TESTCTRL_PRNG_RESTORE: {
128066       sqlite3PrngRestoreState();
128067       break;
128068     }
128069 
128070     /*
128071     ** Reset the PRNG back to its uninitialized state.  The next call
128072     ** to sqlite3_randomness() will reseed the PRNG using a single call
128073     ** to the xRandomness method of the default VFS.
128074     */
128075     case SQLITE_TESTCTRL_PRNG_RESET: {
128076       sqlite3_randomness(0,0);
128077       break;
128078     }
128079 
128080     /*
128081     **  sqlite3_test_control(BITVEC_TEST, size, program)
128082     **
128083     ** Run a test against a Bitvec object of size.  The program argument
128084     ** is an array of integers that defines the test.  Return -1 on a
128085     ** memory allocation error, 0 on success, or non-zero for an error.
128086     ** See the sqlite3BitvecBuiltinTest() for additional information.
128087     */
128088     case SQLITE_TESTCTRL_BITVEC_TEST: {
128089       int sz = va_arg(ap, int);
128090       int *aProg = va_arg(ap, int*);
128091       rc = sqlite3BitvecBuiltinTest(sz, aProg);
128092       break;
128093     }
128094 
128095     /*
128096     **  sqlite3_test_control(FAULT_INSTALL, xCallback)
128097     **
128098     ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
128099     ** if xCallback is not NULL.
128100     **
128101     ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
128102     ** is called immediately after installing the new callback and the return
128103     ** value from sqlite3FaultSim(0) becomes the return from
128104     ** sqlite3_test_control().
128105     */
128106     case SQLITE_TESTCTRL_FAULT_INSTALL: {
128107       /* MSVC is picky about pulling func ptrs from va lists.
128108       ** http://support.microsoft.com/kb/47961
128109       ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
128110       */
128111       typedef int(*TESTCALLBACKFUNC_t)(int);
128112       sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
128113       rc = sqlite3FaultSim(0);
128114       break;
128115     }
128116 
128117     /*
128118     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
128119     **
128120     ** Register hooks to call to indicate which malloc() failures
128121     ** are benign.
128122     */
128123     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
128124       typedef void (*void_function)(void);
128125       void_function xBenignBegin;
128126       void_function xBenignEnd;
128127       xBenignBegin = va_arg(ap, void_function);
128128       xBenignEnd = va_arg(ap, void_function);
128129       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
128130       break;
128131     }
128132 
128133     /*
128134     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
128135     **
128136     ** Set the PENDING byte to the value in the argument, if X>0.
128137     ** Make no changes if X==0.  Return the value of the pending byte
128138     ** as it existing before this routine was called.
128139     **
128140     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
128141     ** an incompatible database file format.  Changing the PENDING byte
128142     ** while any database connection is open results in undefined and
128143     ** deleterious behavior.
128144     */
128145     case SQLITE_TESTCTRL_PENDING_BYTE: {
128146       rc = PENDING_BYTE;
128147 #ifndef SQLITE_OMIT_WSD
128148       {
128149         unsigned int newVal = va_arg(ap, unsigned int);
128150         if( newVal ) sqlite3PendingByte = newVal;
128151       }
128152 #endif
128153       break;
128154     }
128155 
128156     /*
128157     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
128158     **
128159     ** This action provides a run-time test to see whether or not
128160     ** assert() was enabled at compile-time.  If X is true and assert()
128161     ** is enabled, then the return value is true.  If X is true and
128162     ** assert() is disabled, then the return value is zero.  If X is
128163     ** false and assert() is enabled, then the assertion fires and the
128164     ** process aborts.  If X is false and assert() is disabled, then the
128165     ** return value is zero.
128166     */
128167     case SQLITE_TESTCTRL_ASSERT: {
128168       volatile int x = 0;
128169       assert( (x = va_arg(ap,int))!=0 );
128170       rc = x;
128171       break;
128172     }
128173 
128174 
128175     /*
128176     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
128177     **
128178     ** This action provides a run-time test to see how the ALWAYS and
128179     ** NEVER macros were defined at compile-time.
128180     **
128181     ** The return value is ALWAYS(X).
128182     **
128183     ** The recommended test is X==2.  If the return value is 2, that means
128184     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
128185     ** default setting.  If the return value is 1, then ALWAYS() is either
128186     ** hard-coded to true or else it asserts if its argument is false.
128187     ** The first behavior (hard-coded to true) is the case if
128188     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
128189     ** behavior (assert if the argument to ALWAYS() is false) is the case if
128190     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
128191     **
128192     ** The run-time test procedure might look something like this:
128193     **
128194     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
128195     **      // ALWAYS() and NEVER() are no-op pass-through macros
128196     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
128197     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
128198     **    }else{
128199     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
128200     **    }
128201     */
128202     case SQLITE_TESTCTRL_ALWAYS: {
128203       int x = va_arg(ap,int);
128204       rc = ALWAYS(x);
128205       break;
128206     }
128207 
128208     /*
128209     **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
128210     **
128211     ** The integer returned reveals the byte-order of the computer on which
128212     ** SQLite is running:
128213     **
128214     **       1     big-endian,    determined at run-time
128215     **      10     little-endian, determined at run-time
128216     **  432101     big-endian,    determined at compile-time
128217     **  123410     little-endian, determined at compile-time
128218     */
128219     case SQLITE_TESTCTRL_BYTEORDER: {
128220       rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
128221       break;
128222     }
128223 
128224     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
128225     **
128226     ** Set the nReserve size to N for the main database on the database
128227     ** connection db.
128228     */
128229     case SQLITE_TESTCTRL_RESERVE: {
128230       sqlite3 *db = va_arg(ap, sqlite3*);
128231       int x = va_arg(ap,int);
128232       sqlite3_mutex_enter(db->mutex);
128233       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
128234       sqlite3_mutex_leave(db->mutex);
128235       break;
128236     }
128237 
128238     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
128239     **
128240     ** Enable or disable various optimizations for testing purposes.  The
128241     ** argument N is a bitmask of optimizations to be disabled.  For normal
128242     ** operation N should be 0.  The idea is that a test program (like the
128243     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
128244     ** with various optimizations disabled to verify that the same answer
128245     ** is obtained in every case.
128246     */
128247     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
128248       sqlite3 *db = va_arg(ap, sqlite3*);
128249       db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
128250       break;
128251     }
128252 
128253 #ifdef SQLITE_N_KEYWORD
128254     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
128255     **
128256     ** If zWord is a keyword recognized by the parser, then return the
128257     ** number of keywords.  Or if zWord is not a keyword, return 0.
128258     **
128259     ** This test feature is only available in the amalgamation since
128260     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
128261     ** is built using separate source files.
128262     */
128263     case SQLITE_TESTCTRL_ISKEYWORD: {
128264       const char *zWord = va_arg(ap, const char*);
128265       int n = sqlite3Strlen30(zWord);
128266       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
128267       break;
128268     }
128269 #endif
128270 
128271     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
128272     **
128273     ** Pass pFree into sqlite3ScratchFree().
128274     ** If sz>0 then allocate a scratch buffer into pNew.
128275     */
128276     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
128277       void *pFree, **ppNew;
128278       int sz;
128279       sz = va_arg(ap, int);
128280       ppNew = va_arg(ap, void**);
128281       pFree = va_arg(ap, void*);
128282       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
128283       sqlite3ScratchFree(pFree);
128284       break;
128285     }
128286 
128287     /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
128288     **
128289     ** If parameter onoff is non-zero, configure the wrappers so that all
128290     ** subsequent calls to localtime() and variants fail. If onoff is zero,
128291     ** undo this setting.
128292     */
128293     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
128294       sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
128295       break;
128296     }
128297 
128298     /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
128299     **
128300     ** Set or clear a flag that indicates that the database file is always well-
128301     ** formed and never corrupt.  This flag is clear by default, indicating that
128302     ** database files might have arbitrary corruption.  Setting the flag during
128303     ** testing causes certain assert() statements in the code to be activated
128304     ** that demonstrat invariants on well-formed database files.
128305     */
128306     case SQLITE_TESTCTRL_NEVER_CORRUPT: {
128307       sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
128308       break;
128309     }
128310 
128311 
128312     /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
128313     **
128314     ** Set the VDBE coverage callback function to xCallback with context
128315     ** pointer ptr.
128316     */
128317     case SQLITE_TESTCTRL_VDBE_COVERAGE: {
128318 #ifdef SQLITE_VDBE_COVERAGE
128319       typedef void (*branch_callback)(void*,int,u8,u8);
128320       sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
128321       sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
128322 #endif
128323       break;
128324     }
128325 
128326     /*   sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
128327     case SQLITE_TESTCTRL_SORTER_MMAP: {
128328       sqlite3 *db = va_arg(ap, sqlite3*);
128329       db->nMaxSorterMmap = va_arg(ap, int);
128330       break;
128331     }
128332 
128333     /*   sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
128334     **
128335     ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
128336     ** not.
128337     */
128338     case SQLITE_TESTCTRL_ISINIT: {
128339       if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
128340       break;
128341     }
128342   }
128343   va_end(ap);
128344 #endif /* SQLITE_OMIT_BUILTIN_TEST */
128345   return rc;
128346 }
128347 
128348 /*
128349 ** This is a utility routine, useful to VFS implementations, that checks
128350 ** to see if a database file was a URI that contained a specific query
128351 ** parameter, and if so obtains the value of the query parameter.
128352 **
128353 ** The zFilename argument is the filename pointer passed into the xOpen()
128354 ** method of a VFS implementation.  The zParam argument is the name of the
128355 ** query parameter we seek.  This routine returns the value of the zParam
128356 ** parameter if it exists.  If the parameter does not exist, this routine
128357 ** returns a NULL pointer.
128358 */
128359 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
128360   if( zFilename==0 ) return 0;
128361   zFilename += sqlite3Strlen30(zFilename) + 1;
128362   while( zFilename[0] ){
128363     int x = strcmp(zFilename, zParam);
128364     zFilename += sqlite3Strlen30(zFilename) + 1;
128365     if( x==0 ) return zFilename;
128366     zFilename += sqlite3Strlen30(zFilename) + 1;
128367   }
128368   return 0;
128369 }
128370 
128371 /*
128372 ** Return a boolean value for a query parameter.
128373 */
128374 SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
128375   const char *z = sqlite3_uri_parameter(zFilename, zParam);
128376   bDflt = bDflt!=0;
128377   return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
128378 }
128379 
128380 /*
128381 ** Return a 64-bit integer value for a query parameter.
128382 */
128383 SQLITE_API sqlite3_int64 sqlite3_uri_int64(
128384   const char *zFilename,    /* Filename as passed to xOpen */
128385   const char *zParam,       /* URI parameter sought */
128386   sqlite3_int64 bDflt       /* return if parameter is missing */
128387 ){
128388   const char *z = sqlite3_uri_parameter(zFilename, zParam);
128389   sqlite3_int64 v;
128390   if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
128391     bDflt = v;
128392   }
128393   return bDflt;
128394 }
128395 
128396 /*
128397 ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
128398 */
128399 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
128400   int i;
128401   for(i=0; i<db->nDb; i++){
128402     if( db->aDb[i].pBt
128403      && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
128404     ){
128405       return db->aDb[i].pBt;
128406     }
128407   }
128408   return 0;
128409 }
128410 
128411 /*
128412 ** Return the filename of the database associated with a database
128413 ** connection.
128414 */
128415 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
128416   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
128417   return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
128418 }
128419 
128420 /*
128421 ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
128422 ** no such database exists.
128423 */
128424 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
128425   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
128426   return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
128427 }
128428 
128429 /************** End of main.c ************************************************/
128430 /************** Begin file notify.c ******************************************/
128431 /*
128432 ** 2009 March 3
128433 **
128434 ** The author disclaims copyright to this source code.  In place of
128435 ** a legal notice, here is a blessing:
128436 **
128437 **    May you do good and not evil.
128438 **    May you find forgiveness for yourself and forgive others.
128439 **    May you share freely, never taking more than you give.
128440 **
128441 *************************************************************************
128442 **
128443 ** This file contains the implementation of the sqlite3_unlock_notify()
128444 ** API method and its associated functionality.
128445 */
128446 
128447 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
128448 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
128449 
128450 /*
128451 ** Public interfaces:
128452 **
128453 **   sqlite3ConnectionBlocked()
128454 **   sqlite3ConnectionUnlocked()
128455 **   sqlite3ConnectionClosed()
128456 **   sqlite3_unlock_notify()
128457 */
128458 
128459 #define assertMutexHeld() \
128460   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
128461 
128462 /*
128463 ** Head of a linked list of all sqlite3 objects created by this process
128464 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
128465 ** is not NULL. This variable may only accessed while the STATIC_MASTER
128466 ** mutex is held.
128467 */
128468 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
128469 
128470 #ifndef NDEBUG
128471 /*
128472 ** This function is a complex assert() that verifies the following
128473 ** properties of the blocked connections list:
128474 **
128475 **   1) Each entry in the list has a non-NULL value for either
128476 **      pUnlockConnection or pBlockingConnection, or both.
128477 **
128478 **   2) All entries in the list that share a common value for
128479 **      xUnlockNotify are grouped together.
128480 **
128481 **   3) If the argument db is not NULL, then none of the entries in the
128482 **      blocked connections list have pUnlockConnection or pBlockingConnection
128483 **      set to db. This is used when closing connection db.
128484 */
128485 static void checkListProperties(sqlite3 *db){
128486   sqlite3 *p;
128487   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
128488     int seen = 0;
128489     sqlite3 *p2;
128490 
128491     /* Verify property (1) */
128492     assert( p->pUnlockConnection || p->pBlockingConnection );
128493 
128494     /* Verify property (2) */
128495     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
128496       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
128497       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
128498       assert( db==0 || p->pUnlockConnection!=db );
128499       assert( db==0 || p->pBlockingConnection!=db );
128500     }
128501   }
128502 }
128503 #else
128504 # define checkListProperties(x)
128505 #endif
128506 
128507 /*
128508 ** Remove connection db from the blocked connections list. If connection
128509 ** db is not currently a part of the list, this function is a no-op.
128510 */
128511 static void removeFromBlockedList(sqlite3 *db){
128512   sqlite3 **pp;
128513   assertMutexHeld();
128514   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
128515     if( *pp==db ){
128516       *pp = (*pp)->pNextBlocked;
128517       break;
128518     }
128519   }
128520 }
128521 
128522 /*
128523 ** Add connection db to the blocked connections list. It is assumed
128524 ** that it is not already a part of the list.
128525 */
128526 static void addToBlockedList(sqlite3 *db){
128527   sqlite3 **pp;
128528   assertMutexHeld();
128529   for(
128530     pp=&sqlite3BlockedList;
128531     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
128532     pp=&(*pp)->pNextBlocked
128533   );
128534   db->pNextBlocked = *pp;
128535   *pp = db;
128536 }
128537 
128538 /*
128539 ** Obtain the STATIC_MASTER mutex.
128540 */
128541 static void enterMutex(void){
128542   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
128543   checkListProperties(0);
128544 }
128545 
128546 /*
128547 ** Release the STATIC_MASTER mutex.
128548 */
128549 static void leaveMutex(void){
128550   assertMutexHeld();
128551   checkListProperties(0);
128552   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
128553 }
128554 
128555 /*
128556 ** Register an unlock-notify callback.
128557 **
128558 ** This is called after connection "db" has attempted some operation
128559 ** but has received an SQLITE_LOCKED error because another connection
128560 ** (call it pOther) in the same process was busy using the same shared
128561 ** cache.  pOther is found by looking at db->pBlockingConnection.
128562 **
128563 ** If there is no blocking connection, the callback is invoked immediately,
128564 ** before this routine returns.
128565 **
128566 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
128567 ** a deadlock.
128568 **
128569 ** Otherwise, make arrangements to invoke xNotify when pOther drops
128570 ** its locks.
128571 **
128572 ** Each call to this routine overrides any prior callbacks registered
128573 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
128574 ** cancelled.
128575 */
128576 SQLITE_API int sqlite3_unlock_notify(
128577   sqlite3 *db,
128578   void (*xNotify)(void **, int),
128579   void *pArg
128580 ){
128581   int rc = SQLITE_OK;
128582 
128583   sqlite3_mutex_enter(db->mutex);
128584   enterMutex();
128585 
128586   if( xNotify==0 ){
128587     removeFromBlockedList(db);
128588     db->pBlockingConnection = 0;
128589     db->pUnlockConnection = 0;
128590     db->xUnlockNotify = 0;
128591     db->pUnlockArg = 0;
128592   }else if( 0==db->pBlockingConnection ){
128593     /* The blocking transaction has been concluded. Or there never was a
128594     ** blocking transaction. In either case, invoke the notify callback
128595     ** immediately.
128596     */
128597     xNotify(&pArg, 1);
128598   }else{
128599     sqlite3 *p;
128600 
128601     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
128602     if( p ){
128603       rc = SQLITE_LOCKED;              /* Deadlock detected. */
128604     }else{
128605       db->pUnlockConnection = db->pBlockingConnection;
128606       db->xUnlockNotify = xNotify;
128607       db->pUnlockArg = pArg;
128608       removeFromBlockedList(db);
128609       addToBlockedList(db);
128610     }
128611   }
128612 
128613   leaveMutex();
128614   assert( !db->mallocFailed );
128615   sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
128616   sqlite3_mutex_leave(db->mutex);
128617   return rc;
128618 }
128619 
128620 /*
128621 ** This function is called while stepping or preparing a statement
128622 ** associated with connection db. The operation will return SQLITE_LOCKED
128623 ** to the user because it requires a lock that will not be available
128624 ** until connection pBlocker concludes its current transaction.
128625 */
128626 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
128627   enterMutex();
128628   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
128629     addToBlockedList(db);
128630   }
128631   db->pBlockingConnection = pBlocker;
128632   leaveMutex();
128633 }
128634 
128635 /*
128636 ** This function is called when
128637 ** the transaction opened by database db has just finished. Locks held
128638 ** by database connection db have been released.
128639 **
128640 ** This function loops through each entry in the blocked connections
128641 ** list and does the following:
128642 **
128643 **   1) If the sqlite3.pBlockingConnection member of a list entry is
128644 **      set to db, then set pBlockingConnection=0.
128645 **
128646 **   2) If the sqlite3.pUnlockConnection member of a list entry is
128647 **      set to db, then invoke the configured unlock-notify callback and
128648 **      set pUnlockConnection=0.
128649 **
128650 **   3) If the two steps above mean that pBlockingConnection==0 and
128651 **      pUnlockConnection==0, remove the entry from the blocked connections
128652 **      list.
128653 */
128654 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
128655   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
128656   int nArg = 0;                            /* Number of entries in aArg[] */
128657   sqlite3 **pp;                            /* Iterator variable */
128658   void **aArg;               /* Arguments to the unlock callback */
128659   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
128660   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
128661 
128662   aArg = aStatic;
128663   enterMutex();         /* Enter STATIC_MASTER mutex */
128664 
128665   /* This loop runs once for each entry in the blocked-connections list. */
128666   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
128667     sqlite3 *p = *pp;
128668 
128669     /* Step 1. */
128670     if( p->pBlockingConnection==db ){
128671       p->pBlockingConnection = 0;
128672     }
128673 
128674     /* Step 2. */
128675     if( p->pUnlockConnection==db ){
128676       assert( p->xUnlockNotify );
128677       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
128678         xUnlockNotify(aArg, nArg);
128679         nArg = 0;
128680       }
128681 
128682       sqlite3BeginBenignMalloc();
128683       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
128684       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
128685       if( (!aDyn && nArg==(int)ArraySize(aStatic))
128686        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
128687       ){
128688         /* The aArg[] array needs to grow. */
128689         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
128690         if( pNew ){
128691           memcpy(pNew, aArg, nArg*sizeof(void *));
128692           sqlite3_free(aDyn);
128693           aDyn = aArg = pNew;
128694         }else{
128695           /* This occurs when the array of context pointers that need to
128696           ** be passed to the unlock-notify callback is larger than the
128697           ** aStatic[] array allocated on the stack and the attempt to
128698           ** allocate a larger array from the heap has failed.
128699           **
128700           ** This is a difficult situation to handle. Returning an error
128701           ** code to the caller is insufficient, as even if an error code
128702           ** is returned the transaction on connection db will still be
128703           ** closed and the unlock-notify callbacks on blocked connections
128704           ** will go unissued. This might cause the application to wait
128705           ** indefinitely for an unlock-notify callback that will never
128706           ** arrive.
128707           **
128708           ** Instead, invoke the unlock-notify callback with the context
128709           ** array already accumulated. We can then clear the array and
128710           ** begin accumulating any further context pointers without
128711           ** requiring any dynamic allocation. This is sub-optimal because
128712           ** it means that instead of one callback with a large array of
128713           ** context pointers the application will receive two or more
128714           ** callbacks with smaller arrays of context pointers, which will
128715           ** reduce the applications ability to prioritize multiple
128716           ** connections. But it is the best that can be done under the
128717           ** circumstances.
128718           */
128719           xUnlockNotify(aArg, nArg);
128720           nArg = 0;
128721         }
128722       }
128723       sqlite3EndBenignMalloc();
128724 
128725       aArg[nArg++] = p->pUnlockArg;
128726       xUnlockNotify = p->xUnlockNotify;
128727       p->pUnlockConnection = 0;
128728       p->xUnlockNotify = 0;
128729       p->pUnlockArg = 0;
128730     }
128731 
128732     /* Step 3. */
128733     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
128734       /* Remove connection p from the blocked connections list. */
128735       *pp = p->pNextBlocked;
128736       p->pNextBlocked = 0;
128737     }else{
128738       pp = &p->pNextBlocked;
128739     }
128740   }
128741 
128742   if( nArg!=0 ){
128743     xUnlockNotify(aArg, nArg);
128744   }
128745   sqlite3_free(aDyn);
128746   leaveMutex();         /* Leave STATIC_MASTER mutex */
128747 }
128748 
128749 /*
128750 ** This is called when the database connection passed as an argument is
128751 ** being closed. The connection is removed from the blocked list.
128752 */
128753 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
128754   sqlite3ConnectionUnlocked(db);
128755   enterMutex();
128756   removeFromBlockedList(db);
128757   checkListProperties(db);
128758   leaveMutex();
128759 }
128760 #endif
128761 
128762 /************** End of notify.c **********************************************/
128763 /************** Begin file fts3.c ********************************************/
128764 /*
128765 ** 2006 Oct 10
128766 **
128767 ** The author disclaims copyright to this source code.  In place of
128768 ** a legal notice, here is a blessing:
128769 **
128770 **    May you do good and not evil.
128771 **    May you find forgiveness for yourself and forgive others.
128772 **    May you share freely, never taking more than you give.
128773 **
128774 ******************************************************************************
128775 **
128776 ** This is an SQLite module implementing full-text search.
128777 */
128778 
128779 /*
128780 ** The code in this file is only compiled if:
128781 **
128782 **     * The FTS3 module is being built as an extension
128783 **       (in which case SQLITE_CORE is not defined), or
128784 **
128785 **     * The FTS3 module is being built into the core of
128786 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
128787 */
128788 
128789 /* The full-text index is stored in a series of b+tree (-like)
128790 ** structures called segments which map terms to doclists.  The
128791 ** structures are like b+trees in layout, but are constructed from the
128792 ** bottom up in optimal fashion and are not updatable.  Since trees
128793 ** are built from the bottom up, things will be described from the
128794 ** bottom up.
128795 **
128796 **
128797 **** Varints ****
128798 ** The basic unit of encoding is a variable-length integer called a
128799 ** varint.  We encode variable-length integers in little-endian order
128800 ** using seven bits * per byte as follows:
128801 **
128802 ** KEY:
128803 **         A = 0xxxxxxx    7 bits of data and one flag bit
128804 **         B = 1xxxxxxx    7 bits of data and one flag bit
128805 **
128806 **  7 bits - A
128807 ** 14 bits - BA
128808 ** 21 bits - BBA
128809 ** and so on.
128810 **
128811 ** This is similar in concept to how sqlite encodes "varints" but
128812 ** the encoding is not the same.  SQLite varints are big-endian
128813 ** are are limited to 9 bytes in length whereas FTS3 varints are
128814 ** little-endian and can be up to 10 bytes in length (in theory).
128815 **
128816 ** Example encodings:
128817 **
128818 **     1:    0x01
128819 **   127:    0x7f
128820 **   128:    0x81 0x00
128821 **
128822 **
128823 **** Document lists ****
128824 ** A doclist (document list) holds a docid-sorted list of hits for a
128825 ** given term.  Doclists hold docids and associated token positions.
128826 ** A docid is the unique integer identifier for a single document.
128827 ** A position is the index of a word within the document.  The first
128828 ** word of the document has a position of 0.
128829 **
128830 ** FTS3 used to optionally store character offsets using a compile-time
128831 ** option.  But that functionality is no longer supported.
128832 **
128833 ** A doclist is stored like this:
128834 **
128835 ** array {
128836 **   varint docid;          (delta from previous doclist)
128837 **   array {                (position list for column 0)
128838 **     varint position;     (2 more than the delta from previous position)
128839 **   }
128840 **   array {
128841 **     varint POS_COLUMN;   (marks start of position list for new column)
128842 **     varint column;       (index of new column)
128843 **     array {
128844 **       varint position;   (2 more than the delta from previous position)
128845 **     }
128846 **   }
128847 **   varint POS_END;        (marks end of positions for this document.
128848 ** }
128849 **
128850 ** Here, array { X } means zero or more occurrences of X, adjacent in
128851 ** memory.  A "position" is an index of a token in the token stream
128852 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
128853 ** in the same logical place as the position element, and act as sentinals
128854 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
128855 ** The positions numbers are not stored literally but rather as two more
128856 ** than the difference from the prior position, or the just the position plus
128857 ** 2 for the first position.  Example:
128858 **
128859 **   label:       A B C D E  F  G H   I  J K
128860 **   value:     123 5 9 1 1 14 35 0 234 72 0
128861 **
128862 ** The 123 value is the first docid.  For column zero in this document
128863 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
128864 ** at D signals the start of a new column; the 1 at E indicates that the
128865 ** new column is column number 1.  There are two positions at 12 and 45
128866 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
128867 ** 234 at I is the delta to next docid (357).  It has one position 70
128868 ** (72-2) and then terminates with the 0 at K.
128869 **
128870 ** A "position-list" is the list of positions for multiple columns for
128871 ** a single docid.  A "column-list" is the set of positions for a single
128872 ** column.  Hence, a position-list consists of one or more column-lists,
128873 ** a document record consists of a docid followed by a position-list and
128874 ** a doclist consists of one or more document records.
128875 **
128876 ** A bare doclist omits the position information, becoming an
128877 ** array of varint-encoded docids.
128878 **
128879 **** Segment leaf nodes ****
128880 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
128881 ** nodes are written using LeafWriter, and read using LeafReader (to
128882 ** iterate through a single leaf node's data) and LeavesReader (to
128883 ** iterate through a segment's entire leaf layer).  Leaf nodes have
128884 ** the format:
128885 **
128886 ** varint iHeight;             (height from leaf level, always 0)
128887 ** varint nTerm;               (length of first term)
128888 ** char pTerm[nTerm];          (content of first term)
128889 ** varint nDoclist;            (length of term's associated doclist)
128890 ** char pDoclist[nDoclist];    (content of doclist)
128891 ** array {
128892 **                             (further terms are delta-encoded)
128893 **   varint nPrefix;           (length of prefix shared with previous term)
128894 **   varint nSuffix;           (length of unshared suffix)
128895 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
128896 **   varint nDoclist;          (length of term's associated doclist)
128897 **   char pDoclist[nDoclist];  (content of doclist)
128898 ** }
128899 **
128900 ** Here, array { X } means zero or more occurrences of X, adjacent in
128901 ** memory.
128902 **
128903 ** Leaf nodes are broken into blocks which are stored contiguously in
128904 ** the %_segments table in sorted order.  This means that when the end
128905 ** of a node is reached, the next term is in the node with the next
128906 ** greater node id.
128907 **
128908 ** New data is spilled to a new leaf node when the current node
128909 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
128910 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
128911 ** node (a leaf node with a single term and doclist).  The goal of
128912 ** these settings is to pack together groups of small doclists while
128913 ** making it efficient to directly access large doclists.  The
128914 ** assumption is that large doclists represent terms which are more
128915 ** likely to be query targets.
128916 **
128917 ** TODO(shess) It may be useful for blocking decisions to be more
128918 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
128919 ** node rather than splitting into 2k and .5k nodes.  My intuition is
128920 ** that this might extend through 2x or 4x the pagesize.
128921 **
128922 **
128923 **** Segment interior nodes ****
128924 ** Segment interior nodes store blockids for subtree nodes and terms
128925 ** to describe what data is stored by the each subtree.  Interior
128926 ** nodes are written using InteriorWriter, and read using
128927 ** InteriorReader.  InteriorWriters are created as needed when
128928 ** SegmentWriter creates new leaf nodes, or when an interior node
128929 ** itself grows too big and must be split.  The format of interior
128930 ** nodes:
128931 **
128932 ** varint iHeight;           (height from leaf level, always >0)
128933 ** varint iBlockid;          (block id of node's leftmost subtree)
128934 ** optional {
128935 **   varint nTerm;           (length of first term)
128936 **   char pTerm[nTerm];      (content of first term)
128937 **   array {
128938 **                                (further terms are delta-encoded)
128939 **     varint nPrefix;            (length of shared prefix with previous term)
128940 **     varint nSuffix;            (length of unshared suffix)
128941 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
128942 **   }
128943 ** }
128944 **
128945 ** Here, optional { X } means an optional element, while array { X }
128946 ** means zero or more occurrences of X, adjacent in memory.
128947 **
128948 ** An interior node encodes n terms separating n+1 subtrees.  The
128949 ** subtree blocks are contiguous, so only the first subtree's blockid
128950 ** is encoded.  The subtree at iBlockid will contain all terms less
128951 ** than the first term encoded (or all terms if no term is encoded).
128952 ** Otherwise, for terms greater than or equal to pTerm[i] but less
128953 ** than pTerm[i+1], the subtree for that term will be rooted at
128954 ** iBlockid+i.  Interior nodes only store enough term data to
128955 ** distinguish adjacent children (if the rightmost term of the left
128956 ** child is "something", and the leftmost term of the right child is
128957 ** "wicked", only "w" is stored).
128958 **
128959 ** New data is spilled to a new interior node at the same height when
128960 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
128961 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
128962 ** interior nodes and making the tree too skinny.  The interior nodes
128963 ** at a given height are naturally tracked by interior nodes at
128964 ** height+1, and so on.
128965 **
128966 **
128967 **** Segment directory ****
128968 ** The segment directory in table %_segdir stores meta-information for
128969 ** merging and deleting segments, and also the root node of the
128970 ** segment's tree.
128971 **
128972 ** The root node is the top node of the segment's tree after encoding
128973 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
128974 ** This could be either a leaf node or an interior node.  If the top
128975 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
128976 ** and a new root interior node is generated (which should always fit
128977 ** within ROOT_MAX because it only needs space for 2 varints, the
128978 ** height and the blockid of the previous root).
128979 **
128980 ** The meta-information in the segment directory is:
128981 **   level               - segment level (see below)
128982 **   idx                 - index within level
128983 **                       - (level,idx uniquely identify a segment)
128984 **   start_block         - first leaf node
128985 **   leaves_end_block    - last leaf node
128986 **   end_block           - last block (including interior nodes)
128987 **   root                - contents of root node
128988 **
128989 ** If the root node is a leaf node, then start_block,
128990 ** leaves_end_block, and end_block are all 0.
128991 **
128992 **
128993 **** Segment merging ****
128994 ** To amortize update costs, segments are grouped into levels and
128995 ** merged in batches.  Each increase in level represents exponentially
128996 ** more documents.
128997 **
128998 ** New documents (actually, document updates) are tokenized and
128999 ** written individually (using LeafWriter) to a level 0 segment, with
129000 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
129001 ** level 0 segments are merged into a single level 1 segment.  Level 1
129002 ** is populated like level 0, and eventually MERGE_COUNT level 1
129003 ** segments are merged to a single level 2 segment (representing
129004 ** MERGE_COUNT^2 updates), and so on.
129005 **
129006 ** A segment merge traverses all segments at a given level in
129007 ** parallel, performing a straightforward sorted merge.  Since segment
129008 ** leaf nodes are written in to the %_segments table in order, this
129009 ** merge traverses the underlying sqlite disk structures efficiently.
129010 ** After the merge, all segment blocks from the merged level are
129011 ** deleted.
129012 **
129013 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
129014 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
129015 ** very similar performance numbers to 16 on insertion, though they're
129016 ** a tiny bit slower (perhaps due to more overhead in merge-time
129017 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
129018 ** 16, 2 about 66% slower than 16.
129019 **
129020 ** At query time, high MERGE_COUNT increases the number of segments
129021 ** which need to be scanned and merged.  For instance, with 100k docs
129022 ** inserted:
129023 **
129024 **    MERGE_COUNT   segments
129025 **       16           25
129026 **        8           12
129027 **        4           10
129028 **        2            6
129029 **
129030 ** This appears to have only a moderate impact on queries for very
129031 ** frequent terms (which are somewhat dominated by segment merge
129032 ** costs), and infrequent and non-existent terms still seem to be fast
129033 ** even with many segments.
129034 **
129035 ** TODO(shess) That said, it would be nice to have a better query-side
129036 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
129037 ** optimizations to things like doclist merging will swing the sweet
129038 ** spot around.
129039 **
129040 **
129041 **
129042 **** Handling of deletions and updates ****
129043 ** Since we're using a segmented structure, with no docid-oriented
129044 ** index into the term index, we clearly cannot simply update the term
129045 ** index when a document is deleted or updated.  For deletions, we
129046 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
129047 ** we simply write the new doclist.  Segment merges overwrite older
129048 ** data for a particular docid with newer data, so deletes or updates
129049 ** will eventually overtake the earlier data and knock it out.  The
129050 ** query logic likewise merges doclists so that newer data knocks out
129051 ** older data.
129052 */
129053 
129054 /************** Include fts3Int.h in the middle of fts3.c ********************/
129055 /************** Begin file fts3Int.h *****************************************/
129056 /*
129057 ** 2009 Nov 12
129058 **
129059 ** The author disclaims copyright to this source code.  In place of
129060 ** a legal notice, here is a blessing:
129061 **
129062 **    May you do good and not evil.
129063 **    May you find forgiveness for yourself and forgive others.
129064 **    May you share freely, never taking more than you give.
129065 **
129066 ******************************************************************************
129067 **
129068 */
129069 #ifndef _FTSINT_H
129070 #define _FTSINT_H
129071 
129072 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
129073 # define NDEBUG 1
129074 #endif
129075 
129076 /*
129077 ** FTS4 is really an extension for FTS3.  It is enabled using the
129078 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
129079 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
129080 */
129081 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
129082 # define SQLITE_ENABLE_FTS3
129083 #endif
129084 
129085 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
129086 
129087 /* If not building as part of the core, include sqlite3ext.h. */
129088 #ifndef SQLITE_CORE
129089 SQLITE_EXTENSION_INIT3
129090 #endif
129091 
129092 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
129093 /************** Begin file fts3_tokenizer.h **********************************/
129094 /*
129095 ** 2006 July 10
129096 **
129097 ** The author disclaims copyright to this source code.
129098 **
129099 *************************************************************************
129100 ** Defines the interface to tokenizers used by fulltext-search.  There
129101 ** are three basic components:
129102 **
129103 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
129104 ** interface functions.  This is essentially the class structure for
129105 ** tokenizers.
129106 **
129107 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
129108 ** including customization information defined at creation time.
129109 **
129110 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
129111 ** tokens from a particular input.
129112 */
129113 #ifndef _FTS3_TOKENIZER_H_
129114 #define _FTS3_TOKENIZER_H_
129115 
129116 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
129117 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
129118 ** we will need a way to register the API consistently.
129119 */
129120 
129121 /*
129122 ** Structures used by the tokenizer interface. When a new tokenizer
129123 ** implementation is registered, the caller provides a pointer to
129124 ** an sqlite3_tokenizer_module containing pointers to the callback
129125 ** functions that make up an implementation.
129126 **
129127 ** When an fts3 table is created, it passes any arguments passed to
129128 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
129129 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
129130 ** implementation. The xCreate() function in turn returns an
129131 ** sqlite3_tokenizer structure representing the specific tokenizer to
129132 ** be used for the fts3 table (customized by the tokenizer clause arguments).
129133 **
129134 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
129135 ** method is called. It returns an sqlite3_tokenizer_cursor object
129136 ** that may be used to tokenize a specific input buffer based on
129137 ** the tokenization rules supplied by a specific sqlite3_tokenizer
129138 ** object.
129139 */
129140 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
129141 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
129142 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
129143 
129144 struct sqlite3_tokenizer_module {
129145 
129146   /*
129147   ** Structure version. Should always be set to 0 or 1.
129148   */
129149   int iVersion;
129150 
129151   /*
129152   ** Create a new tokenizer. The values in the argv[] array are the
129153   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
129154   ** TABLE statement that created the fts3 table. For example, if
129155   ** the following SQL is executed:
129156   **
129157   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
129158   **
129159   ** then argc is set to 2, and the argv[] array contains pointers
129160   ** to the strings "arg1" and "arg2".
129161   **
129162   ** This method should return either SQLITE_OK (0), or an SQLite error
129163   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
129164   ** to point at the newly created tokenizer structure. The generic
129165   ** sqlite3_tokenizer.pModule variable should not be initialized by
129166   ** this callback. The caller will do so.
129167   */
129168   int (*xCreate)(
129169     int argc,                           /* Size of argv array */
129170     const char *const*argv,             /* Tokenizer argument strings */
129171     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
129172   );
129173 
129174   /*
129175   ** Destroy an existing tokenizer. The fts3 module calls this method
129176   ** exactly once for each successful call to xCreate().
129177   */
129178   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
129179 
129180   /*
129181   ** Create a tokenizer cursor to tokenize an input buffer. The caller
129182   ** is responsible for ensuring that the input buffer remains valid
129183   ** until the cursor is closed (using the xClose() method).
129184   */
129185   int (*xOpen)(
129186     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
129187     const char *pInput, int nBytes,      /* Input buffer */
129188     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
129189   );
129190 
129191   /*
129192   ** Destroy an existing tokenizer cursor. The fts3 module calls this
129193   ** method exactly once for each successful call to xOpen().
129194   */
129195   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
129196 
129197   /*
129198   ** Retrieve the next token from the tokenizer cursor pCursor. This
129199   ** method should either return SQLITE_OK and set the values of the
129200   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
129201   ** the end of the buffer has been reached, or an SQLite error code.
129202   **
129203   ** *ppToken should be set to point at a buffer containing the
129204   ** normalized version of the token (i.e. after any case-folding and/or
129205   ** stemming has been performed). *pnBytes should be set to the length
129206   ** of this buffer in bytes. The input text that generated the token is
129207   ** identified by the byte offsets returned in *piStartOffset and
129208   ** *piEndOffset. *piStartOffset should be set to the index of the first
129209   ** byte of the token in the input buffer. *piEndOffset should be set
129210   ** to the index of the first byte just past the end of the token in
129211   ** the input buffer.
129212   **
129213   ** The buffer *ppToken is set to point at is managed by the tokenizer
129214   ** implementation. It is only required to be valid until the next call
129215   ** to xNext() or xClose().
129216   */
129217   /* TODO(shess) current implementation requires pInput to be
129218   ** nul-terminated.  This should either be fixed, or pInput/nBytes
129219   ** should be converted to zInput.
129220   */
129221   int (*xNext)(
129222     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
129223     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
129224     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
129225     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
129226     int *piPosition      /* OUT: Number of tokens returned before this one */
129227   );
129228 
129229   /***********************************************************************
129230   ** Methods below this point are only available if iVersion>=1.
129231   */
129232 
129233   /*
129234   ** Configure the language id of a tokenizer cursor.
129235   */
129236   int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
129237 };
129238 
129239 struct sqlite3_tokenizer {
129240   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
129241   /* Tokenizer implementations will typically add additional fields */
129242 };
129243 
129244 struct sqlite3_tokenizer_cursor {
129245   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
129246   /* Tokenizer implementations will typically add additional fields */
129247 };
129248 
129249 int fts3_global_term_cnt(int iTerm, int iCol);
129250 int fts3_term_cnt(int iTerm, int iCol);
129251 
129252 
129253 #endif /* _FTS3_TOKENIZER_H_ */
129254 
129255 /************** End of fts3_tokenizer.h **************************************/
129256 /************** Continuing where we left off in fts3Int.h ********************/
129257 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
129258 /************** Begin file fts3_hash.h ***************************************/
129259 /*
129260 ** 2001 September 22
129261 **
129262 ** The author disclaims copyright to this source code.  In place of
129263 ** a legal notice, here is a blessing:
129264 **
129265 **    May you do good and not evil.
129266 **    May you find forgiveness for yourself and forgive others.
129267 **    May you share freely, never taking more than you give.
129268 **
129269 *************************************************************************
129270 ** This is the header file for the generic hash-table implementation
129271 ** used in SQLite.  We've modified it slightly to serve as a standalone
129272 ** hash table implementation for the full-text indexing module.
129273 **
129274 */
129275 #ifndef _FTS3_HASH_H_
129276 #define _FTS3_HASH_H_
129277 
129278 /* Forward declarations of structures. */
129279 typedef struct Fts3Hash Fts3Hash;
129280 typedef struct Fts3HashElem Fts3HashElem;
129281 
129282 /* A complete hash table is an instance of the following structure.
129283 ** The internals of this structure are intended to be opaque -- client
129284 ** code should not attempt to access or modify the fields of this structure
129285 ** directly.  Change this structure only by using the routines below.
129286 ** However, many of the "procedures" and "functions" for modifying and
129287 ** accessing this structure are really macros, so we can't really make
129288 ** this structure opaque.
129289 */
129290 struct Fts3Hash {
129291   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
129292   char copyKey;           /* True if copy of key made on insert */
129293   int count;              /* Number of entries in this table */
129294   Fts3HashElem *first;    /* The first element of the array */
129295   int htsize;             /* Number of buckets in the hash table */
129296   struct _fts3ht {        /* the hash table */
129297     int count;               /* Number of entries with this hash */
129298     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
129299   } *ht;
129300 };
129301 
129302 /* Each element in the hash table is an instance of the following
129303 ** structure.  All elements are stored on a single doubly-linked list.
129304 **
129305 ** Again, this structure is intended to be opaque, but it can't really
129306 ** be opaque because it is used by macros.
129307 */
129308 struct Fts3HashElem {
129309   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
129310   void *data;                /* Data associated with this element */
129311   void *pKey; int nKey;      /* Key associated with this element */
129312 };
129313 
129314 /*
129315 ** There are 2 different modes of operation for a hash table:
129316 **
129317 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
129318 **                           (including the null-terminator, if any).  Case
129319 **                           is respected in comparisons.
129320 **
129321 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
129322 **                           memcmp() is used to compare keys.
129323 **
129324 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
129325 */
129326 #define FTS3_HASH_STRING    1
129327 #define FTS3_HASH_BINARY    2
129328 
129329 /*
129330 ** Access routines.  To delete, insert a NULL pointer.
129331 */
129332 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
129333 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
129334 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
129335 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
129336 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
129337 
129338 /*
129339 ** Shorthand for the functions above
129340 */
129341 #define fts3HashInit     sqlite3Fts3HashInit
129342 #define fts3HashInsert   sqlite3Fts3HashInsert
129343 #define fts3HashFind     sqlite3Fts3HashFind
129344 #define fts3HashClear    sqlite3Fts3HashClear
129345 #define fts3HashFindElem sqlite3Fts3HashFindElem
129346 
129347 /*
129348 ** Macros for looping over all elements of a hash table.  The idiom is
129349 ** like this:
129350 **
129351 **   Fts3Hash h;
129352 **   Fts3HashElem *p;
129353 **   ...
129354 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
129355 **     SomeStructure *pData = fts3HashData(p);
129356 **     // do something with pData
129357 **   }
129358 */
129359 #define fts3HashFirst(H)  ((H)->first)
129360 #define fts3HashNext(E)   ((E)->next)
129361 #define fts3HashData(E)   ((E)->data)
129362 #define fts3HashKey(E)    ((E)->pKey)
129363 #define fts3HashKeysize(E) ((E)->nKey)
129364 
129365 /*
129366 ** Number of entries in a hash table
129367 */
129368 #define fts3HashCount(H)  ((H)->count)
129369 
129370 #endif /* _FTS3_HASH_H_ */
129371 
129372 /************** End of fts3_hash.h *******************************************/
129373 /************** Continuing where we left off in fts3Int.h ********************/
129374 
129375 /*
129376 ** This constant determines the maximum depth of an FTS expression tree
129377 ** that the library will create and use. FTS uses recursion to perform
129378 ** various operations on the query tree, so the disadvantage of a large
129379 ** limit is that it may allow very large queries to use large amounts
129380 ** of stack space (perhaps causing a stack overflow).
129381 */
129382 #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
129383 # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
129384 #endif
129385 
129386 
129387 /*
129388 ** This constant controls how often segments are merged. Once there are
129389 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
129390 ** segment of level N+1.
129391 */
129392 #define FTS3_MERGE_COUNT 16
129393 
129394 /*
129395 ** This is the maximum amount of data (in bytes) to store in the
129396 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
129397 ** populated as documents are inserted/updated/deleted in a transaction
129398 ** and used to create a new segment when the transaction is committed.
129399 ** However if this limit is reached midway through a transaction, a new
129400 ** segment is created and the hash table cleared immediately.
129401 */
129402 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
129403 
129404 /*
129405 ** Macro to return the number of elements in an array. SQLite has a
129406 ** similar macro called ArraySize(). Use a different name to avoid
129407 ** a collision when building an amalgamation with built-in FTS3.
129408 */
129409 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
129410 
129411 
129412 #ifndef MIN
129413 # define MIN(x,y) ((x)<(y)?(x):(y))
129414 #endif
129415 #ifndef MAX
129416 # define MAX(x,y) ((x)>(y)?(x):(y))
129417 #endif
129418 
129419 /*
129420 ** Maximum length of a varint encoded integer. The varint format is different
129421 ** from that used by SQLite, so the maximum length is 10, not 9.
129422 */
129423 #define FTS3_VARINT_MAX 10
129424 
129425 /*
129426 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
129427 ** in the document set and zero or more prefix indexes. All indexes are stored
129428 ** as one or more b+-trees in the %_segments and %_segdir tables.
129429 **
129430 ** It is possible to determine which index a b+-tree belongs to based on the
129431 ** value stored in the "%_segdir.level" column. Given this value L, the index
129432 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
129433 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
129434 ** between 1024 and 2047 to index 1, and so on.
129435 **
129436 ** It is considered impossible for an index to use more than 1024 levels. In
129437 ** theory though this may happen, but only after at least
129438 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
129439 */
129440 #define FTS3_SEGDIR_MAXLEVEL      1024
129441 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
129442 
129443 /*
129444 ** The testcase() macro is only used by the amalgamation.  If undefined,
129445 ** make it a no-op.
129446 */
129447 #ifndef testcase
129448 # define testcase(X)
129449 #endif
129450 
129451 /*
129452 ** Terminator values for position-lists and column-lists.
129453 */
129454 #define POS_COLUMN  (1)     /* Column-list terminator */
129455 #define POS_END     (0)     /* Position-list terminator */
129456 
129457 /*
129458 ** This section provides definitions to allow the
129459 ** FTS3 extension to be compiled outside of the
129460 ** amalgamation.
129461 */
129462 #ifndef SQLITE_AMALGAMATION
129463 /*
129464 ** Macros indicating that conditional expressions are always true or
129465 ** false.
129466 */
129467 #ifdef SQLITE_COVERAGE_TEST
129468 # define ALWAYS(x) (1)
129469 # define NEVER(X)  (0)
129470 #else
129471 # define ALWAYS(x) (x)
129472 # define NEVER(x)  (x)
129473 #endif
129474 
129475 /*
129476 ** Internal types used by SQLite.
129477 */
129478 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
129479 typedef short int i16;            /* 2-byte (or larger) signed integer */
129480 typedef unsigned int u32;         /* 4-byte unsigned integer */
129481 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
129482 typedef sqlite3_int64 i64;        /* 8-byte signed integer */
129483 
129484 /*
129485 ** Macro used to suppress compiler warnings for unused parameters.
129486 */
129487 #define UNUSED_PARAMETER(x) (void)(x)
129488 
129489 /*
129490 ** Activate assert() only if SQLITE_TEST is enabled.
129491 */
129492 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
129493 # define NDEBUG 1
129494 #endif
129495 
129496 /*
129497 ** The TESTONLY macro is used to enclose variable declarations or
129498 ** other bits of code that are needed to support the arguments
129499 ** within testcase() and assert() macros.
129500 */
129501 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
129502 # define TESTONLY(X)  X
129503 #else
129504 # define TESTONLY(X)
129505 #endif
129506 
129507 #endif /* SQLITE_AMALGAMATION */
129508 
129509 #ifdef SQLITE_DEBUG
129510 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
129511 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
129512 #else
129513 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
129514 #endif
129515 
129516 typedef struct Fts3Table Fts3Table;
129517 typedef struct Fts3Cursor Fts3Cursor;
129518 typedef struct Fts3Expr Fts3Expr;
129519 typedef struct Fts3Phrase Fts3Phrase;
129520 typedef struct Fts3PhraseToken Fts3PhraseToken;
129521 
129522 typedef struct Fts3Doclist Fts3Doclist;
129523 typedef struct Fts3SegFilter Fts3SegFilter;
129524 typedef struct Fts3DeferredToken Fts3DeferredToken;
129525 typedef struct Fts3SegReader Fts3SegReader;
129526 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
129527 
129528 /*
129529 ** A connection to a fulltext index is an instance of the following
129530 ** structure. The xCreate and xConnect methods create an instance
129531 ** of this structure and xDestroy and xDisconnect free that instance.
129532 ** All other methods receive a pointer to the structure as one of their
129533 ** arguments.
129534 */
129535 struct Fts3Table {
129536   sqlite3_vtab base;              /* Base class used by SQLite core */
129537   sqlite3 *db;                    /* The database connection */
129538   const char *zDb;                /* logical database name */
129539   const char *zName;              /* virtual table name */
129540   int nColumn;                    /* number of named columns in virtual table */
129541   char **azColumn;                /* column names.  malloced */
129542   u8 *abNotindexed;               /* True for 'notindexed' columns */
129543   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
129544   char *zContentTbl;              /* content=xxx option, or NULL */
129545   char *zLanguageid;              /* languageid=xxx option, or NULL */
129546   int nAutoincrmerge;             /* Value configured by 'automerge' */
129547   u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
129548 
129549   /* Precompiled statements used by the implementation. Each of these
129550   ** statements is run and reset within a single virtual table API call.
129551   */
129552   sqlite3_stmt *aStmt[40];
129553 
129554   char *zReadExprlist;
129555   char *zWriteExprlist;
129556 
129557   int nNodeSize;                  /* Soft limit for node size */
129558   u8 bFts4;                       /* True for FTS4, false for FTS3 */
129559   u8 bHasStat;                    /* True if %_stat table exists (2==unknown) */
129560   u8 bHasDocsize;                 /* True if %_docsize table exists */
129561   u8 bDescIdx;                    /* True if doclists are in reverse order */
129562   u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
129563   int nPgsz;                      /* Page size for host database */
129564   char *zSegmentsTbl;             /* Name of %_segments table */
129565   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
129566 
129567   /*
129568   ** The following array of hash tables is used to buffer pending index
129569   ** updates during transactions. All pending updates buffered at any one
129570   ** time must share a common language-id (see the FTS4 langid= feature).
129571   ** The current language id is stored in variable iPrevLangid.
129572   **
129573   ** A single FTS4 table may have multiple full-text indexes. For each index
129574   ** there is an entry in the aIndex[] array. Index 0 is an index of all the
129575   ** terms that appear in the document set. Each subsequent index in aIndex[]
129576   ** is an index of prefixes of a specific length.
129577   **
129578   ** Variable nPendingData contains an estimate the memory consumed by the
129579   ** pending data structures, including hash table overhead, but not including
129580   ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
129581   ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
129582   ** recently inserted record.
129583   */
129584   int nIndex;                     /* Size of aIndex[] */
129585   struct Fts3Index {
129586     int nPrefix;                  /* Prefix length (0 for main terms index) */
129587     Fts3Hash hPending;            /* Pending terms table for this index */
129588   } *aIndex;
129589   int nMaxPendingData;            /* Max pending data before flush to disk */
129590   int nPendingData;               /* Current bytes of pending data */
129591   sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
129592   int iPrevLangid;                /* Langid of recently inserted document */
129593 
129594 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
129595   /* State variables used for validating that the transaction control
129596   ** methods of the virtual table are called at appropriate times.  These
129597   ** values do not contribute to FTS functionality; they are used for
129598   ** verifying the operation of the SQLite core.
129599   */
129600   int inTransaction;     /* True after xBegin but before xCommit/xRollback */
129601   int mxSavepoint;       /* Largest valid xSavepoint integer */
129602 #endif
129603 
129604 #ifdef SQLITE_TEST
129605   /* True to disable the incremental doclist optimization. This is controled
129606   ** by special insert command 'test-no-incr-doclist'.  */
129607   int bNoIncrDoclist;
129608 #endif
129609 };
129610 
129611 /*
129612 ** When the core wants to read from the virtual table, it creates a
129613 ** virtual table cursor (an instance of the following structure) using
129614 ** the xOpen method. Cursors are destroyed using the xClose method.
129615 */
129616 struct Fts3Cursor {
129617   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
129618   i16 eSearch;                    /* Search strategy (see below) */
129619   u8 isEof;                       /* True if at End Of Results */
129620   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
129621   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
129622   Fts3Expr *pExpr;                /* Parsed MATCH query string */
129623   int iLangid;                    /* Language being queried for */
129624   int nPhrase;                    /* Number of matchable phrases in query */
129625   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
129626   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
129627   char *pNextId;                  /* Pointer into the body of aDoclist */
129628   char *aDoclist;                 /* List of docids for full-text queries */
129629   int nDoclist;                   /* Size of buffer at aDoclist */
129630   u8 bDesc;                       /* True to sort in descending order */
129631   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
129632   int nRowAvg;                    /* Average size of database rows, in pages */
129633   sqlite3_int64 nDoc;             /* Documents in table */
129634   i64 iMinDocid;                  /* Minimum docid to return */
129635   i64 iMaxDocid;                  /* Maximum docid to return */
129636   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
129637   u32 *aMatchinfo;                /* Information about most recent match */
129638   int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
129639   char *zMatchinfo;               /* Matchinfo specification */
129640 };
129641 
129642 #define FTS3_EVAL_FILTER    0
129643 #define FTS3_EVAL_NEXT      1
129644 #define FTS3_EVAL_MATCHINFO 2
129645 
129646 /*
129647 ** The Fts3Cursor.eSearch member is always set to one of the following.
129648 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
129649 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
129650 ** of the column to be searched.  For example, in
129651 **
129652 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
129653 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
129654 **
129655 ** Because the LHS of the MATCH operator is 2nd column "b",
129656 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
129657 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
129658 ** indicating that all columns should be searched,
129659 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
129660 */
129661 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
129662 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
129663 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
129664 
129665 /*
129666 ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
129667 ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
129668 ** above. The upper 16-bits contain a combination of the following
129669 ** bits, used to describe extra constraints on full-text searches.
129670 */
129671 #define FTS3_HAVE_LANGID    0x00010000      /* languageid=? */
129672 #define FTS3_HAVE_DOCID_GE  0x00020000      /* docid>=? */
129673 #define FTS3_HAVE_DOCID_LE  0x00040000      /* docid<=? */
129674 
129675 struct Fts3Doclist {
129676   char *aAll;                    /* Array containing doclist (or NULL) */
129677   int nAll;                      /* Size of a[] in bytes */
129678   char *pNextDocid;              /* Pointer to next docid */
129679 
129680   sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
129681   int bFreeList;                 /* True if pList should be sqlite3_free()d */
129682   char *pList;                   /* Pointer to position list following iDocid */
129683   int nList;                     /* Length of position list */
129684 };
129685 
129686 /*
129687 ** A "phrase" is a sequence of one or more tokens that must match in
129688 ** sequence.  A single token is the base case and the most common case.
129689 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
129690 ** nToken will be the number of tokens in the string.
129691 */
129692 struct Fts3PhraseToken {
129693   char *z;                        /* Text of the token */
129694   int n;                          /* Number of bytes in buffer z */
129695   int isPrefix;                   /* True if token ends with a "*" character */
129696   int bFirst;                     /* True if token must appear at position 0 */
129697 
129698   /* Variables above this point are populated when the expression is
129699   ** parsed (by code in fts3_expr.c). Below this point the variables are
129700   ** used when evaluating the expression. */
129701   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
129702   Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
129703 };
129704 
129705 struct Fts3Phrase {
129706   /* Cache of doclist for this phrase. */
129707   Fts3Doclist doclist;
129708   int bIncr;                 /* True if doclist is loaded incrementally */
129709   int iDoclistToken;
129710 
129711   /* Variables below this point are populated by fts3_expr.c when parsing
129712   ** a MATCH expression. Everything above is part of the evaluation phase.
129713   */
129714   int nToken;                /* Number of tokens in the phrase */
129715   int iColumn;               /* Index of column this phrase must match */
129716   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
129717 };
129718 
129719 /*
129720 ** A tree of these objects forms the RHS of a MATCH operator.
129721 **
129722 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
129723 ** points to a malloced buffer, size nDoclist bytes, containing the results
129724 ** of this phrase query in FTS3 doclist format. As usual, the initial
129725 ** "Length" field found in doclists stored on disk is omitted from this
129726 ** buffer.
129727 **
129728 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
129729 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
129730 ** where nCol is the number of columns in the queried FTS table. The array
129731 ** is populated as follows:
129732 **
129733 **   aMI[iCol*3 + 0] = Undefined
129734 **   aMI[iCol*3 + 1] = Number of occurrences
129735 **   aMI[iCol*3 + 2] = Number of rows containing at least one instance
129736 **
129737 ** The aMI array is allocated using sqlite3_malloc(). It should be freed
129738 ** when the expression node is.
129739 */
129740 struct Fts3Expr {
129741   int eType;                 /* One of the FTSQUERY_XXX values defined below */
129742   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
129743   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
129744   Fts3Expr *pLeft;           /* Left operand */
129745   Fts3Expr *pRight;          /* Right operand */
129746   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
129747 
129748   /* The following are used by the fts3_eval.c module. */
129749   sqlite3_int64 iDocid;      /* Current docid */
129750   u8 bEof;                   /* True this expression is at EOF already */
129751   u8 bStart;                 /* True if iDocid is valid */
129752   u8 bDeferred;              /* True if this expression is entirely deferred */
129753 
129754   u32 *aMI;
129755 };
129756 
129757 /*
129758 ** Candidate values for Fts3Query.eType. Note that the order of the first
129759 ** four values is in order of precedence when parsing expressions. For
129760 ** example, the following:
129761 **
129762 **   "a OR b AND c NOT d NEAR e"
129763 **
129764 ** is equivalent to:
129765 **
129766 **   "a OR (b AND (c NOT (d NEAR e)))"
129767 */
129768 #define FTSQUERY_NEAR   1
129769 #define FTSQUERY_NOT    2
129770 #define FTSQUERY_AND    3
129771 #define FTSQUERY_OR     4
129772 #define FTSQUERY_PHRASE 5
129773 
129774 
129775 /* fts3_write.c */
129776 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
129777 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
129778 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
129779 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
129780 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
129781   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
129782 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
129783   Fts3Table*,int,const char*,int,int,Fts3SegReader**);
129784 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
129785 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
129786 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
129787 
129788 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
129789 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
129790 
129791 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
129792 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
129793 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
129794 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
129795 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
129796 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
129797 #else
129798 # define sqlite3Fts3FreeDeferredTokens(x)
129799 # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
129800 # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
129801 # define sqlite3Fts3FreeDeferredDoclists(x)
129802 # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
129803 #endif
129804 
129805 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
129806 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
129807 
129808 /* Special values interpreted by sqlite3SegReaderCursor() */
129809 #define FTS3_SEGCURSOR_PENDING        -1
129810 #define FTS3_SEGCURSOR_ALL            -2
129811 
129812 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
129813 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
129814 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
129815 
129816 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
129817     int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
129818 
129819 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
129820 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
129821 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
129822 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
129823 #define FTS3_SEGMENT_PREFIX        0x00000008
129824 #define FTS3_SEGMENT_SCAN          0x00000010
129825 #define FTS3_SEGMENT_FIRST         0x00000020
129826 
129827 /* Type passed as 4th argument to SegmentReaderIterate() */
129828 struct Fts3SegFilter {
129829   const char *zTerm;
129830   int nTerm;
129831   int iCol;
129832   int flags;
129833 };
129834 
129835 struct Fts3MultiSegReader {
129836   /* Used internally by sqlite3Fts3SegReaderXXX() calls */
129837   Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
129838   int nSegment;                   /* Size of apSegment array */
129839   int nAdvance;                   /* How many seg-readers to advance */
129840   Fts3SegFilter *pFilter;         /* Pointer to filter object */
129841   char *aBuffer;                  /* Buffer to merge doclists in */
129842   int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
129843 
129844   int iColFilter;                 /* If >=0, filter for this column */
129845   int bRestart;
129846 
129847   /* Used by fts3.c only. */
129848   int nCost;                      /* Cost of running iterator */
129849   int bLookup;                    /* True if a lookup of a single entry. */
129850 
129851   /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
129852   char *zTerm;                    /* Pointer to term buffer */
129853   int nTerm;                      /* Size of zTerm in bytes */
129854   char *aDoclist;                 /* Pointer to doclist buffer */
129855   int nDoclist;                   /* Size of aDoclist[] in bytes */
129856 };
129857 
129858 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
129859 
129860 #define fts3GetVarint32(p, piVal) (                                           \
129861   (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
129862 )
129863 
129864 /* fts3.c */
129865 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
129866 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
129867 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
129868 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
129869 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
129870 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
129871 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
129872 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
129873 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
129874 
129875 /* fts3_tokenizer.c */
129876 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
129877 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
129878 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
129879     sqlite3_tokenizer **, char **
129880 );
129881 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
129882 
129883 /* fts3_snippet.c */
129884 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
129885 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
129886   const char *, const char *, int, int
129887 );
129888 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
129889 
129890 /* fts3_expr.c */
129891 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
129892   char **, int, int, int, const char *, int, Fts3Expr **, char **
129893 );
129894 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
129895 #ifdef SQLITE_TEST
129896 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
129897 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
129898 #endif
129899 
129900 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
129901   sqlite3_tokenizer_cursor **
129902 );
129903 
129904 /* fts3_aux.c */
129905 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
129906 
129907 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
129908 
129909 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
129910     Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
129911 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
129912     Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
129913 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
129914 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
129915 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
129916 
129917 /* fts3_tokenize_vtab.c */
129918 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
129919 
129920 /* fts3_unicode2.c (functions generated by parsing unicode text files) */
129921 #ifndef SQLITE_DISABLE_FTS3_UNICODE
129922 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
129923 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
129924 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
129925 #endif
129926 
129927 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
129928 #endif /* _FTSINT_H */
129929 
129930 /************** End of fts3Int.h *********************************************/
129931 /************** Continuing where we left off in fts3.c ***********************/
129932 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
129933 
129934 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
129935 # define SQLITE_CORE 1
129936 #endif
129937 
129938 /* #include <assert.h> */
129939 /* #include <stdlib.h> */
129940 /* #include <stddef.h> */
129941 /* #include <stdio.h> */
129942 /* #include <string.h> */
129943 /* #include <stdarg.h> */
129944 
129945 #ifndef SQLITE_CORE
129946   SQLITE_EXTENSION_INIT1
129947 #endif
129948 
129949 static int fts3EvalNext(Fts3Cursor *pCsr);
129950 static int fts3EvalStart(Fts3Cursor *pCsr);
129951 static int fts3TermSegReaderCursor(
129952     Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
129953 
129954 /*
129955 ** Write a 64-bit variable-length integer to memory starting at p[0].
129956 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
129957 ** The number of bytes written is returned.
129958 */
129959 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
129960   unsigned char *q = (unsigned char *) p;
129961   sqlite_uint64 vu = v;
129962   do{
129963     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
129964     vu >>= 7;
129965   }while( vu!=0 );
129966   q[-1] &= 0x7f;  /* turn off high bit in final byte */
129967   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
129968   return (int) (q - (unsigned char *)p);
129969 }
129970 
129971 #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
129972   v = (v & mask1) | ( (*ptr++) << shift );                    \
129973   if( (v & mask2)==0 ){ var = v; return ret; }
129974 #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
129975   v = (*ptr++);                                               \
129976   if( (v & mask2)==0 ){ var = v; return ret; }
129977 
129978 /*
129979 ** Read a 64-bit variable-length integer from memory starting at p[0].
129980 ** Return the number of bytes read, or 0 on error.
129981 ** The value is stored in *v.
129982 */
129983 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
129984   const char *pStart = p;
129985   u32 a;
129986   u64 b;
129987   int shift;
129988 
129989   GETVARINT_INIT(a, p, 0,  0x00,     0x80, *v, 1);
129990   GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *v, 2);
129991   GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *v, 3);
129992   GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
129993   b = (a & 0x0FFFFFFF );
129994 
129995   for(shift=28; shift<=63; shift+=7){
129996     u64 c = *p++;
129997     b += (c&0x7F) << shift;
129998     if( (c & 0x80)==0 ) break;
129999   }
130000   *v = b;
130001   return (int)(p - pStart);
130002 }
130003 
130004 /*
130005 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
130006 ** 32-bit integer before it is returned.
130007 */
130008 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
130009   u32 a;
130010 
130011 #ifndef fts3GetVarint32
130012   GETVARINT_INIT(a, p, 0,  0x00,     0x80, *pi, 1);
130013 #else
130014   a = (*p++);
130015   assert( a & 0x80 );
130016 #endif
130017 
130018   GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *pi, 2);
130019   GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *pi, 3);
130020   GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
130021   a = (a & 0x0FFFFFFF );
130022   *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
130023   return 5;
130024 }
130025 
130026 /*
130027 ** Return the number of bytes required to encode v as a varint
130028 */
130029 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
130030   int i = 0;
130031   do{
130032     i++;
130033     v >>= 7;
130034   }while( v!=0 );
130035   return i;
130036 }
130037 
130038 /*
130039 ** Convert an SQL-style quoted string into a normal string by removing
130040 ** the quote characters.  The conversion is done in-place.  If the
130041 ** input does not begin with a quote character, then this routine
130042 ** is a no-op.
130043 **
130044 ** Examples:
130045 **
130046 **     "abc"   becomes   abc
130047 **     'xyz'   becomes   xyz
130048 **     [pqr]   becomes   pqr
130049 **     `mno`   becomes   mno
130050 **
130051 */
130052 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
130053   char quote;                     /* Quote character (if any ) */
130054 
130055   quote = z[0];
130056   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
130057     int iIn = 1;                  /* Index of next byte to read from input */
130058     int iOut = 0;                 /* Index of next byte to write to output */
130059 
130060     /* If the first byte was a '[', then the close-quote character is a ']' */
130061     if( quote=='[' ) quote = ']';
130062 
130063     while( ALWAYS(z[iIn]) ){
130064       if( z[iIn]==quote ){
130065         if( z[iIn+1]!=quote ) break;
130066         z[iOut++] = quote;
130067         iIn += 2;
130068       }else{
130069         z[iOut++] = z[iIn++];
130070       }
130071     }
130072     z[iOut] = '\0';
130073   }
130074 }
130075 
130076 /*
130077 ** Read a single varint from the doclist at *pp and advance *pp to point
130078 ** to the first byte past the end of the varint.  Add the value of the varint
130079 ** to *pVal.
130080 */
130081 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
130082   sqlite3_int64 iVal;
130083   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
130084   *pVal += iVal;
130085 }
130086 
130087 /*
130088 ** When this function is called, *pp points to the first byte following a
130089 ** varint that is part of a doclist (or position-list, or any other list
130090 ** of varints). This function moves *pp to point to the start of that varint,
130091 ** and sets *pVal by the varint value.
130092 **
130093 ** Argument pStart points to the first byte of the doclist that the
130094 ** varint is part of.
130095 */
130096 static void fts3GetReverseVarint(
130097   char **pp,
130098   char *pStart,
130099   sqlite3_int64 *pVal
130100 ){
130101   sqlite3_int64 iVal;
130102   char *p;
130103 
130104   /* Pointer p now points at the first byte past the varint we are
130105   ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
130106   ** clear on character p[-1]. */
130107   for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
130108   p++;
130109   *pp = p;
130110 
130111   sqlite3Fts3GetVarint(p, &iVal);
130112   *pVal = iVal;
130113 }
130114 
130115 /*
130116 ** The xDisconnect() virtual table method.
130117 */
130118 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
130119   Fts3Table *p = (Fts3Table *)pVtab;
130120   int i;
130121 
130122   assert( p->nPendingData==0 );
130123   assert( p->pSegments==0 );
130124 
130125   /* Free any prepared statements held */
130126   for(i=0; i<SizeofArray(p->aStmt); i++){
130127     sqlite3_finalize(p->aStmt[i]);
130128   }
130129   sqlite3_free(p->zSegmentsTbl);
130130   sqlite3_free(p->zReadExprlist);
130131   sqlite3_free(p->zWriteExprlist);
130132   sqlite3_free(p->zContentTbl);
130133   sqlite3_free(p->zLanguageid);
130134 
130135   /* Invoke the tokenizer destructor to free the tokenizer. */
130136   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
130137 
130138   sqlite3_free(p);
130139   return SQLITE_OK;
130140 }
130141 
130142 /*
130143 ** Construct one or more SQL statements from the format string given
130144 ** and then evaluate those statements. The success code is written
130145 ** into *pRc.
130146 **
130147 ** If *pRc is initially non-zero then this routine is a no-op.
130148 */
130149 static void fts3DbExec(
130150   int *pRc,              /* Success code */
130151   sqlite3 *db,           /* Database in which to run SQL */
130152   const char *zFormat,   /* Format string for SQL */
130153   ...                    /* Arguments to the format string */
130154 ){
130155   va_list ap;
130156   char *zSql;
130157   if( *pRc ) return;
130158   va_start(ap, zFormat);
130159   zSql = sqlite3_vmprintf(zFormat, ap);
130160   va_end(ap);
130161   if( zSql==0 ){
130162     *pRc = SQLITE_NOMEM;
130163   }else{
130164     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
130165     sqlite3_free(zSql);
130166   }
130167 }
130168 
130169 /*
130170 ** The xDestroy() virtual table method.
130171 */
130172 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
130173   Fts3Table *p = (Fts3Table *)pVtab;
130174   int rc = SQLITE_OK;              /* Return code */
130175   const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
130176   sqlite3 *db = p->db;             /* Database handle */
130177 
130178   /* Drop the shadow tables */
130179   if( p->zContentTbl==0 ){
130180     fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
130181   }
130182   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
130183   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
130184   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
130185   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
130186 
130187   /* If everything has worked, invoke fts3DisconnectMethod() to free the
130188   ** memory associated with the Fts3Table structure and return SQLITE_OK.
130189   ** Otherwise, return an SQLite error code.
130190   */
130191   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
130192 }
130193 
130194 
130195 /*
130196 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
130197 ** passed as the first argument. This is done as part of the xConnect()
130198 ** and xCreate() methods.
130199 **
130200 ** If *pRc is non-zero when this function is called, it is a no-op.
130201 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
130202 ** before returning.
130203 */
130204 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
130205   if( *pRc==SQLITE_OK ){
130206     int i;                        /* Iterator variable */
130207     int rc;                       /* Return code */
130208     char *zSql;                   /* SQL statement passed to declare_vtab() */
130209     char *zCols;                  /* List of user defined columns */
130210     const char *zLanguageid;
130211 
130212     zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
130213     sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
130214 
130215     /* Create a list of user columns for the virtual table */
130216     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
130217     for(i=1; zCols && i<p->nColumn; i++){
130218       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
130219     }
130220 
130221     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
130222     zSql = sqlite3_mprintf(
130223         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
130224         zCols, p->zName, zLanguageid
130225     );
130226     if( !zCols || !zSql ){
130227       rc = SQLITE_NOMEM;
130228     }else{
130229       rc = sqlite3_declare_vtab(p->db, zSql);
130230     }
130231 
130232     sqlite3_free(zSql);
130233     sqlite3_free(zCols);
130234     *pRc = rc;
130235   }
130236 }
130237 
130238 /*
130239 ** Create the %_stat table if it does not already exist.
130240 */
130241 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
130242   fts3DbExec(pRc, p->db,
130243       "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
130244           "(id INTEGER PRIMARY KEY, value BLOB);",
130245       p->zDb, p->zName
130246   );
130247   if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
130248 }
130249 
130250 /*
130251 ** Create the backing store tables (%_content, %_segments and %_segdir)
130252 ** required by the FTS3 table passed as the only argument. This is done
130253 ** as part of the vtab xCreate() method.
130254 **
130255 ** If the p->bHasDocsize boolean is true (indicating that this is an
130256 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
130257 ** %_stat tables required by FTS4.
130258 */
130259 static int fts3CreateTables(Fts3Table *p){
130260   int rc = SQLITE_OK;             /* Return code */
130261   int i;                          /* Iterator variable */
130262   sqlite3 *db = p->db;            /* The database connection */
130263 
130264   if( p->zContentTbl==0 ){
130265     const char *zLanguageid = p->zLanguageid;
130266     char *zContentCols;           /* Columns of %_content table */
130267 
130268     /* Create a list of user columns for the content table */
130269     zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
130270     for(i=0; zContentCols && i<p->nColumn; i++){
130271       char *z = p->azColumn[i];
130272       zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
130273     }
130274     if( zLanguageid && zContentCols ){
130275       zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
130276     }
130277     if( zContentCols==0 ) rc = SQLITE_NOMEM;
130278 
130279     /* Create the content table */
130280     fts3DbExec(&rc, db,
130281        "CREATE TABLE %Q.'%q_content'(%s)",
130282        p->zDb, p->zName, zContentCols
130283     );
130284     sqlite3_free(zContentCols);
130285   }
130286 
130287   /* Create other tables */
130288   fts3DbExec(&rc, db,
130289       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
130290       p->zDb, p->zName
130291   );
130292   fts3DbExec(&rc, db,
130293       "CREATE TABLE %Q.'%q_segdir'("
130294         "level INTEGER,"
130295         "idx INTEGER,"
130296         "start_block INTEGER,"
130297         "leaves_end_block INTEGER,"
130298         "end_block INTEGER,"
130299         "root BLOB,"
130300         "PRIMARY KEY(level, idx)"
130301       ");",
130302       p->zDb, p->zName
130303   );
130304   if( p->bHasDocsize ){
130305     fts3DbExec(&rc, db,
130306         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
130307         p->zDb, p->zName
130308     );
130309   }
130310   assert( p->bHasStat==p->bFts4 );
130311   if( p->bHasStat ){
130312     sqlite3Fts3CreateStatTable(&rc, p);
130313   }
130314   return rc;
130315 }
130316 
130317 /*
130318 ** Store the current database page-size in bytes in p->nPgsz.
130319 **
130320 ** If *pRc is non-zero when this function is called, it is a no-op.
130321 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
130322 ** before returning.
130323 */
130324 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
130325   if( *pRc==SQLITE_OK ){
130326     int rc;                       /* Return code */
130327     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
130328     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
130329 
130330     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
130331     if( !zSql ){
130332       rc = SQLITE_NOMEM;
130333     }else{
130334       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
130335       if( rc==SQLITE_OK ){
130336         sqlite3_step(pStmt);
130337         p->nPgsz = sqlite3_column_int(pStmt, 0);
130338         rc = sqlite3_finalize(pStmt);
130339       }else if( rc==SQLITE_AUTH ){
130340         p->nPgsz = 1024;
130341         rc = SQLITE_OK;
130342       }
130343     }
130344     assert( p->nPgsz>0 || rc!=SQLITE_OK );
130345     sqlite3_free(zSql);
130346     *pRc = rc;
130347   }
130348 }
130349 
130350 /*
130351 ** "Special" FTS4 arguments are column specifications of the following form:
130352 **
130353 **   <key> = <value>
130354 **
130355 ** There may not be whitespace surrounding the "=" character. The <value>
130356 ** term may be quoted, but the <key> may not.
130357 */
130358 static int fts3IsSpecialColumn(
130359   const char *z,
130360   int *pnKey,
130361   char **pzValue
130362 ){
130363   char *zValue;
130364   const char *zCsr = z;
130365 
130366   while( *zCsr!='=' ){
130367     if( *zCsr=='\0' ) return 0;
130368     zCsr++;
130369   }
130370 
130371   *pnKey = (int)(zCsr-z);
130372   zValue = sqlite3_mprintf("%s", &zCsr[1]);
130373   if( zValue ){
130374     sqlite3Fts3Dequote(zValue);
130375   }
130376   *pzValue = zValue;
130377   return 1;
130378 }
130379 
130380 /*
130381 ** Append the output of a printf() style formatting to an existing string.
130382 */
130383 static void fts3Appendf(
130384   int *pRc,                       /* IN/OUT: Error code */
130385   char **pz,                      /* IN/OUT: Pointer to string buffer */
130386   const char *zFormat,            /* Printf format string to append */
130387   ...                             /* Arguments for printf format string */
130388 ){
130389   if( *pRc==SQLITE_OK ){
130390     va_list ap;
130391     char *z;
130392     va_start(ap, zFormat);
130393     z = sqlite3_vmprintf(zFormat, ap);
130394     va_end(ap);
130395     if( z && *pz ){
130396       char *z2 = sqlite3_mprintf("%s%s", *pz, z);
130397       sqlite3_free(z);
130398       z = z2;
130399     }
130400     if( z==0 ) *pRc = SQLITE_NOMEM;
130401     sqlite3_free(*pz);
130402     *pz = z;
130403   }
130404 }
130405 
130406 /*
130407 ** Return a copy of input string zInput enclosed in double-quotes (") and
130408 ** with all double quote characters escaped. For example:
130409 **
130410 **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
130411 **
130412 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
130413 ** is the callers responsibility to call sqlite3_free() to release this
130414 ** memory.
130415 */
130416 static char *fts3QuoteId(char const *zInput){
130417   int nRet;
130418   char *zRet;
130419   nRet = 2 + (int)strlen(zInput)*2 + 1;
130420   zRet = sqlite3_malloc(nRet);
130421   if( zRet ){
130422     int i;
130423     char *z = zRet;
130424     *(z++) = '"';
130425     for(i=0; zInput[i]; i++){
130426       if( zInput[i]=='"' ) *(z++) = '"';
130427       *(z++) = zInput[i];
130428     }
130429     *(z++) = '"';
130430     *(z++) = '\0';
130431   }
130432   return zRet;
130433 }
130434 
130435 /*
130436 ** Return a list of comma separated SQL expressions and a FROM clause that
130437 ** could be used in a SELECT statement such as the following:
130438 **
130439 **     SELECT <list of expressions> FROM %_content AS x ...
130440 **
130441 ** to return the docid, followed by each column of text data in order
130442 ** from left to write. If parameter zFunc is not NULL, then instead of
130443 ** being returned directly each column of text data is passed to an SQL
130444 ** function named zFunc first. For example, if zFunc is "unzip" and the
130445 ** table has the three user-defined columns "a", "b", and "c", the following
130446 ** string is returned:
130447 **
130448 **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
130449 **
130450 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
130451 ** is the responsibility of the caller to eventually free it.
130452 **
130453 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
130454 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
130455 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
130456 ** no error occurs, *pRc is left unmodified.
130457 */
130458 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
130459   char *zRet = 0;
130460   char *zFree = 0;
130461   char *zFunction;
130462   int i;
130463 
130464   if( p->zContentTbl==0 ){
130465     if( !zFunc ){
130466       zFunction = "";
130467     }else{
130468       zFree = zFunction = fts3QuoteId(zFunc);
130469     }
130470     fts3Appendf(pRc, &zRet, "docid");
130471     for(i=0; i<p->nColumn; i++){
130472       fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
130473     }
130474     if( p->zLanguageid ){
130475       fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
130476     }
130477     sqlite3_free(zFree);
130478   }else{
130479     fts3Appendf(pRc, &zRet, "rowid");
130480     for(i=0; i<p->nColumn; i++){
130481       fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
130482     }
130483     if( p->zLanguageid ){
130484       fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
130485     }
130486   }
130487   fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
130488       p->zDb,
130489       (p->zContentTbl ? p->zContentTbl : p->zName),
130490       (p->zContentTbl ? "" : "_content")
130491   );
130492   return zRet;
130493 }
130494 
130495 /*
130496 ** Return a list of N comma separated question marks, where N is the number
130497 ** of columns in the %_content table (one for the docid plus one for each
130498 ** user-defined text column).
130499 **
130500 ** If argument zFunc is not NULL, then all but the first question mark
130501 ** is preceded by zFunc and an open bracket, and followed by a closed
130502 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
130503 ** user-defined text columns, the following string is returned:
130504 **
130505 **     "?, zip(?), zip(?), zip(?)"
130506 **
130507 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
130508 ** is the responsibility of the caller to eventually free it.
130509 **
130510 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
130511 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
130512 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
130513 ** no error occurs, *pRc is left unmodified.
130514 */
130515 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
130516   char *zRet = 0;
130517   char *zFree = 0;
130518   char *zFunction;
130519   int i;
130520 
130521   if( !zFunc ){
130522     zFunction = "";
130523   }else{
130524     zFree = zFunction = fts3QuoteId(zFunc);
130525   }
130526   fts3Appendf(pRc, &zRet, "?");
130527   for(i=0; i<p->nColumn; i++){
130528     fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
130529   }
130530   if( p->zLanguageid ){
130531     fts3Appendf(pRc, &zRet, ", ?");
130532   }
130533   sqlite3_free(zFree);
130534   return zRet;
130535 }
130536 
130537 /*
130538 ** This function interprets the string at (*pp) as a non-negative integer
130539 ** value. It reads the integer and sets *pnOut to the value read, then
130540 ** sets *pp to point to the byte immediately following the last byte of
130541 ** the integer value.
130542 **
130543 ** Only decimal digits ('0'..'9') may be part of an integer value.
130544 **
130545 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
130546 ** the output value undefined. Otherwise SQLITE_OK is returned.
130547 **
130548 ** This function is used when parsing the "prefix=" FTS4 parameter.
130549 */
130550 static int fts3GobbleInt(const char **pp, int *pnOut){
130551   const char *p;                  /* Iterator pointer */
130552   int nInt = 0;                   /* Output value */
130553 
130554   for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
130555     nInt = nInt * 10 + (p[0] - '0');
130556   }
130557   if( p==*pp ) return SQLITE_ERROR;
130558   *pnOut = nInt;
130559   *pp = p;
130560   return SQLITE_OK;
130561 }
130562 
130563 /*
130564 ** This function is called to allocate an array of Fts3Index structures
130565 ** representing the indexes maintained by the current FTS table. FTS tables
130566 ** always maintain the main "terms" index, but may also maintain one or
130567 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
130568 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
130569 **
130570 ** Argument zParam is passed the value of the "prefix=" option if one was
130571 ** specified, or NULL otherwise.
130572 **
130573 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
130574 ** the allocated array. *pnIndex is set to the number of elements in the
130575 ** array. If an error does occur, an SQLite error code is returned.
130576 **
130577 ** Regardless of whether or not an error is returned, it is the responsibility
130578 ** of the caller to call sqlite3_free() on the output array to free it.
130579 */
130580 static int fts3PrefixParameter(
130581   const char *zParam,             /* ABC in prefix=ABC parameter to parse */
130582   int *pnIndex,                   /* OUT: size of *apIndex[] array */
130583   struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
130584 ){
130585   struct Fts3Index *aIndex;       /* Allocated array */
130586   int nIndex = 1;                 /* Number of entries in array */
130587 
130588   if( zParam && zParam[0] ){
130589     const char *p;
130590     nIndex++;
130591     for(p=zParam; *p; p++){
130592       if( *p==',' ) nIndex++;
130593     }
130594   }
130595 
130596   aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
130597   *apIndex = aIndex;
130598   *pnIndex = nIndex;
130599   if( !aIndex ){
130600     return SQLITE_NOMEM;
130601   }
130602 
130603   memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
130604   if( zParam ){
130605     const char *p = zParam;
130606     int i;
130607     for(i=1; i<nIndex; i++){
130608       int nPrefix;
130609       if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
130610       aIndex[i].nPrefix = nPrefix;
130611       p++;
130612     }
130613   }
130614 
130615   return SQLITE_OK;
130616 }
130617 
130618 /*
130619 ** This function is called when initializing an FTS4 table that uses the
130620 ** content=xxx option. It determines the number of and names of the columns
130621 ** of the new FTS4 table.
130622 **
130623 ** The third argument passed to this function is the value passed to the
130624 ** config=xxx option (i.e. "xxx"). This function queries the database for
130625 ** a table of that name. If found, the output variables are populated
130626 ** as follows:
130627 **
130628 **   *pnCol:   Set to the number of columns table xxx has,
130629 **
130630 **   *pnStr:   Set to the total amount of space required to store a copy
130631 **             of each columns name, including the nul-terminator.
130632 **
130633 **   *pazCol:  Set to point to an array of *pnCol strings. Each string is
130634 **             the name of the corresponding column in table xxx. The array
130635 **             and its contents are allocated using a single allocation. It
130636 **             is the responsibility of the caller to free this allocation
130637 **             by eventually passing the *pazCol value to sqlite3_free().
130638 **
130639 ** If the table cannot be found, an error code is returned and the output
130640 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
130641 ** returned (and the output variables are undefined).
130642 */
130643 static int fts3ContentColumns(
130644   sqlite3 *db,                    /* Database handle */
130645   const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
130646   const char *zTbl,               /* Name of content table */
130647   const char ***pazCol,           /* OUT: Malloc'd array of column names */
130648   int *pnCol,                     /* OUT: Size of array *pazCol */
130649   int *pnStr                      /* OUT: Bytes of string content */
130650 ){
130651   int rc = SQLITE_OK;             /* Return code */
130652   char *zSql;                     /* "SELECT *" statement on zTbl */
130653   sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
130654 
130655   zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
130656   if( !zSql ){
130657     rc = SQLITE_NOMEM;
130658   }else{
130659     rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
130660   }
130661   sqlite3_free(zSql);
130662 
130663   if( rc==SQLITE_OK ){
130664     const char **azCol;           /* Output array */
130665     int nStr = 0;                 /* Size of all column names (incl. 0x00) */
130666     int nCol;                     /* Number of table columns */
130667     int i;                        /* Used to iterate through columns */
130668 
130669     /* Loop through the returned columns. Set nStr to the number of bytes of
130670     ** space required to store a copy of each column name, including the
130671     ** nul-terminator byte.  */
130672     nCol = sqlite3_column_count(pStmt);
130673     for(i=0; i<nCol; i++){
130674       const char *zCol = sqlite3_column_name(pStmt, i);
130675       nStr += (int)strlen(zCol) + 1;
130676     }
130677 
130678     /* Allocate and populate the array to return. */
130679     azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
130680     if( azCol==0 ){
130681       rc = SQLITE_NOMEM;
130682     }else{
130683       char *p = (char *)&azCol[nCol];
130684       for(i=0; i<nCol; i++){
130685         const char *zCol = sqlite3_column_name(pStmt, i);
130686         int n = (int)strlen(zCol)+1;
130687         memcpy(p, zCol, n);
130688         azCol[i] = p;
130689         p += n;
130690       }
130691     }
130692     sqlite3_finalize(pStmt);
130693 
130694     /* Set the output variables. */
130695     *pnCol = nCol;
130696     *pnStr = nStr;
130697     *pazCol = azCol;
130698   }
130699 
130700   return rc;
130701 }
130702 
130703 /*
130704 ** This function is the implementation of both the xConnect and xCreate
130705 ** methods of the FTS3 virtual table.
130706 **
130707 ** The argv[] array contains the following:
130708 **
130709 **   argv[0]   -> module name  ("fts3" or "fts4")
130710 **   argv[1]   -> database name
130711 **   argv[2]   -> table name
130712 **   argv[...] -> "column name" and other module argument fields.
130713 */
130714 static int fts3InitVtab(
130715   int isCreate,                   /* True for xCreate, false for xConnect */
130716   sqlite3 *db,                    /* The SQLite database connection */
130717   void *pAux,                     /* Hash table containing tokenizers */
130718   int argc,                       /* Number of elements in argv array */
130719   const char * const *argv,       /* xCreate/xConnect argument array */
130720   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
130721   char **pzErr                    /* Write any error message here */
130722 ){
130723   Fts3Hash *pHash = (Fts3Hash *)pAux;
130724   Fts3Table *p = 0;               /* Pointer to allocated vtab */
130725   int rc = SQLITE_OK;             /* Return code */
130726   int i;                          /* Iterator variable */
130727   int nByte;                      /* Size of allocation used for *p */
130728   int iCol;                       /* Column index */
130729   int nString = 0;                /* Bytes required to hold all column names */
130730   int nCol = 0;                   /* Number of columns in the FTS table */
130731   char *zCsr;                     /* Space for holding column names */
130732   int nDb;                        /* Bytes required to hold database name */
130733   int nName;                      /* Bytes required to hold table name */
130734   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
130735   const char **aCol;              /* Array of column names */
130736   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
130737 
130738   int nIndex;                     /* Size of aIndex[] array */
130739   struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
130740 
130741   /* The results of parsing supported FTS4 key=value options: */
130742   int bNoDocsize = 0;             /* True to omit %_docsize table */
130743   int bDescIdx = 0;               /* True to store descending indexes */
130744   char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
130745   char *zCompress = 0;            /* compress=? parameter (or NULL) */
130746   char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
130747   char *zContent = 0;             /* content=? parameter (or NULL) */
130748   char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
130749   char **azNotindexed = 0;        /* The set of notindexed= columns */
130750   int nNotindexed = 0;            /* Size of azNotindexed[] array */
130751 
130752   assert( strlen(argv[0])==4 );
130753   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
130754        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
130755   );
130756 
130757   nDb = (int)strlen(argv[1]) + 1;
130758   nName = (int)strlen(argv[2]) + 1;
130759 
130760   nByte = sizeof(const char *) * (argc-2);
130761   aCol = (const char **)sqlite3_malloc(nByte);
130762   if( aCol ){
130763     memset((void*)aCol, 0, nByte);
130764     azNotindexed = (char **)sqlite3_malloc(nByte);
130765   }
130766   if( azNotindexed ){
130767     memset(azNotindexed, 0, nByte);
130768   }
130769   if( !aCol || !azNotindexed ){
130770     rc = SQLITE_NOMEM;
130771     goto fts3_init_out;
130772   }
130773 
130774   /* Loop through all of the arguments passed by the user to the FTS3/4
130775   ** module (i.e. all the column names and special arguments). This loop
130776   ** does the following:
130777   **
130778   **   + Figures out the number of columns the FTSX table will have, and
130779   **     the number of bytes of space that must be allocated to store copies
130780   **     of the column names.
130781   **
130782   **   + If there is a tokenizer specification included in the arguments,
130783   **     initializes the tokenizer pTokenizer.
130784   */
130785   for(i=3; rc==SQLITE_OK && i<argc; i++){
130786     char const *z = argv[i];
130787     int nKey;
130788     char *zVal;
130789 
130790     /* Check if this is a tokenizer specification */
130791     if( !pTokenizer
130792      && strlen(z)>8
130793      && 0==sqlite3_strnicmp(z, "tokenize", 8)
130794      && 0==sqlite3Fts3IsIdChar(z[8])
130795     ){
130796       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
130797     }
130798 
130799     /* Check if it is an FTS4 special argument. */
130800     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
130801       struct Fts4Option {
130802         const char *zOpt;
130803         int nOpt;
130804       } aFts4Opt[] = {
130805         { "matchinfo",   9 },     /* 0 -> MATCHINFO */
130806         { "prefix",      6 },     /* 1 -> PREFIX */
130807         { "compress",    8 },     /* 2 -> COMPRESS */
130808         { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
130809         { "order",       5 },     /* 4 -> ORDER */
130810         { "content",     7 },     /* 5 -> CONTENT */
130811         { "languageid", 10 },     /* 6 -> LANGUAGEID */
130812         { "notindexed", 10 }      /* 7 -> NOTINDEXED */
130813       };
130814 
130815       int iOpt;
130816       if( !zVal ){
130817         rc = SQLITE_NOMEM;
130818       }else{
130819         for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
130820           struct Fts4Option *pOp = &aFts4Opt[iOpt];
130821           if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
130822             break;
130823           }
130824         }
130825         if( iOpt==SizeofArray(aFts4Opt) ){
130826           *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
130827           rc = SQLITE_ERROR;
130828         }else{
130829           switch( iOpt ){
130830             case 0:               /* MATCHINFO */
130831               if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
130832                 *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
130833                 rc = SQLITE_ERROR;
130834               }
130835               bNoDocsize = 1;
130836               break;
130837 
130838             case 1:               /* PREFIX */
130839               sqlite3_free(zPrefix);
130840               zPrefix = zVal;
130841               zVal = 0;
130842               break;
130843 
130844             case 2:               /* COMPRESS */
130845               sqlite3_free(zCompress);
130846               zCompress = zVal;
130847               zVal = 0;
130848               break;
130849 
130850             case 3:               /* UNCOMPRESS */
130851               sqlite3_free(zUncompress);
130852               zUncompress = zVal;
130853               zVal = 0;
130854               break;
130855 
130856             case 4:               /* ORDER */
130857               if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
130858                && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
130859               ){
130860                 *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
130861                 rc = SQLITE_ERROR;
130862               }
130863               bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
130864               break;
130865 
130866             case 5:              /* CONTENT */
130867               sqlite3_free(zContent);
130868               zContent = zVal;
130869               zVal = 0;
130870               break;
130871 
130872             case 6:              /* LANGUAGEID */
130873               assert( iOpt==6 );
130874               sqlite3_free(zLanguageid);
130875               zLanguageid = zVal;
130876               zVal = 0;
130877               break;
130878 
130879             case 7:              /* NOTINDEXED */
130880               azNotindexed[nNotindexed++] = zVal;
130881               zVal = 0;
130882               break;
130883           }
130884         }
130885         sqlite3_free(zVal);
130886       }
130887     }
130888 
130889     /* Otherwise, the argument is a column name. */
130890     else {
130891       nString += (int)(strlen(z) + 1);
130892       aCol[nCol++] = z;
130893     }
130894   }
130895 
130896   /* If a content=xxx option was specified, the following:
130897   **
130898   **   1. Ignore any compress= and uncompress= options.
130899   **
130900   **   2. If no column names were specified as part of the CREATE VIRTUAL
130901   **      TABLE statement, use all columns from the content table.
130902   */
130903   if( rc==SQLITE_OK && zContent ){
130904     sqlite3_free(zCompress);
130905     sqlite3_free(zUncompress);
130906     zCompress = 0;
130907     zUncompress = 0;
130908     if( nCol==0 ){
130909       sqlite3_free((void*)aCol);
130910       aCol = 0;
130911       rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
130912 
130913       /* If a languageid= option was specified, remove the language id
130914       ** column from the aCol[] array. */
130915       if( rc==SQLITE_OK && zLanguageid ){
130916         int j;
130917         for(j=0; j<nCol; j++){
130918           if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
130919             int k;
130920             for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
130921             nCol--;
130922             break;
130923           }
130924         }
130925       }
130926     }
130927   }
130928   if( rc!=SQLITE_OK ) goto fts3_init_out;
130929 
130930   if( nCol==0 ){
130931     assert( nString==0 );
130932     aCol[0] = "content";
130933     nString = 8;
130934     nCol = 1;
130935   }
130936 
130937   if( pTokenizer==0 ){
130938     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
130939     if( rc!=SQLITE_OK ) goto fts3_init_out;
130940   }
130941   assert( pTokenizer );
130942 
130943   rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
130944   if( rc==SQLITE_ERROR ){
130945     assert( zPrefix );
130946     *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
130947   }
130948   if( rc!=SQLITE_OK ) goto fts3_init_out;
130949 
130950   /* Allocate and populate the Fts3Table structure. */
130951   nByte = sizeof(Fts3Table) +                  /* Fts3Table */
130952           nCol * sizeof(char *) +              /* azColumn */
130953           nIndex * sizeof(struct Fts3Index) +  /* aIndex */
130954           nCol * sizeof(u8) +                  /* abNotindexed */
130955           nName +                              /* zName */
130956           nDb +                                /* zDb */
130957           nString;                             /* Space for azColumn strings */
130958   p = (Fts3Table*)sqlite3_malloc(nByte);
130959   if( p==0 ){
130960     rc = SQLITE_NOMEM;
130961     goto fts3_init_out;
130962   }
130963   memset(p, 0, nByte);
130964   p->db = db;
130965   p->nColumn = nCol;
130966   p->nPendingData = 0;
130967   p->azColumn = (char **)&p[1];
130968   p->pTokenizer = pTokenizer;
130969   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
130970   p->bHasDocsize = (isFts4 && bNoDocsize==0);
130971   p->bHasStat = isFts4;
130972   p->bFts4 = isFts4;
130973   p->bDescIdx = bDescIdx;
130974   p->nAutoincrmerge = 0xff;   /* 0xff means setting unknown */
130975   p->zContentTbl = zContent;
130976   p->zLanguageid = zLanguageid;
130977   zContent = 0;
130978   zLanguageid = 0;
130979   TESTONLY( p->inTransaction = -1 );
130980   TESTONLY( p->mxSavepoint = -1 );
130981 
130982   p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
130983   memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
130984   p->nIndex = nIndex;
130985   for(i=0; i<nIndex; i++){
130986     fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
130987   }
130988   p->abNotindexed = (u8 *)&p->aIndex[nIndex];
130989 
130990   /* Fill in the zName and zDb fields of the vtab structure. */
130991   zCsr = (char *)&p->abNotindexed[nCol];
130992   p->zName = zCsr;
130993   memcpy(zCsr, argv[2], nName);
130994   zCsr += nName;
130995   p->zDb = zCsr;
130996   memcpy(zCsr, argv[1], nDb);
130997   zCsr += nDb;
130998 
130999   /* Fill in the azColumn array */
131000   for(iCol=0; iCol<nCol; iCol++){
131001     char *z;
131002     int n = 0;
131003     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
131004     memcpy(zCsr, z, n);
131005     zCsr[n] = '\0';
131006     sqlite3Fts3Dequote(zCsr);
131007     p->azColumn[iCol] = zCsr;
131008     zCsr += n+1;
131009     assert( zCsr <= &((char *)p)[nByte] );
131010   }
131011 
131012   /* Fill in the abNotindexed array */
131013   for(iCol=0; iCol<nCol; iCol++){
131014     int n = (int)strlen(p->azColumn[iCol]);
131015     for(i=0; i<nNotindexed; i++){
131016       char *zNot = azNotindexed[i];
131017       if( zNot && n==(int)strlen(zNot)
131018        && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
131019       ){
131020         p->abNotindexed[iCol] = 1;
131021         sqlite3_free(zNot);
131022         azNotindexed[i] = 0;
131023       }
131024     }
131025   }
131026   for(i=0; i<nNotindexed; i++){
131027     if( azNotindexed[i] ){
131028       *pzErr = sqlite3_mprintf("no such column: %s", azNotindexed[i]);
131029       rc = SQLITE_ERROR;
131030     }
131031   }
131032 
131033   if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
131034     char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
131035     rc = SQLITE_ERROR;
131036     *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
131037   }
131038   p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
131039   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
131040   if( rc!=SQLITE_OK ) goto fts3_init_out;
131041 
131042   /* If this is an xCreate call, create the underlying tables in the
131043   ** database. TODO: For xConnect(), it could verify that said tables exist.
131044   */
131045   if( isCreate ){
131046     rc = fts3CreateTables(p);
131047   }
131048 
131049   /* Check to see if a legacy fts3 table has been "upgraded" by the
131050   ** addition of a %_stat table so that it can use incremental merge.
131051   */
131052   if( !isFts4 && !isCreate ){
131053     p->bHasStat = 2;
131054   }
131055 
131056   /* Figure out the page-size for the database. This is required in order to
131057   ** estimate the cost of loading large doclists from the database.  */
131058   fts3DatabasePageSize(&rc, p);
131059   p->nNodeSize = p->nPgsz-35;
131060 
131061   /* Declare the table schema to SQLite. */
131062   fts3DeclareVtab(&rc, p);
131063 
131064 fts3_init_out:
131065   sqlite3_free(zPrefix);
131066   sqlite3_free(aIndex);
131067   sqlite3_free(zCompress);
131068   sqlite3_free(zUncompress);
131069   sqlite3_free(zContent);
131070   sqlite3_free(zLanguageid);
131071   for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
131072   sqlite3_free((void *)aCol);
131073   sqlite3_free((void *)azNotindexed);
131074   if( rc!=SQLITE_OK ){
131075     if( p ){
131076       fts3DisconnectMethod((sqlite3_vtab *)p);
131077     }else if( pTokenizer ){
131078       pTokenizer->pModule->xDestroy(pTokenizer);
131079     }
131080   }else{
131081     assert( p->pSegments==0 );
131082     *ppVTab = &p->base;
131083   }
131084   return rc;
131085 }
131086 
131087 /*
131088 ** The xConnect() and xCreate() methods for the virtual table. All the
131089 ** work is done in function fts3InitVtab().
131090 */
131091 static int fts3ConnectMethod(
131092   sqlite3 *db,                    /* Database connection */
131093   void *pAux,                     /* Pointer to tokenizer hash table */
131094   int argc,                       /* Number of elements in argv array */
131095   const char * const *argv,       /* xCreate/xConnect argument array */
131096   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
131097   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
131098 ){
131099   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
131100 }
131101 static int fts3CreateMethod(
131102   sqlite3 *db,                    /* Database connection */
131103   void *pAux,                     /* Pointer to tokenizer hash table */
131104   int argc,                       /* Number of elements in argv array */
131105   const char * const *argv,       /* xCreate/xConnect argument array */
131106   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
131107   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
131108 ){
131109   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
131110 }
131111 
131112 /*
131113 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
131114 ** extension is currently being used by a version of SQLite too old to
131115 ** support estimatedRows. In that case this function is a no-op.
131116 */
131117 static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
131118 #if SQLITE_VERSION_NUMBER>=3008002
131119   if( sqlite3_libversion_number()>=3008002 ){
131120     pIdxInfo->estimatedRows = nRow;
131121   }
131122 #endif
131123 }
131124 
131125 /*
131126 ** Implementation of the xBestIndex method for FTS3 tables. There
131127 ** are three possible strategies, in order of preference:
131128 **
131129 **   1. Direct lookup by rowid or docid.
131130 **   2. Full-text search using a MATCH operator on a non-docid column.
131131 **   3. Linear scan of %_content table.
131132 */
131133 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
131134   Fts3Table *p = (Fts3Table *)pVTab;
131135   int i;                          /* Iterator variable */
131136   int iCons = -1;                 /* Index of constraint to use */
131137 
131138   int iLangidCons = -1;           /* Index of langid=x constraint, if present */
131139   int iDocidGe = -1;              /* Index of docid>=x constraint, if present */
131140   int iDocidLe = -1;              /* Index of docid<=x constraint, if present */
131141   int iIdx;
131142 
131143   /* By default use a full table scan. This is an expensive option,
131144   ** so search through the constraints to see if a more efficient
131145   ** strategy is possible.
131146   */
131147   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
131148   pInfo->estimatedCost = 5000000;
131149   for(i=0; i<pInfo->nConstraint; i++){
131150     int bDocid;                 /* True if this constraint is on docid */
131151     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
131152     if( pCons->usable==0 ){
131153       if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
131154         /* There exists an unusable MATCH constraint. This means that if
131155         ** the planner does elect to use the results of this call as part
131156         ** of the overall query plan the user will see an "unable to use
131157         ** function MATCH in the requested context" error. To discourage
131158         ** this, return a very high cost here.  */
131159         pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
131160         pInfo->estimatedCost = 1e50;
131161         fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
131162         return SQLITE_OK;
131163       }
131164       continue;
131165     }
131166 
131167     bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
131168 
131169     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
131170     if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
131171       pInfo->idxNum = FTS3_DOCID_SEARCH;
131172       pInfo->estimatedCost = 1.0;
131173       iCons = i;
131174     }
131175 
131176     /* A MATCH constraint. Use a full-text search.
131177     **
131178     ** If there is more than one MATCH constraint available, use the first
131179     ** one encountered. If there is both a MATCH constraint and a direct
131180     ** rowid/docid lookup, prefer the MATCH strategy. This is done even
131181     ** though the rowid/docid lookup is faster than a MATCH query, selecting
131182     ** it would lead to an "unable to use function MATCH in the requested
131183     ** context" error.
131184     */
131185     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
131186      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
131187     ){
131188       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
131189       pInfo->estimatedCost = 2.0;
131190       iCons = i;
131191     }
131192 
131193     /* Equality constraint on the langid column */
131194     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
131195      && pCons->iColumn==p->nColumn + 2
131196     ){
131197       iLangidCons = i;
131198     }
131199 
131200     if( bDocid ){
131201       switch( pCons->op ){
131202         case SQLITE_INDEX_CONSTRAINT_GE:
131203         case SQLITE_INDEX_CONSTRAINT_GT:
131204           iDocidGe = i;
131205           break;
131206 
131207         case SQLITE_INDEX_CONSTRAINT_LE:
131208         case SQLITE_INDEX_CONSTRAINT_LT:
131209           iDocidLe = i;
131210           break;
131211       }
131212     }
131213   }
131214 
131215   iIdx = 1;
131216   if( iCons>=0 ){
131217     pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
131218     pInfo->aConstraintUsage[iCons].omit = 1;
131219   }
131220   if( iLangidCons>=0 ){
131221     pInfo->idxNum |= FTS3_HAVE_LANGID;
131222     pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
131223   }
131224   if( iDocidGe>=0 ){
131225     pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
131226     pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
131227   }
131228   if( iDocidLe>=0 ){
131229     pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
131230     pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
131231   }
131232 
131233   /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
131234   ** docid) order. Both ascending and descending are possible.
131235   */
131236   if( pInfo->nOrderBy==1 ){
131237     struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
131238     if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
131239       if( pOrder->desc ){
131240         pInfo->idxStr = "DESC";
131241       }else{
131242         pInfo->idxStr = "ASC";
131243       }
131244       pInfo->orderByConsumed = 1;
131245     }
131246   }
131247 
131248   assert( p->pSegments==0 );
131249   return SQLITE_OK;
131250 }
131251 
131252 /*
131253 ** Implementation of xOpen method.
131254 */
131255 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
131256   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
131257 
131258   UNUSED_PARAMETER(pVTab);
131259 
131260   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
131261   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
131262   ** if the allocation fails, return SQLITE_NOMEM.
131263   */
131264   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
131265   if( !pCsr ){
131266     return SQLITE_NOMEM;
131267   }
131268   memset(pCsr, 0, sizeof(Fts3Cursor));
131269   return SQLITE_OK;
131270 }
131271 
131272 /*
131273 ** Close the cursor.  For additional information see the documentation
131274 ** on the xClose method of the virtual table interface.
131275 */
131276 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
131277   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
131278   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
131279   sqlite3_finalize(pCsr->pStmt);
131280   sqlite3Fts3ExprFree(pCsr->pExpr);
131281   sqlite3Fts3FreeDeferredTokens(pCsr);
131282   sqlite3_free(pCsr->aDoclist);
131283   sqlite3_free(pCsr->aMatchinfo);
131284   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
131285   sqlite3_free(pCsr);
131286   return SQLITE_OK;
131287 }
131288 
131289 /*
131290 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
131291 ** compose and prepare an SQL statement of the form:
131292 **
131293 **    "SELECT <columns> FROM %_content WHERE rowid = ?"
131294 **
131295 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
131296 ** it. If an error occurs, return an SQLite error code.
131297 **
131298 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
131299 */
131300 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
131301   int rc = SQLITE_OK;
131302   if( pCsr->pStmt==0 ){
131303     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
131304     char *zSql;
131305     zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
131306     if( !zSql ) return SQLITE_NOMEM;
131307     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
131308     sqlite3_free(zSql);
131309   }
131310   *ppStmt = pCsr->pStmt;
131311   return rc;
131312 }
131313 
131314 /*
131315 ** Position the pCsr->pStmt statement so that it is on the row
131316 ** of the %_content table that contains the last match.  Return
131317 ** SQLITE_OK on success.
131318 */
131319 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
131320   int rc = SQLITE_OK;
131321   if( pCsr->isRequireSeek ){
131322     sqlite3_stmt *pStmt = 0;
131323 
131324     rc = fts3CursorSeekStmt(pCsr, &pStmt);
131325     if( rc==SQLITE_OK ){
131326       sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
131327       pCsr->isRequireSeek = 0;
131328       if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
131329         return SQLITE_OK;
131330       }else{
131331         rc = sqlite3_reset(pCsr->pStmt);
131332         if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
131333           /* If no row was found and no error has occurred, then the %_content
131334           ** table is missing a row that is present in the full-text index.
131335           ** The data structures are corrupt.  */
131336           rc = FTS_CORRUPT_VTAB;
131337           pCsr->isEof = 1;
131338         }
131339       }
131340     }
131341   }
131342 
131343   if( rc!=SQLITE_OK && pContext ){
131344     sqlite3_result_error_code(pContext, rc);
131345   }
131346   return rc;
131347 }
131348 
131349 /*
131350 ** This function is used to process a single interior node when searching
131351 ** a b-tree for a term or term prefix. The node data is passed to this
131352 ** function via the zNode/nNode parameters. The term to search for is
131353 ** passed in zTerm/nTerm.
131354 **
131355 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
131356 ** of the child node that heads the sub-tree that may contain the term.
131357 **
131358 ** If piLast is not NULL, then *piLast is set to the right-most child node
131359 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
131360 ** a prefix.
131361 **
131362 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
131363 */
131364 static int fts3ScanInteriorNode(
131365   const char *zTerm,              /* Term to select leaves for */
131366   int nTerm,                      /* Size of term zTerm in bytes */
131367   const char *zNode,              /* Buffer containing segment interior node */
131368   int nNode,                      /* Size of buffer at zNode */
131369   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
131370   sqlite3_int64 *piLast           /* OUT: Selected child node */
131371 ){
131372   int rc = SQLITE_OK;             /* Return code */
131373   const char *zCsr = zNode;       /* Cursor to iterate through node */
131374   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
131375   char *zBuffer = 0;              /* Buffer to load terms into */
131376   int nAlloc = 0;                 /* Size of allocated buffer */
131377   int isFirstTerm = 1;            /* True when processing first term on page */
131378   sqlite3_int64 iChild;           /* Block id of child node to descend to */
131379 
131380   /* Skip over the 'height' varint that occurs at the start of every
131381   ** interior node. Then load the blockid of the left-child of the b-tree
131382   ** node into variable iChild.
131383   **
131384   ** Even if the data structure on disk is corrupted, this (reading two
131385   ** varints from the buffer) does not risk an overread. If zNode is a
131386   ** root node, then the buffer comes from a SELECT statement. SQLite does
131387   ** not make this guarantee explicitly, but in practice there are always
131388   ** either more than 20 bytes of allocated space following the nNode bytes of
131389   ** contents, or two zero bytes. Or, if the node is read from the %_segments
131390   ** table, then there are always 20 bytes of zeroed padding following the
131391   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
131392   */
131393   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
131394   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
131395   if( zCsr>zEnd ){
131396     return FTS_CORRUPT_VTAB;
131397   }
131398 
131399   while( zCsr<zEnd && (piFirst || piLast) ){
131400     int cmp;                      /* memcmp() result */
131401     int nSuffix;                  /* Size of term suffix */
131402     int nPrefix = 0;              /* Size of term prefix */
131403     int nBuffer;                  /* Total term size */
131404 
131405     /* Load the next term on the node into zBuffer. Use realloc() to expand
131406     ** the size of zBuffer if required.  */
131407     if( !isFirstTerm ){
131408       zCsr += fts3GetVarint32(zCsr, &nPrefix);
131409     }
131410     isFirstTerm = 0;
131411     zCsr += fts3GetVarint32(zCsr, &nSuffix);
131412 
131413     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
131414       rc = FTS_CORRUPT_VTAB;
131415       goto finish_scan;
131416     }
131417     if( nPrefix+nSuffix>nAlloc ){
131418       char *zNew;
131419       nAlloc = (nPrefix+nSuffix) * 2;
131420       zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
131421       if( !zNew ){
131422         rc = SQLITE_NOMEM;
131423         goto finish_scan;
131424       }
131425       zBuffer = zNew;
131426     }
131427     assert( zBuffer );
131428     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
131429     nBuffer = nPrefix + nSuffix;
131430     zCsr += nSuffix;
131431 
131432     /* Compare the term we are searching for with the term just loaded from
131433     ** the interior node. If the specified term is greater than or equal
131434     ** to the term from the interior node, then all terms on the sub-tree
131435     ** headed by node iChild are smaller than zTerm. No need to search
131436     ** iChild.
131437     **
131438     ** If the interior node term is larger than the specified term, then
131439     ** the tree headed by iChild may contain the specified term.
131440     */
131441     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
131442     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
131443       *piFirst = iChild;
131444       piFirst = 0;
131445     }
131446 
131447     if( piLast && cmp<0 ){
131448       *piLast = iChild;
131449       piLast = 0;
131450     }
131451 
131452     iChild++;
131453   };
131454 
131455   if( piFirst ) *piFirst = iChild;
131456   if( piLast ) *piLast = iChild;
131457 
131458  finish_scan:
131459   sqlite3_free(zBuffer);
131460   return rc;
131461 }
131462 
131463 
131464 /*
131465 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
131466 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
131467 ** contains a term. This function searches the sub-tree headed by the zNode
131468 ** node for the range of leaf nodes that may contain the specified term
131469 ** or terms for which the specified term is a prefix.
131470 **
131471 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
131472 ** left-most leaf node in the tree that may contain the specified term.
131473 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
131474 ** right-most leaf node that may contain a term for which the specified
131475 ** term is a prefix.
131476 **
131477 ** It is possible that the range of returned leaf nodes does not contain
131478 ** the specified term or any terms for which it is a prefix. However, if the
131479 ** segment does contain any such terms, they are stored within the identified
131480 ** range. Because this function only inspects interior segment nodes (and
131481 ** never loads leaf nodes into memory), it is not possible to be sure.
131482 **
131483 ** If an error occurs, an error code other than SQLITE_OK is returned.
131484 */
131485 static int fts3SelectLeaf(
131486   Fts3Table *p,                   /* Virtual table handle */
131487   const char *zTerm,              /* Term to select leaves for */
131488   int nTerm,                      /* Size of term zTerm in bytes */
131489   const char *zNode,              /* Buffer containing segment interior node */
131490   int nNode,                      /* Size of buffer at zNode */
131491   sqlite3_int64 *piLeaf,          /* Selected leaf node */
131492   sqlite3_int64 *piLeaf2          /* Selected leaf node */
131493 ){
131494   int rc;                         /* Return code */
131495   int iHeight;                    /* Height of this node in tree */
131496 
131497   assert( piLeaf || piLeaf2 );
131498 
131499   fts3GetVarint32(zNode, &iHeight);
131500   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
131501   assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
131502 
131503   if( rc==SQLITE_OK && iHeight>1 ){
131504     char *zBlob = 0;              /* Blob read from %_segments table */
131505     int nBlob;                    /* Size of zBlob in bytes */
131506 
131507     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
131508       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
131509       if( rc==SQLITE_OK ){
131510         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
131511       }
131512       sqlite3_free(zBlob);
131513       piLeaf = 0;
131514       zBlob = 0;
131515     }
131516 
131517     if( rc==SQLITE_OK ){
131518       rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
131519     }
131520     if( rc==SQLITE_OK ){
131521       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
131522     }
131523     sqlite3_free(zBlob);
131524   }
131525 
131526   return rc;
131527 }
131528 
131529 /*
131530 ** This function is used to create delta-encoded serialized lists of FTS3
131531 ** varints. Each call to this function appends a single varint to a list.
131532 */
131533 static void fts3PutDeltaVarint(
131534   char **pp,                      /* IN/OUT: Output pointer */
131535   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
131536   sqlite3_int64 iVal              /* Write this value to the list */
131537 ){
131538   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
131539   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
131540   *piPrev = iVal;
131541 }
131542 
131543 /*
131544 ** When this function is called, *ppPoslist is assumed to point to the
131545 ** start of a position-list. After it returns, *ppPoslist points to the
131546 ** first byte after the position-list.
131547 **
131548 ** A position list is list of positions (delta encoded) and columns for
131549 ** a single document record of a doclist.  So, in other words, this
131550 ** routine advances *ppPoslist so that it points to the next docid in
131551 ** the doclist, or to the first byte past the end of the doclist.
131552 **
131553 ** If pp is not NULL, then the contents of the position list are copied
131554 ** to *pp. *pp is set to point to the first byte past the last byte copied
131555 ** before this function returns.
131556 */
131557 static void fts3PoslistCopy(char **pp, char **ppPoslist){
131558   char *pEnd = *ppPoslist;
131559   char c = 0;
131560 
131561   /* The end of a position list is marked by a zero encoded as an FTS3
131562   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
131563   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
131564   ** of some other, multi-byte, value.
131565   **
131566   ** The following while-loop moves pEnd to point to the first byte that is not
131567   ** immediately preceded by a byte with the 0x80 bit set. Then increments
131568   ** pEnd once more so that it points to the byte immediately following the
131569   ** last byte in the position-list.
131570   */
131571   while( *pEnd | c ){
131572     c = *pEnd++ & 0x80;
131573     testcase( c!=0 && (*pEnd)==0 );
131574   }
131575   pEnd++;  /* Advance past the POS_END terminator byte */
131576 
131577   if( pp ){
131578     int n = (int)(pEnd - *ppPoslist);
131579     char *p = *pp;
131580     memcpy(p, *ppPoslist, n);
131581     p += n;
131582     *pp = p;
131583   }
131584   *ppPoslist = pEnd;
131585 }
131586 
131587 /*
131588 ** When this function is called, *ppPoslist is assumed to point to the
131589 ** start of a column-list. After it returns, *ppPoslist points to the
131590 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
131591 **
131592 ** A column-list is list of delta-encoded positions for a single column
131593 ** within a single document within a doclist.
131594 **
131595 ** The column-list is terminated either by a POS_COLUMN varint (1) or
131596 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
131597 ** the POS_COLUMN or POS_END that terminates the column-list.
131598 **
131599 ** If pp is not NULL, then the contents of the column-list are copied
131600 ** to *pp. *pp is set to point to the first byte past the last byte copied
131601 ** before this function returns.  The POS_COLUMN or POS_END terminator
131602 ** is not copied into *pp.
131603 */
131604 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
131605   char *pEnd = *ppPoslist;
131606   char c = 0;
131607 
131608   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
131609   ** not part of a multi-byte varint.
131610   */
131611   while( 0xFE & (*pEnd | c) ){
131612     c = *pEnd++ & 0x80;
131613     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
131614   }
131615   if( pp ){
131616     int n = (int)(pEnd - *ppPoslist);
131617     char *p = *pp;
131618     memcpy(p, *ppPoslist, n);
131619     p += n;
131620     *pp = p;
131621   }
131622   *ppPoslist = pEnd;
131623 }
131624 
131625 /*
131626 ** Value used to signify the end of an position-list. This is safe because
131627 ** it is not possible to have a document with 2^31 terms.
131628 */
131629 #define POSITION_LIST_END 0x7fffffff
131630 
131631 /*
131632 ** This function is used to help parse position-lists. When this function is
131633 ** called, *pp may point to the start of the next varint in the position-list
131634 ** being parsed, or it may point to 1 byte past the end of the position-list
131635 ** (in which case **pp will be a terminator bytes POS_END (0) or
131636 ** (1)).
131637 **
131638 ** If *pp points past the end of the current position-list, set *pi to
131639 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
131640 ** increment the current value of *pi by the value read, and set *pp to
131641 ** point to the next value before returning.
131642 **
131643 ** Before calling this routine *pi must be initialized to the value of
131644 ** the previous position, or zero if we are reading the first position
131645 ** in the position-list.  Because positions are delta-encoded, the value
131646 ** of the previous position is needed in order to compute the value of
131647 ** the next position.
131648 */
131649 static void fts3ReadNextPos(
131650   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
131651   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
131652 ){
131653   if( (**pp)&0xFE ){
131654     fts3GetDeltaVarint(pp, pi);
131655     *pi -= 2;
131656   }else{
131657     *pi = POSITION_LIST_END;
131658   }
131659 }
131660 
131661 /*
131662 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
131663 ** the value of iCol encoded as a varint to *pp.   This will start a new
131664 ** column list.
131665 **
131666 ** Set *pp to point to the byte just after the last byte written before
131667 ** returning (do not modify it if iCol==0). Return the total number of bytes
131668 ** written (0 if iCol==0).
131669 */
131670 static int fts3PutColNumber(char **pp, int iCol){
131671   int n = 0;                      /* Number of bytes written */
131672   if( iCol ){
131673     char *p = *pp;                /* Output pointer */
131674     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
131675     *p = 0x01;
131676     *pp = &p[n];
131677   }
131678   return n;
131679 }
131680 
131681 /*
131682 ** Compute the union of two position lists.  The output written
131683 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
131684 ** order and with any duplicates removed.  All pointers are
131685 ** updated appropriately.   The caller is responsible for insuring
131686 ** that there is enough space in *pp to hold the complete output.
131687 */
131688 static void fts3PoslistMerge(
131689   char **pp,                      /* Output buffer */
131690   char **pp1,                     /* Left input list */
131691   char **pp2                      /* Right input list */
131692 ){
131693   char *p = *pp;
131694   char *p1 = *pp1;
131695   char *p2 = *pp2;
131696 
131697   while( *p1 || *p2 ){
131698     int iCol1;         /* The current column index in pp1 */
131699     int iCol2;         /* The current column index in pp2 */
131700 
131701     if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
131702     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
131703     else iCol1 = 0;
131704 
131705     if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
131706     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
131707     else iCol2 = 0;
131708 
131709     if( iCol1==iCol2 ){
131710       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
131711       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
131712       sqlite3_int64 iPrev = 0;
131713       int n = fts3PutColNumber(&p, iCol1);
131714       p1 += n;
131715       p2 += n;
131716 
131717       /* At this point, both p1 and p2 point to the start of column-lists
131718       ** for the same column (the column with index iCol1 and iCol2).
131719       ** A column-list is a list of non-negative delta-encoded varints, each
131720       ** incremented by 2 before being stored. Each list is terminated by a
131721       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
131722       ** and writes the results to buffer p. p is left pointing to the byte
131723       ** after the list written. No terminator (POS_END or POS_COLUMN) is
131724       ** written to the output.
131725       */
131726       fts3GetDeltaVarint(&p1, &i1);
131727       fts3GetDeltaVarint(&p2, &i2);
131728       do {
131729         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
131730         iPrev -= 2;
131731         if( i1==i2 ){
131732           fts3ReadNextPos(&p1, &i1);
131733           fts3ReadNextPos(&p2, &i2);
131734         }else if( i1<i2 ){
131735           fts3ReadNextPos(&p1, &i1);
131736         }else{
131737           fts3ReadNextPos(&p2, &i2);
131738         }
131739       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
131740     }else if( iCol1<iCol2 ){
131741       p1 += fts3PutColNumber(&p, iCol1);
131742       fts3ColumnlistCopy(&p, &p1);
131743     }else{
131744       p2 += fts3PutColNumber(&p, iCol2);
131745       fts3ColumnlistCopy(&p, &p2);
131746     }
131747   }
131748 
131749   *p++ = POS_END;
131750   *pp = p;
131751   *pp1 = p1 + 1;
131752   *pp2 = p2 + 1;
131753 }
131754 
131755 /*
131756 ** This function is used to merge two position lists into one. When it is
131757 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
131758 ** the part of a doclist that follows each document id. For example, if a row
131759 ** contains:
131760 **
131761 **     'a b c'|'x y z'|'a b b a'
131762 **
131763 ** Then the position list for this row for token 'b' would consist of:
131764 **
131765 **     0x02 0x01 0x02 0x03 0x03 0x00
131766 **
131767 ** When this function returns, both *pp1 and *pp2 are left pointing to the
131768 ** byte following the 0x00 terminator of their respective position lists.
131769 **
131770 ** If isSaveLeft is 0, an entry is added to the output position list for
131771 ** each position in *pp2 for which there exists one or more positions in
131772 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
131773 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
131774 ** slots before it.
131775 **
131776 ** e.g. nToken==1 searches for adjacent positions.
131777 */
131778 static int fts3PoslistPhraseMerge(
131779   char **pp,                      /* IN/OUT: Preallocated output buffer */
131780   int nToken,                     /* Maximum difference in token positions */
131781   int isSaveLeft,                 /* Save the left position */
131782   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
131783   char **pp1,                     /* IN/OUT: Left input list */
131784   char **pp2                      /* IN/OUT: Right input list */
131785 ){
131786   char *p = *pp;
131787   char *p1 = *pp1;
131788   char *p2 = *pp2;
131789   int iCol1 = 0;
131790   int iCol2 = 0;
131791 
131792   /* Never set both isSaveLeft and isExact for the same invocation. */
131793   assert( isSaveLeft==0 || isExact==0 );
131794 
131795   assert( p!=0 && *p1!=0 && *p2!=0 );
131796   if( *p1==POS_COLUMN ){
131797     p1++;
131798     p1 += fts3GetVarint32(p1, &iCol1);
131799   }
131800   if( *p2==POS_COLUMN ){
131801     p2++;
131802     p2 += fts3GetVarint32(p2, &iCol2);
131803   }
131804 
131805   while( 1 ){
131806     if( iCol1==iCol2 ){
131807       char *pSave = p;
131808       sqlite3_int64 iPrev = 0;
131809       sqlite3_int64 iPos1 = 0;
131810       sqlite3_int64 iPos2 = 0;
131811 
131812       if( iCol1 ){
131813         *p++ = POS_COLUMN;
131814         p += sqlite3Fts3PutVarint(p, iCol1);
131815       }
131816 
131817       assert( *p1!=POS_END && *p1!=POS_COLUMN );
131818       assert( *p2!=POS_END && *p2!=POS_COLUMN );
131819       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
131820       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
131821 
131822       while( 1 ){
131823         if( iPos2==iPos1+nToken
131824          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
131825         ){
131826           sqlite3_int64 iSave;
131827           iSave = isSaveLeft ? iPos1 : iPos2;
131828           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
131829           pSave = 0;
131830           assert( p );
131831         }
131832         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
131833           if( (*p2&0xFE)==0 ) break;
131834           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
131835         }else{
131836           if( (*p1&0xFE)==0 ) break;
131837           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
131838         }
131839       }
131840 
131841       if( pSave ){
131842         assert( pp && p );
131843         p = pSave;
131844       }
131845 
131846       fts3ColumnlistCopy(0, &p1);
131847       fts3ColumnlistCopy(0, &p2);
131848       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
131849       if( 0==*p1 || 0==*p2 ) break;
131850 
131851       p1++;
131852       p1 += fts3GetVarint32(p1, &iCol1);
131853       p2++;
131854       p2 += fts3GetVarint32(p2, &iCol2);
131855     }
131856 
131857     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
131858     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
131859     ** end of the position list, or the 0x01 that precedes the next
131860     ** column-number in the position list.
131861     */
131862     else if( iCol1<iCol2 ){
131863       fts3ColumnlistCopy(0, &p1);
131864       if( 0==*p1 ) break;
131865       p1++;
131866       p1 += fts3GetVarint32(p1, &iCol1);
131867     }else{
131868       fts3ColumnlistCopy(0, &p2);
131869       if( 0==*p2 ) break;
131870       p2++;
131871       p2 += fts3GetVarint32(p2, &iCol2);
131872     }
131873   }
131874 
131875   fts3PoslistCopy(0, &p2);
131876   fts3PoslistCopy(0, &p1);
131877   *pp1 = p1;
131878   *pp2 = p2;
131879   if( *pp==p ){
131880     return 0;
131881   }
131882   *p++ = 0x00;
131883   *pp = p;
131884   return 1;
131885 }
131886 
131887 /*
131888 ** Merge two position-lists as required by the NEAR operator. The argument
131889 ** position lists correspond to the left and right phrases of an expression
131890 ** like:
131891 **
131892 **     "phrase 1" NEAR "phrase number 2"
131893 **
131894 ** Position list *pp1 corresponds to the left-hand side of the NEAR
131895 ** expression and *pp2 to the right. As usual, the indexes in the position
131896 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
131897 ** in the example above).
131898 **
131899 ** The output position list - written to *pp - is a copy of *pp2 with those
131900 ** entries that are not sufficiently NEAR entries in *pp1 removed.
131901 */
131902 static int fts3PoslistNearMerge(
131903   char **pp,                      /* Output buffer */
131904   char *aTmp,                     /* Temporary buffer space */
131905   int nRight,                     /* Maximum difference in token positions */
131906   int nLeft,                      /* Maximum difference in token positions */
131907   char **pp1,                     /* IN/OUT: Left input list */
131908   char **pp2                      /* IN/OUT: Right input list */
131909 ){
131910   char *p1 = *pp1;
131911   char *p2 = *pp2;
131912 
131913   char *pTmp1 = aTmp;
131914   char *pTmp2;
131915   char *aTmp2;
131916   int res = 1;
131917 
131918   fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
131919   aTmp2 = pTmp2 = pTmp1;
131920   *pp1 = p1;
131921   *pp2 = p2;
131922   fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
131923   if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
131924     fts3PoslistMerge(pp, &aTmp, &aTmp2);
131925   }else if( pTmp1!=aTmp ){
131926     fts3PoslistCopy(pp, &aTmp);
131927   }else if( pTmp2!=aTmp2 ){
131928     fts3PoslistCopy(pp, &aTmp2);
131929   }else{
131930     res = 0;
131931   }
131932 
131933   return res;
131934 }
131935 
131936 /*
131937 ** An instance of this function is used to merge together the (potentially
131938 ** large number of) doclists for each term that matches a prefix query.
131939 ** See function fts3TermSelectMerge() for details.
131940 */
131941 typedef struct TermSelect TermSelect;
131942 struct TermSelect {
131943   char *aaOutput[16];             /* Malloc'd output buffers */
131944   int anOutput[16];               /* Size each output buffer in bytes */
131945 };
131946 
131947 /*
131948 ** This function is used to read a single varint from a buffer. Parameter
131949 ** pEnd points 1 byte past the end of the buffer. When this function is
131950 ** called, if *pp points to pEnd or greater, then the end of the buffer
131951 ** has been reached. In this case *pp is set to 0 and the function returns.
131952 **
131953 ** If *pp does not point to or past pEnd, then a single varint is read
131954 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
131955 **
131956 ** If bDescIdx is false, the value read is added to *pVal before returning.
131957 ** If it is true, the value read is subtracted from *pVal before this
131958 ** function returns.
131959 */
131960 static void fts3GetDeltaVarint3(
131961   char **pp,                      /* IN/OUT: Point to read varint from */
131962   char *pEnd,                     /* End of buffer */
131963   int bDescIdx,                   /* True if docids are descending */
131964   sqlite3_int64 *pVal             /* IN/OUT: Integer value */
131965 ){
131966   if( *pp>=pEnd ){
131967     *pp = 0;
131968   }else{
131969     sqlite3_int64 iVal;
131970     *pp += sqlite3Fts3GetVarint(*pp, &iVal);
131971     if( bDescIdx ){
131972       *pVal -= iVal;
131973     }else{
131974       *pVal += iVal;
131975     }
131976   }
131977 }
131978 
131979 /*
131980 ** This function is used to write a single varint to a buffer. The varint
131981 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
131982 ** end of the value written.
131983 **
131984 ** If *pbFirst is zero when this function is called, the value written to
131985 ** the buffer is that of parameter iVal.
131986 **
131987 ** If *pbFirst is non-zero when this function is called, then the value
131988 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
131989 ** (if bDescIdx is non-zero).
131990 **
131991 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
131992 ** to the value of parameter iVal.
131993 */
131994 static void fts3PutDeltaVarint3(
131995   char **pp,                      /* IN/OUT: Output pointer */
131996   int bDescIdx,                   /* True for descending docids */
131997   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
131998   int *pbFirst,                   /* IN/OUT: True after first int written */
131999   sqlite3_int64 iVal              /* Write this value to the list */
132000 ){
132001   sqlite3_int64 iWrite;
132002   if( bDescIdx==0 || *pbFirst==0 ){
132003     iWrite = iVal - *piPrev;
132004   }else{
132005     iWrite = *piPrev - iVal;
132006   }
132007   assert( *pbFirst || *piPrev==0 );
132008   assert( *pbFirst==0 || iWrite>0 );
132009   *pp += sqlite3Fts3PutVarint(*pp, iWrite);
132010   *piPrev = iVal;
132011   *pbFirst = 1;
132012 }
132013 
132014 
132015 /*
132016 ** This macro is used by various functions that merge doclists. The two
132017 ** arguments are 64-bit docid values. If the value of the stack variable
132018 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
132019 ** Otherwise, (i2-i1).
132020 **
132021 ** Using this makes it easier to write code that can merge doclists that are
132022 ** sorted in either ascending or descending order.
132023 */
132024 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
132025 
132026 /*
132027 ** This function does an "OR" merge of two doclists (output contains all
132028 ** positions contained in either argument doclist). If the docids in the
132029 ** input doclists are sorted in ascending order, parameter bDescDoclist
132030 ** should be false. If they are sorted in ascending order, it should be
132031 ** passed a non-zero value.
132032 **
132033 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
132034 ** containing the output doclist and SQLITE_OK is returned. In this case
132035 ** *pnOut is set to the number of bytes in the output doclist.
132036 **
132037 ** If an error occurs, an SQLite error code is returned. The output values
132038 ** are undefined in this case.
132039 */
132040 static int fts3DoclistOrMerge(
132041   int bDescDoclist,               /* True if arguments are desc */
132042   char *a1, int n1,               /* First doclist */
132043   char *a2, int n2,               /* Second doclist */
132044   char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
132045 ){
132046   sqlite3_int64 i1 = 0;
132047   sqlite3_int64 i2 = 0;
132048   sqlite3_int64 iPrev = 0;
132049   char *pEnd1 = &a1[n1];
132050   char *pEnd2 = &a2[n2];
132051   char *p1 = a1;
132052   char *p2 = a2;
132053   char *p;
132054   char *aOut;
132055   int bFirstOut = 0;
132056 
132057   *paOut = 0;
132058   *pnOut = 0;
132059 
132060   /* Allocate space for the output. Both the input and output doclists
132061   ** are delta encoded. If they are in ascending order (bDescDoclist==0),
132062   ** then the first docid in each list is simply encoded as a varint. For
132063   ** each subsequent docid, the varint stored is the difference between the
132064   ** current and previous docid (a positive number - since the list is in
132065   ** ascending order).
132066   **
132067   ** The first docid written to the output is therefore encoded using the
132068   ** same number of bytes as it is in whichever of the input lists it is
132069   ** read from. And each subsequent docid read from the same input list
132070   ** consumes either the same or less bytes as it did in the input (since
132071   ** the difference between it and the previous value in the output must
132072   ** be a positive value less than or equal to the delta value read from
132073   ** the input list). The same argument applies to all but the first docid
132074   ** read from the 'other' list. And to the contents of all position lists
132075   ** that will be copied and merged from the input to the output.
132076   **
132077   ** However, if the first docid copied to the output is a negative number,
132078   ** then the encoding of the first docid from the 'other' input list may
132079   ** be larger in the output than it was in the input (since the delta value
132080   ** may be a larger positive integer than the actual docid).
132081   **
132082   ** The space required to store the output is therefore the sum of the
132083   ** sizes of the two inputs, plus enough space for exactly one of the input
132084   ** docids to grow.
132085   **
132086   ** A symetric argument may be made if the doclists are in descending
132087   ** order.
132088   */
132089   aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
132090   if( !aOut ) return SQLITE_NOMEM;
132091 
132092   p = aOut;
132093   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
132094   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
132095   while( p1 || p2 ){
132096     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
132097 
132098     if( p2 && p1 && iDiff==0 ){
132099       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
132100       fts3PoslistMerge(&p, &p1, &p2);
132101       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
132102       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
132103     }else if( !p2 || (p1 && iDiff<0) ){
132104       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
132105       fts3PoslistCopy(&p, &p1);
132106       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
132107     }else{
132108       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
132109       fts3PoslistCopy(&p, &p2);
132110       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
132111     }
132112   }
132113 
132114   *paOut = aOut;
132115   *pnOut = (int)(p-aOut);
132116   assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
132117   return SQLITE_OK;
132118 }
132119 
132120 /*
132121 ** This function does a "phrase" merge of two doclists. In a phrase merge,
132122 ** the output contains a copy of each position from the right-hand input
132123 ** doclist for which there is a position in the left-hand input doclist
132124 ** exactly nDist tokens before it.
132125 **
132126 ** If the docids in the input doclists are sorted in ascending order,
132127 ** parameter bDescDoclist should be false. If they are sorted in ascending
132128 ** order, it should be passed a non-zero value.
132129 **
132130 ** The right-hand input doclist is overwritten by this function.
132131 */
132132 static void fts3DoclistPhraseMerge(
132133   int bDescDoclist,               /* True if arguments are desc */
132134   int nDist,                      /* Distance from left to right (1=adjacent) */
132135   char *aLeft, int nLeft,         /* Left doclist */
132136   char *aRight, int *pnRight      /* IN/OUT: Right/output doclist */
132137 ){
132138   sqlite3_int64 i1 = 0;
132139   sqlite3_int64 i2 = 0;
132140   sqlite3_int64 iPrev = 0;
132141   char *pEnd1 = &aLeft[nLeft];
132142   char *pEnd2 = &aRight[*pnRight];
132143   char *p1 = aLeft;
132144   char *p2 = aRight;
132145   char *p;
132146   int bFirstOut = 0;
132147   char *aOut = aRight;
132148 
132149   assert( nDist>0 );
132150 
132151   p = aOut;
132152   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
132153   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
132154 
132155   while( p1 && p2 ){
132156     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
132157     if( iDiff==0 ){
132158       char *pSave = p;
132159       sqlite3_int64 iPrevSave = iPrev;
132160       int bFirstOutSave = bFirstOut;
132161 
132162       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
132163       if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
132164         p = pSave;
132165         iPrev = iPrevSave;
132166         bFirstOut = bFirstOutSave;
132167       }
132168       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
132169       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
132170     }else if( iDiff<0 ){
132171       fts3PoslistCopy(0, &p1);
132172       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
132173     }else{
132174       fts3PoslistCopy(0, &p2);
132175       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
132176     }
132177   }
132178 
132179   *pnRight = (int)(p - aOut);
132180 }
132181 
132182 /*
132183 ** Argument pList points to a position list nList bytes in size. This
132184 ** function checks to see if the position list contains any entries for
132185 ** a token in position 0 (of any column). If so, it writes argument iDelta
132186 ** to the output buffer pOut, followed by a position list consisting only
132187 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
132188 ** The value returned is the number of bytes written to pOut (if any).
132189 */
132190 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
132191   sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
132192   char *pList,                    /* Position list (no 0x00 term) */
132193   int nList,                      /* Size of pList in bytes */
132194   char *pOut                      /* Write output here */
132195 ){
132196   int nOut = 0;
132197   int bWritten = 0;               /* True once iDelta has been written */
132198   char *p = pList;
132199   char *pEnd = &pList[nList];
132200 
132201   if( *p!=0x01 ){
132202     if( *p==0x02 ){
132203       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
132204       pOut[nOut++] = 0x02;
132205       bWritten = 1;
132206     }
132207     fts3ColumnlistCopy(0, &p);
132208   }
132209 
132210   while( p<pEnd && *p==0x01 ){
132211     sqlite3_int64 iCol;
132212     p++;
132213     p += sqlite3Fts3GetVarint(p, &iCol);
132214     if( *p==0x02 ){
132215       if( bWritten==0 ){
132216         nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
132217         bWritten = 1;
132218       }
132219       pOut[nOut++] = 0x01;
132220       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
132221       pOut[nOut++] = 0x02;
132222     }
132223     fts3ColumnlistCopy(0, &p);
132224   }
132225   if( bWritten ){
132226     pOut[nOut++] = 0x00;
132227   }
132228 
132229   return nOut;
132230 }
132231 
132232 
132233 /*
132234 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
132235 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
132236 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
132237 **
132238 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
132239 ** the responsibility of the caller to free any doclists left in the
132240 ** TermSelect.aaOutput[] array.
132241 */
132242 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
132243   char *aOut = 0;
132244   int nOut = 0;
132245   int i;
132246 
132247   /* Loop through the doclists in the aaOutput[] array. Merge them all
132248   ** into a single doclist.
132249   */
132250   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
132251     if( pTS->aaOutput[i] ){
132252       if( !aOut ){
132253         aOut = pTS->aaOutput[i];
132254         nOut = pTS->anOutput[i];
132255         pTS->aaOutput[i] = 0;
132256       }else{
132257         int nNew;
132258         char *aNew;
132259 
132260         int rc = fts3DoclistOrMerge(p->bDescIdx,
132261             pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
132262         );
132263         if( rc!=SQLITE_OK ){
132264           sqlite3_free(aOut);
132265           return rc;
132266         }
132267 
132268         sqlite3_free(pTS->aaOutput[i]);
132269         sqlite3_free(aOut);
132270         pTS->aaOutput[i] = 0;
132271         aOut = aNew;
132272         nOut = nNew;
132273       }
132274     }
132275   }
132276 
132277   pTS->aaOutput[0] = aOut;
132278   pTS->anOutput[0] = nOut;
132279   return SQLITE_OK;
132280 }
132281 
132282 /*
132283 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
132284 ** as the first argument. The merge is an "OR" merge (see function
132285 ** fts3DoclistOrMerge() for details).
132286 **
132287 ** This function is called with the doclist for each term that matches
132288 ** a queried prefix. It merges all these doclists into one, the doclist
132289 ** for the specified prefix. Since there can be a very large number of
132290 ** doclists to merge, the merging is done pair-wise using the TermSelect
132291 ** object.
132292 **
132293 ** This function returns SQLITE_OK if the merge is successful, or an
132294 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
132295 */
132296 static int fts3TermSelectMerge(
132297   Fts3Table *p,                   /* FTS table handle */
132298   TermSelect *pTS,                /* TermSelect object to merge into */
132299   char *aDoclist,                 /* Pointer to doclist */
132300   int nDoclist                    /* Size of aDoclist in bytes */
132301 ){
132302   if( pTS->aaOutput[0]==0 ){
132303     /* If this is the first term selected, copy the doclist to the output
132304     ** buffer using memcpy(). */
132305     pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
132306     pTS->anOutput[0] = nDoclist;
132307     if( pTS->aaOutput[0] ){
132308       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
132309     }else{
132310       return SQLITE_NOMEM;
132311     }
132312   }else{
132313     char *aMerge = aDoclist;
132314     int nMerge = nDoclist;
132315     int iOut;
132316 
132317     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
132318       if( pTS->aaOutput[iOut]==0 ){
132319         assert( iOut>0 );
132320         pTS->aaOutput[iOut] = aMerge;
132321         pTS->anOutput[iOut] = nMerge;
132322         break;
132323       }else{
132324         char *aNew;
132325         int nNew;
132326 
132327         int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
132328             pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
132329         );
132330         if( rc!=SQLITE_OK ){
132331           if( aMerge!=aDoclist ) sqlite3_free(aMerge);
132332           return rc;
132333         }
132334 
132335         if( aMerge!=aDoclist ) sqlite3_free(aMerge);
132336         sqlite3_free(pTS->aaOutput[iOut]);
132337         pTS->aaOutput[iOut] = 0;
132338 
132339         aMerge = aNew;
132340         nMerge = nNew;
132341         if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
132342           pTS->aaOutput[iOut] = aMerge;
132343           pTS->anOutput[iOut] = nMerge;
132344         }
132345       }
132346     }
132347   }
132348   return SQLITE_OK;
132349 }
132350 
132351 /*
132352 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
132353 */
132354 static int fts3SegReaderCursorAppend(
132355   Fts3MultiSegReader *pCsr,
132356   Fts3SegReader *pNew
132357 ){
132358   if( (pCsr->nSegment%16)==0 ){
132359     Fts3SegReader **apNew;
132360     int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
132361     apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
132362     if( !apNew ){
132363       sqlite3Fts3SegReaderFree(pNew);
132364       return SQLITE_NOMEM;
132365     }
132366     pCsr->apSegment = apNew;
132367   }
132368   pCsr->apSegment[pCsr->nSegment++] = pNew;
132369   return SQLITE_OK;
132370 }
132371 
132372 /*
132373 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
132374 ** 8th argument.
132375 **
132376 ** This function returns SQLITE_OK if successful, or an SQLite error code
132377 ** otherwise.
132378 */
132379 static int fts3SegReaderCursor(
132380   Fts3Table *p,                   /* FTS3 table handle */
132381   int iLangid,                    /* Language id */
132382   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
132383   int iLevel,                     /* Level of segments to scan */
132384   const char *zTerm,              /* Term to query for */
132385   int nTerm,                      /* Size of zTerm in bytes */
132386   int isPrefix,                   /* True for a prefix search */
132387   int isScan,                     /* True to scan from zTerm to EOF */
132388   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
132389 ){
132390   int rc = SQLITE_OK;             /* Error code */
132391   sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
132392   int rc2;                        /* Result of sqlite3_reset() */
132393 
132394   /* If iLevel is less than 0 and this is not a scan, include a seg-reader
132395   ** for the pending-terms. If this is a scan, then this call must be being
132396   ** made by an fts4aux module, not an FTS table. In this case calling
132397   ** Fts3SegReaderPending might segfault, as the data structures used by
132398   ** fts4aux are not completely populated. So it's easiest to filter these
132399   ** calls out here.  */
132400   if( iLevel<0 && p->aIndex ){
132401     Fts3SegReader *pSeg = 0;
132402     rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
132403     if( rc==SQLITE_OK && pSeg ){
132404       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
132405     }
132406   }
132407 
132408   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
132409     if( rc==SQLITE_OK ){
132410       rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
132411     }
132412 
132413     while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
132414       Fts3SegReader *pSeg = 0;
132415 
132416       /* Read the values returned by the SELECT into local variables. */
132417       sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
132418       sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
132419       sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
132420       int nRoot = sqlite3_column_bytes(pStmt, 4);
132421       char const *zRoot = sqlite3_column_blob(pStmt, 4);
132422 
132423       /* If zTerm is not NULL, and this segment is not stored entirely on its
132424       ** root node, the range of leaves scanned can be reduced. Do this. */
132425       if( iStartBlock && zTerm ){
132426         sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
132427         rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
132428         if( rc!=SQLITE_OK ) goto finished;
132429         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
132430       }
132431 
132432       rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
132433           (isPrefix==0 && isScan==0),
132434           iStartBlock, iLeavesEndBlock,
132435           iEndBlock, zRoot, nRoot, &pSeg
132436       );
132437       if( rc!=SQLITE_OK ) goto finished;
132438       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
132439     }
132440   }
132441 
132442  finished:
132443   rc2 = sqlite3_reset(pStmt);
132444   if( rc==SQLITE_DONE ) rc = rc2;
132445 
132446   return rc;
132447 }
132448 
132449 /*
132450 ** Set up a cursor object for iterating through a full-text index or a
132451 ** single level therein.
132452 */
132453 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
132454   Fts3Table *p,                   /* FTS3 table handle */
132455   int iLangid,                    /* Language-id to search */
132456   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
132457   int iLevel,                     /* Level of segments to scan */
132458   const char *zTerm,              /* Term to query for */
132459   int nTerm,                      /* Size of zTerm in bytes */
132460   int isPrefix,                   /* True for a prefix search */
132461   int isScan,                     /* True to scan from zTerm to EOF */
132462   Fts3MultiSegReader *pCsr       /* Cursor object to populate */
132463 ){
132464   assert( iIndex>=0 && iIndex<p->nIndex );
132465   assert( iLevel==FTS3_SEGCURSOR_ALL
132466       ||  iLevel==FTS3_SEGCURSOR_PENDING
132467       ||  iLevel>=0
132468   );
132469   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
132470   assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
132471   assert( isPrefix==0 || isScan==0 );
132472 
132473   memset(pCsr, 0, sizeof(Fts3MultiSegReader));
132474   return fts3SegReaderCursor(
132475       p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
132476   );
132477 }
132478 
132479 /*
132480 ** In addition to its current configuration, have the Fts3MultiSegReader
132481 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
132482 **
132483 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
132484 */
132485 static int fts3SegReaderCursorAddZero(
132486   Fts3Table *p,                   /* FTS virtual table handle */
132487   int iLangid,
132488   const char *zTerm,              /* Term to scan doclist of */
132489   int nTerm,                      /* Number of bytes in zTerm */
132490   Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
132491 ){
132492   return fts3SegReaderCursor(p,
132493       iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
132494   );
132495 }
132496 
132497 /*
132498 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
132499 ** if isPrefix is true, to scan the doclist for all terms for which
132500 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
132501 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
132502 ** an SQLite error code.
132503 **
132504 ** It is the responsibility of the caller to free this object by eventually
132505 ** passing it to fts3SegReaderCursorFree()
132506 **
132507 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
132508 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
132509 */
132510 static int fts3TermSegReaderCursor(
132511   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
132512   const char *zTerm,              /* Term to query for */
132513   int nTerm,                      /* Size of zTerm in bytes */
132514   int isPrefix,                   /* True for a prefix search */
132515   Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
132516 ){
132517   Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
132518   int rc = SQLITE_NOMEM;          /* Return code */
132519 
132520   pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
132521   if( pSegcsr ){
132522     int i;
132523     int bFound = 0;               /* True once an index has been found */
132524     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
132525 
132526     if( isPrefix ){
132527       for(i=1; bFound==0 && i<p->nIndex; i++){
132528         if( p->aIndex[i].nPrefix==nTerm ){
132529           bFound = 1;
132530           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
132531               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
132532           );
132533           pSegcsr->bLookup = 1;
132534         }
132535       }
132536 
132537       for(i=1; bFound==0 && i<p->nIndex; i++){
132538         if( p->aIndex[i].nPrefix==nTerm+1 ){
132539           bFound = 1;
132540           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
132541               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
132542           );
132543           if( rc==SQLITE_OK ){
132544             rc = fts3SegReaderCursorAddZero(
132545                 p, pCsr->iLangid, zTerm, nTerm, pSegcsr
132546             );
132547           }
132548         }
132549       }
132550     }
132551 
132552     if( bFound==0 ){
132553       rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
132554           0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
132555       );
132556       pSegcsr->bLookup = !isPrefix;
132557     }
132558   }
132559 
132560   *ppSegcsr = pSegcsr;
132561   return rc;
132562 }
132563 
132564 /*
132565 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
132566 */
132567 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
132568   sqlite3Fts3SegReaderFinish(pSegcsr);
132569   sqlite3_free(pSegcsr);
132570 }
132571 
132572 /*
132573 ** This function retrieves the doclist for the specified term (or term
132574 ** prefix) from the database.
132575 */
132576 static int fts3TermSelect(
132577   Fts3Table *p,                   /* Virtual table handle */
132578   Fts3PhraseToken *pTok,          /* Token to query for */
132579   int iColumn,                    /* Column to query (or -ve for all columns) */
132580   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
132581   char **ppOut                    /* OUT: Malloced result buffer */
132582 ){
132583   int rc;                         /* Return code */
132584   Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
132585   TermSelect tsc;                 /* Object for pair-wise doclist merging */
132586   Fts3SegFilter filter;           /* Segment term filter configuration */
132587 
132588   pSegcsr = pTok->pSegcsr;
132589   memset(&tsc, 0, sizeof(TermSelect));
132590 
132591   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
132592         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
132593         | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
132594         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
132595   filter.iCol = iColumn;
132596   filter.zTerm = pTok->z;
132597   filter.nTerm = pTok->n;
132598 
132599   rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
132600   while( SQLITE_OK==rc
132601       && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
132602   ){
132603     rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
132604   }
132605 
132606   if( rc==SQLITE_OK ){
132607     rc = fts3TermSelectFinishMerge(p, &tsc);
132608   }
132609   if( rc==SQLITE_OK ){
132610     *ppOut = tsc.aaOutput[0];
132611     *pnOut = tsc.anOutput[0];
132612   }else{
132613     int i;
132614     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
132615       sqlite3_free(tsc.aaOutput[i]);
132616     }
132617   }
132618 
132619   fts3SegReaderCursorFree(pSegcsr);
132620   pTok->pSegcsr = 0;
132621   return rc;
132622 }
132623 
132624 /*
132625 ** This function counts the total number of docids in the doclist stored
132626 ** in buffer aList[], size nList bytes.
132627 **
132628 ** If the isPoslist argument is true, then it is assumed that the doclist
132629 ** contains a position-list following each docid. Otherwise, it is assumed
132630 ** that the doclist is simply a list of docids stored as delta encoded
132631 ** varints.
132632 */
132633 static int fts3DoclistCountDocids(char *aList, int nList){
132634   int nDoc = 0;                   /* Return value */
132635   if( aList ){
132636     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
132637     char *p = aList;              /* Cursor */
132638     while( p<aEnd ){
132639       nDoc++;
132640       while( (*p++)&0x80 );     /* Skip docid varint */
132641       fts3PoslistCopy(0, &p);   /* Skip over position list */
132642     }
132643   }
132644 
132645   return nDoc;
132646 }
132647 
132648 /*
132649 ** Advance the cursor to the next row in the %_content table that
132650 ** matches the search criteria.  For a MATCH search, this will be
132651 ** the next row that matches. For a full-table scan, this will be
132652 ** simply the next row in the %_content table.  For a docid lookup,
132653 ** this routine simply sets the EOF flag.
132654 **
132655 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
132656 ** even if we reach end-of-file.  The fts3EofMethod() will be called
132657 ** subsequently to determine whether or not an EOF was hit.
132658 */
132659 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
132660   int rc;
132661   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
132662   if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
132663     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
132664       pCsr->isEof = 1;
132665       rc = sqlite3_reset(pCsr->pStmt);
132666     }else{
132667       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
132668       rc = SQLITE_OK;
132669     }
132670   }else{
132671     rc = fts3EvalNext((Fts3Cursor *)pCursor);
132672   }
132673   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
132674   return rc;
132675 }
132676 
132677 /*
132678 ** The following are copied from sqliteInt.h.
132679 **
132680 ** Constants for the largest and smallest possible 64-bit signed integers.
132681 ** These macros are designed to work correctly on both 32-bit and 64-bit
132682 ** compilers.
132683 */
132684 #ifndef SQLITE_AMALGAMATION
132685 # define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
132686 # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
132687 #endif
132688 
132689 /*
132690 ** If the numeric type of argument pVal is "integer", then return it
132691 ** converted to a 64-bit signed integer. Otherwise, return a copy of
132692 ** the second parameter, iDefault.
132693 */
132694 static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
132695   if( pVal ){
132696     int eType = sqlite3_value_numeric_type(pVal);
132697     if( eType==SQLITE_INTEGER ){
132698       return sqlite3_value_int64(pVal);
132699     }
132700   }
132701   return iDefault;
132702 }
132703 
132704 /*
132705 ** This is the xFilter interface for the virtual table.  See
132706 ** the virtual table xFilter method documentation for additional
132707 ** information.
132708 **
132709 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
132710 ** the %_content table.
132711 **
132712 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
132713 ** in the %_content table.
132714 **
132715 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
132716 ** column on the left-hand side of the MATCH operator is column
132717 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
132718 ** side of the MATCH operator.
132719 */
132720 static int fts3FilterMethod(
132721   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
132722   int idxNum,                     /* Strategy index */
132723   const char *idxStr,             /* Unused */
132724   int nVal,                       /* Number of elements in apVal */
132725   sqlite3_value **apVal           /* Arguments for the indexing scheme */
132726 ){
132727   int rc;
132728   char *zSql;                     /* SQL statement used to access %_content */
132729   int eSearch;
132730   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
132731   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
132732 
132733   sqlite3_value *pCons = 0;       /* The MATCH or rowid constraint, if any */
132734   sqlite3_value *pLangid = 0;     /* The "langid = ?" constraint, if any */
132735   sqlite3_value *pDocidGe = 0;    /* The "docid >= ?" constraint, if any */
132736   sqlite3_value *pDocidLe = 0;    /* The "docid <= ?" constraint, if any */
132737   int iIdx;
132738 
132739   UNUSED_PARAMETER(idxStr);
132740   UNUSED_PARAMETER(nVal);
132741 
132742   eSearch = (idxNum & 0x0000FFFF);
132743   assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
132744   assert( p->pSegments==0 );
132745 
132746   /* Collect arguments into local variables */
132747   iIdx = 0;
132748   if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
132749   if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
132750   if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
132751   if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
132752   assert( iIdx==nVal );
132753 
132754   /* In case the cursor has been used before, clear it now. */
132755   sqlite3_finalize(pCsr->pStmt);
132756   sqlite3_free(pCsr->aDoclist);
132757   sqlite3_free(pCsr->aMatchinfo);
132758   sqlite3Fts3ExprFree(pCsr->pExpr);
132759   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
132760 
132761   /* Set the lower and upper bounds on docids to return */
132762   pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
132763   pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
132764 
132765   if( idxStr ){
132766     pCsr->bDesc = (idxStr[0]=='D');
132767   }else{
132768     pCsr->bDesc = p->bDescIdx;
132769   }
132770   pCsr->eSearch = (i16)eSearch;
132771 
132772   if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
132773     int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
132774     const char *zQuery = (const char *)sqlite3_value_text(pCons);
132775 
132776     if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
132777       return SQLITE_NOMEM;
132778     }
132779 
132780     pCsr->iLangid = 0;
132781     if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
132782 
132783     assert( p->base.zErrMsg==0 );
132784     rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
132785         p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
132786         &p->base.zErrMsg
132787     );
132788     if( rc!=SQLITE_OK ){
132789       return rc;
132790     }
132791 
132792     rc = fts3EvalStart(pCsr);
132793     sqlite3Fts3SegmentsClose(p);
132794     if( rc!=SQLITE_OK ) return rc;
132795     pCsr->pNextId = pCsr->aDoclist;
132796     pCsr->iPrevId = 0;
132797   }
132798 
132799   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
132800   ** statement loops through all rows of the %_content table. For a
132801   ** full-text query or docid lookup, the statement retrieves a single
132802   ** row by docid.
132803   */
132804   if( eSearch==FTS3_FULLSCAN_SEARCH ){
132805     zSql = sqlite3_mprintf(
132806         "SELECT %s ORDER BY rowid %s",
132807         p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
132808     );
132809     if( zSql ){
132810       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
132811       sqlite3_free(zSql);
132812     }else{
132813       rc = SQLITE_NOMEM;
132814     }
132815   }else if( eSearch==FTS3_DOCID_SEARCH ){
132816     rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
132817     if( rc==SQLITE_OK ){
132818       rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
132819     }
132820   }
132821   if( rc!=SQLITE_OK ) return rc;
132822 
132823   return fts3NextMethod(pCursor);
132824 }
132825 
132826 /*
132827 ** This is the xEof method of the virtual table. SQLite calls this
132828 ** routine to find out if it has reached the end of a result set.
132829 */
132830 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
132831   return ((Fts3Cursor *)pCursor)->isEof;
132832 }
132833 
132834 /*
132835 ** This is the xRowid method. The SQLite core calls this routine to
132836 ** retrieve the rowid for the current row of the result set. fts3
132837 ** exposes %_content.docid as the rowid for the virtual table. The
132838 ** rowid should be written to *pRowid.
132839 */
132840 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
132841   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
132842   *pRowid = pCsr->iPrevId;
132843   return SQLITE_OK;
132844 }
132845 
132846 /*
132847 ** This is the xColumn method, called by SQLite to request a value from
132848 ** the row that the supplied cursor currently points to.
132849 **
132850 ** If:
132851 **
132852 **   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
132853 **   (iCol == p->nColumn)   -> Magic column with the same name as the table.
132854 **   (iCol == p->nColumn+1) -> Docid column
132855 **   (iCol == p->nColumn+2) -> Langid column
132856 */
132857 static int fts3ColumnMethod(
132858   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
132859   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
132860   int iCol                        /* Index of column to read value from */
132861 ){
132862   int rc = SQLITE_OK;             /* Return Code */
132863   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
132864   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
132865 
132866   /* The column value supplied by SQLite must be in range. */
132867   assert( iCol>=0 && iCol<=p->nColumn+2 );
132868 
132869   if( iCol==p->nColumn+1 ){
132870     /* This call is a request for the "docid" column. Since "docid" is an
132871     ** alias for "rowid", use the xRowid() method to obtain the value.
132872     */
132873     sqlite3_result_int64(pCtx, pCsr->iPrevId);
132874   }else if( iCol==p->nColumn ){
132875     /* The extra column whose name is the same as the table.
132876     ** Return a blob which is a pointer to the cursor.  */
132877     sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
132878   }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
132879     sqlite3_result_int64(pCtx, pCsr->iLangid);
132880   }else{
132881     /* The requested column is either a user column (one that contains
132882     ** indexed data), or the language-id column.  */
132883     rc = fts3CursorSeek(0, pCsr);
132884 
132885     if( rc==SQLITE_OK ){
132886       if( iCol==p->nColumn+2 ){
132887         int iLangid = 0;
132888         if( p->zLanguageid ){
132889           iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
132890         }
132891         sqlite3_result_int(pCtx, iLangid);
132892       }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
132893         sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
132894       }
132895     }
132896   }
132897 
132898   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
132899   return rc;
132900 }
132901 
132902 /*
132903 ** This function is the implementation of the xUpdate callback used by
132904 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
132905 ** inserted, updated or deleted.
132906 */
132907 static int fts3UpdateMethod(
132908   sqlite3_vtab *pVtab,            /* Virtual table handle */
132909   int nArg,                       /* Size of argument array */
132910   sqlite3_value **apVal,          /* Array of arguments */
132911   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
132912 ){
132913   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
132914 }
132915 
132916 /*
132917 ** Implementation of xSync() method. Flush the contents of the pending-terms
132918 ** hash-table to the database.
132919 */
132920 static int fts3SyncMethod(sqlite3_vtab *pVtab){
132921 
132922   /* Following an incremental-merge operation, assuming that the input
132923   ** segments are not completely consumed (the usual case), they are updated
132924   ** in place to remove the entries that have already been merged. This
132925   ** involves updating the leaf block that contains the smallest unmerged
132926   ** entry and each block (if any) between the leaf and the root node. So
132927   ** if the height of the input segment b-trees is N, and input segments
132928   ** are merged eight at a time, updating the input segments at the end
132929   ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
132930   ** small - often between 0 and 2. So the overhead of the incremental
132931   ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
132932   ** dwarfing the actual productive work accomplished, the incremental merge
132933   ** is only attempted if it will write at least 64 leaf blocks. Hence
132934   ** nMinMerge.
132935   **
132936   ** Of course, updating the input segments also involves deleting a bunch
132937   ** of blocks from the segments table. But this is not considered overhead
132938   ** as it would also be required by a crisis-merge that used the same input
132939   ** segments.
132940   */
132941   const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
132942 
132943   Fts3Table *p = (Fts3Table*)pVtab;
132944   int rc = sqlite3Fts3PendingTermsFlush(p);
132945 
132946   if( rc==SQLITE_OK
132947    && p->nLeafAdd>(nMinMerge/16)
132948    && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
132949   ){
132950     int mxLevel = 0;              /* Maximum relative level value in db */
132951     int A;                        /* Incr-merge parameter A */
132952 
132953     rc = sqlite3Fts3MaxLevel(p, &mxLevel);
132954     assert( rc==SQLITE_OK || mxLevel==0 );
132955     A = p->nLeafAdd * mxLevel;
132956     A += (A/2);
132957     if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
132958   }
132959   sqlite3Fts3SegmentsClose(p);
132960   return rc;
132961 }
132962 
132963 /*
132964 ** If it is currently unknown whether or not the FTS table has an %_stat
132965 ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
132966 ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
132967 ** if an error occurs.
132968 */
132969 static int fts3SetHasStat(Fts3Table *p){
132970   int rc = SQLITE_OK;
132971   if( p->bHasStat==2 ){
132972     const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
132973     char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
132974     if( zSql ){
132975       sqlite3_stmt *pStmt = 0;
132976       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
132977       if( rc==SQLITE_OK ){
132978         int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
132979         rc = sqlite3_finalize(pStmt);
132980         if( rc==SQLITE_OK ) p->bHasStat = bHasStat;
132981       }
132982       sqlite3_free(zSql);
132983     }else{
132984       rc = SQLITE_NOMEM;
132985     }
132986   }
132987   return rc;
132988 }
132989 
132990 /*
132991 ** Implementation of xBegin() method.
132992 */
132993 static int fts3BeginMethod(sqlite3_vtab *pVtab){
132994   Fts3Table *p = (Fts3Table*)pVtab;
132995   UNUSED_PARAMETER(pVtab);
132996   assert( p->pSegments==0 );
132997   assert( p->nPendingData==0 );
132998   assert( p->inTransaction!=1 );
132999   TESTONLY( p->inTransaction = 1 );
133000   TESTONLY( p->mxSavepoint = -1; );
133001   p->nLeafAdd = 0;
133002   return fts3SetHasStat(p);
133003 }
133004 
133005 /*
133006 ** Implementation of xCommit() method. This is a no-op. The contents of
133007 ** the pending-terms hash-table have already been flushed into the database
133008 ** by fts3SyncMethod().
133009 */
133010 static int fts3CommitMethod(sqlite3_vtab *pVtab){
133011   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
133012   UNUSED_PARAMETER(pVtab);
133013   assert( p->nPendingData==0 );
133014   assert( p->inTransaction!=0 );
133015   assert( p->pSegments==0 );
133016   TESTONLY( p->inTransaction = 0 );
133017   TESTONLY( p->mxSavepoint = -1; );
133018   return SQLITE_OK;
133019 }
133020 
133021 /*
133022 ** Implementation of xRollback(). Discard the contents of the pending-terms
133023 ** hash-table. Any changes made to the database are reverted by SQLite.
133024 */
133025 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
133026   Fts3Table *p = (Fts3Table*)pVtab;
133027   sqlite3Fts3PendingTermsClear(p);
133028   assert( p->inTransaction!=0 );
133029   TESTONLY( p->inTransaction = 0 );
133030   TESTONLY( p->mxSavepoint = -1; );
133031   return SQLITE_OK;
133032 }
133033 
133034 /*
133035 ** When called, *ppPoslist must point to the byte immediately following the
133036 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
133037 ** moves *ppPoslist so that it instead points to the first byte of the
133038 ** same position list.
133039 */
133040 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
133041   char *p = &(*ppPoslist)[-2];
133042   char c = 0;
133043 
133044   while( p>pStart && (c=*p--)==0 );
133045   while( p>pStart && (*p & 0x80) | c ){
133046     c = *p--;
133047   }
133048   if( p>pStart ){ p = &p[2]; }
133049   while( *p++&0x80 );
133050   *ppPoslist = p;
133051 }
133052 
133053 /*
133054 ** Helper function used by the implementation of the overloaded snippet(),
133055 ** offsets() and optimize() SQL functions.
133056 **
133057 ** If the value passed as the third argument is a blob of size
133058 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
133059 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
133060 ** message is written to context pContext and SQLITE_ERROR returned. The
133061 ** string passed via zFunc is used as part of the error message.
133062 */
133063 static int fts3FunctionArg(
133064   sqlite3_context *pContext,      /* SQL function call context */
133065   const char *zFunc,              /* Function name */
133066   sqlite3_value *pVal,            /* argv[0] passed to function */
133067   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
133068 ){
133069   Fts3Cursor *pRet;
133070   if( sqlite3_value_type(pVal)!=SQLITE_BLOB
133071    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
133072   ){
133073     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
133074     sqlite3_result_error(pContext, zErr, -1);
133075     sqlite3_free(zErr);
133076     return SQLITE_ERROR;
133077   }
133078   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
133079   *ppCsr = pRet;
133080   return SQLITE_OK;
133081 }
133082 
133083 /*
133084 ** Implementation of the snippet() function for FTS3
133085 */
133086 static void fts3SnippetFunc(
133087   sqlite3_context *pContext,      /* SQLite function call context */
133088   int nVal,                       /* Size of apVal[] array */
133089   sqlite3_value **apVal           /* Array of arguments */
133090 ){
133091   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
133092   const char *zStart = "<b>";
133093   const char *zEnd = "</b>";
133094   const char *zEllipsis = "<b>...</b>";
133095   int iCol = -1;
133096   int nToken = 15;                /* Default number of tokens in snippet */
133097 
133098   /* There must be at least one argument passed to this function (otherwise
133099   ** the non-overloaded version would have been called instead of this one).
133100   */
133101   assert( nVal>=1 );
133102 
133103   if( nVal>6 ){
133104     sqlite3_result_error(pContext,
133105         "wrong number of arguments to function snippet()", -1);
133106     return;
133107   }
133108   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
133109 
133110   switch( nVal ){
133111     case 6: nToken = sqlite3_value_int(apVal[5]);
133112     case 5: iCol = sqlite3_value_int(apVal[4]);
133113     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
133114     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
133115     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
133116   }
133117   if( !zEllipsis || !zEnd || !zStart ){
133118     sqlite3_result_error_nomem(pContext);
133119   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
133120     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
133121   }
133122 }
133123 
133124 /*
133125 ** Implementation of the offsets() function for FTS3
133126 */
133127 static void fts3OffsetsFunc(
133128   sqlite3_context *pContext,      /* SQLite function call context */
133129   int nVal,                       /* Size of argument array */
133130   sqlite3_value **apVal           /* Array of arguments */
133131 ){
133132   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
133133 
133134   UNUSED_PARAMETER(nVal);
133135 
133136   assert( nVal==1 );
133137   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
133138   assert( pCsr );
133139   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
133140     sqlite3Fts3Offsets(pContext, pCsr);
133141   }
133142 }
133143 
133144 /*
133145 ** Implementation of the special optimize() function for FTS3. This
133146 ** function merges all segments in the database to a single segment.
133147 ** Example usage is:
133148 **
133149 **   SELECT optimize(t) FROM t LIMIT 1;
133150 **
133151 ** where 't' is the name of an FTS3 table.
133152 */
133153 static void fts3OptimizeFunc(
133154   sqlite3_context *pContext,      /* SQLite function call context */
133155   int nVal,                       /* Size of argument array */
133156   sqlite3_value **apVal           /* Array of arguments */
133157 ){
133158   int rc;                         /* Return code */
133159   Fts3Table *p;                   /* Virtual table handle */
133160   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
133161 
133162   UNUSED_PARAMETER(nVal);
133163 
133164   assert( nVal==1 );
133165   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
133166   p = (Fts3Table *)pCursor->base.pVtab;
133167   assert( p );
133168 
133169   rc = sqlite3Fts3Optimize(p);
133170 
133171   switch( rc ){
133172     case SQLITE_OK:
133173       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
133174       break;
133175     case SQLITE_DONE:
133176       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
133177       break;
133178     default:
133179       sqlite3_result_error_code(pContext, rc);
133180       break;
133181   }
133182 }
133183 
133184 /*
133185 ** Implementation of the matchinfo() function for FTS3
133186 */
133187 static void fts3MatchinfoFunc(
133188   sqlite3_context *pContext,      /* SQLite function call context */
133189   int nVal,                       /* Size of argument array */
133190   sqlite3_value **apVal           /* Array of arguments */
133191 ){
133192   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
133193   assert( nVal==1 || nVal==2 );
133194   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
133195     const char *zArg = 0;
133196     if( nVal>1 ){
133197       zArg = (const char *)sqlite3_value_text(apVal[1]);
133198     }
133199     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
133200   }
133201 }
133202 
133203 /*
133204 ** This routine implements the xFindFunction method for the FTS3
133205 ** virtual table.
133206 */
133207 static int fts3FindFunctionMethod(
133208   sqlite3_vtab *pVtab,            /* Virtual table handle */
133209   int nArg,                       /* Number of SQL function arguments */
133210   const char *zName,              /* Name of SQL function */
133211   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
133212   void **ppArg                    /* Unused */
133213 ){
133214   struct Overloaded {
133215     const char *zName;
133216     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
133217   } aOverload[] = {
133218     { "snippet", fts3SnippetFunc },
133219     { "offsets", fts3OffsetsFunc },
133220     { "optimize", fts3OptimizeFunc },
133221     { "matchinfo", fts3MatchinfoFunc },
133222   };
133223   int i;                          /* Iterator variable */
133224 
133225   UNUSED_PARAMETER(pVtab);
133226   UNUSED_PARAMETER(nArg);
133227   UNUSED_PARAMETER(ppArg);
133228 
133229   for(i=0; i<SizeofArray(aOverload); i++){
133230     if( strcmp(zName, aOverload[i].zName)==0 ){
133231       *pxFunc = aOverload[i].xFunc;
133232       return 1;
133233     }
133234   }
133235 
133236   /* No function of the specified name was found. Return 0. */
133237   return 0;
133238 }
133239 
133240 /*
133241 ** Implementation of FTS3 xRename method. Rename an fts3 table.
133242 */
133243 static int fts3RenameMethod(
133244   sqlite3_vtab *pVtab,            /* Virtual table handle */
133245   const char *zName               /* New name of table */
133246 ){
133247   Fts3Table *p = (Fts3Table *)pVtab;
133248   sqlite3 *db = p->db;            /* Database connection */
133249   int rc;                         /* Return Code */
133250 
133251   /* At this point it must be known if the %_stat table exists or not.
133252   ** So bHasStat may not be 2.  */
133253   rc = fts3SetHasStat(p);
133254 
133255   /* As it happens, the pending terms table is always empty here. This is
133256   ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
133257   ** always opens a savepoint transaction. And the xSavepoint() method
133258   ** flushes the pending terms table. But leave the (no-op) call to
133259   ** PendingTermsFlush() in in case that changes.
133260   */
133261   assert( p->nPendingData==0 );
133262   if( rc==SQLITE_OK ){
133263     rc = sqlite3Fts3PendingTermsFlush(p);
133264   }
133265 
133266   if( p->zContentTbl==0 ){
133267     fts3DbExec(&rc, db,
133268       "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
133269       p->zDb, p->zName, zName
133270     );
133271   }
133272 
133273   if( p->bHasDocsize ){
133274     fts3DbExec(&rc, db,
133275       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
133276       p->zDb, p->zName, zName
133277     );
133278   }
133279   if( p->bHasStat ){
133280     fts3DbExec(&rc, db,
133281       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
133282       p->zDb, p->zName, zName
133283     );
133284   }
133285   fts3DbExec(&rc, db,
133286     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
133287     p->zDb, p->zName, zName
133288   );
133289   fts3DbExec(&rc, db,
133290     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
133291     p->zDb, p->zName, zName
133292   );
133293   return rc;
133294 }
133295 
133296 /*
133297 ** The xSavepoint() method.
133298 **
133299 ** Flush the contents of the pending-terms table to disk.
133300 */
133301 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
133302   int rc = SQLITE_OK;
133303   UNUSED_PARAMETER(iSavepoint);
133304   assert( ((Fts3Table *)pVtab)->inTransaction );
133305   assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
133306   TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
133307   if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
133308     rc = fts3SyncMethod(pVtab);
133309   }
133310   return rc;
133311 }
133312 
133313 /*
133314 ** The xRelease() method.
133315 **
133316 ** This is a no-op.
133317 */
133318 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
133319   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
133320   UNUSED_PARAMETER(iSavepoint);
133321   UNUSED_PARAMETER(pVtab);
133322   assert( p->inTransaction );
133323   assert( p->mxSavepoint >= iSavepoint );
133324   TESTONLY( p->mxSavepoint = iSavepoint-1 );
133325   return SQLITE_OK;
133326 }
133327 
133328 /*
133329 ** The xRollbackTo() method.
133330 **
133331 ** Discard the contents of the pending terms table.
133332 */
133333 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
133334   Fts3Table *p = (Fts3Table*)pVtab;
133335   UNUSED_PARAMETER(iSavepoint);
133336   assert( p->inTransaction );
133337   assert( p->mxSavepoint >= iSavepoint );
133338   TESTONLY( p->mxSavepoint = iSavepoint );
133339   sqlite3Fts3PendingTermsClear(p);
133340   return SQLITE_OK;
133341 }
133342 
133343 static const sqlite3_module fts3Module = {
133344   /* iVersion      */ 2,
133345   /* xCreate       */ fts3CreateMethod,
133346   /* xConnect      */ fts3ConnectMethod,
133347   /* xBestIndex    */ fts3BestIndexMethod,
133348   /* xDisconnect   */ fts3DisconnectMethod,
133349   /* xDestroy      */ fts3DestroyMethod,
133350   /* xOpen         */ fts3OpenMethod,
133351   /* xClose        */ fts3CloseMethod,
133352   /* xFilter       */ fts3FilterMethod,
133353   /* xNext         */ fts3NextMethod,
133354   /* xEof          */ fts3EofMethod,
133355   /* xColumn       */ fts3ColumnMethod,
133356   /* xRowid        */ fts3RowidMethod,
133357   /* xUpdate       */ fts3UpdateMethod,
133358   /* xBegin        */ fts3BeginMethod,
133359   /* xSync         */ fts3SyncMethod,
133360   /* xCommit       */ fts3CommitMethod,
133361   /* xRollback     */ fts3RollbackMethod,
133362   /* xFindFunction */ fts3FindFunctionMethod,
133363   /* xRename */       fts3RenameMethod,
133364   /* xSavepoint    */ fts3SavepointMethod,
133365   /* xRelease      */ fts3ReleaseMethod,
133366   /* xRollbackTo   */ fts3RollbackToMethod,
133367 };
133368 
133369 /*
133370 ** This function is registered as the module destructor (called when an
133371 ** FTS3 enabled database connection is closed). It frees the memory
133372 ** allocated for the tokenizer hash table.
133373 */
133374 static void hashDestroy(void *p){
133375   Fts3Hash *pHash = (Fts3Hash *)p;
133376   sqlite3Fts3HashClear(pHash);
133377   sqlite3_free(pHash);
133378 }
133379 
133380 /*
133381 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
133382 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
133383 ** respectively. The following three forward declarations are for functions
133384 ** declared in these files used to retrieve the respective implementations.
133385 **
133386 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
133387 ** to by the argument to point to the "simple" tokenizer implementation.
133388 ** And so on.
133389 */
133390 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
133391 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
133392 #ifndef SQLITE_DISABLE_FTS3_UNICODE
133393 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
133394 #endif
133395 #ifdef SQLITE_ENABLE_ICU
133396 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
133397 #endif
133398 
133399 /*
133400 ** Initialize the fts3 extension. If this extension is built as part
133401 ** of the sqlite library, then this function is called directly by
133402 ** SQLite. If fts3 is built as a dynamically loadable extension, this
133403 ** function is called by the sqlite3_extension_init() entry point.
133404 */
133405 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
133406   int rc = SQLITE_OK;
133407   Fts3Hash *pHash = 0;
133408   const sqlite3_tokenizer_module *pSimple = 0;
133409   const sqlite3_tokenizer_module *pPorter = 0;
133410 #ifndef SQLITE_DISABLE_FTS3_UNICODE
133411   const sqlite3_tokenizer_module *pUnicode = 0;
133412 #endif
133413 
133414 #ifdef SQLITE_ENABLE_ICU
133415   const sqlite3_tokenizer_module *pIcu = 0;
133416   sqlite3Fts3IcuTokenizerModule(&pIcu);
133417 #endif
133418 
133419 #ifndef SQLITE_DISABLE_FTS3_UNICODE
133420   sqlite3Fts3UnicodeTokenizer(&pUnicode);
133421 #endif
133422 
133423 #ifdef SQLITE_TEST
133424   rc = sqlite3Fts3InitTerm(db);
133425   if( rc!=SQLITE_OK ) return rc;
133426 #endif
133427 
133428   rc = sqlite3Fts3InitAux(db);
133429   if( rc!=SQLITE_OK ) return rc;
133430 
133431   sqlite3Fts3SimpleTokenizerModule(&pSimple);
133432   sqlite3Fts3PorterTokenizerModule(&pPorter);
133433 
133434   /* Allocate and initialize the hash-table used to store tokenizers. */
133435   pHash = sqlite3_malloc(sizeof(Fts3Hash));
133436   if( !pHash ){
133437     rc = SQLITE_NOMEM;
133438   }else{
133439     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
133440   }
133441 
133442   /* Load the built-in tokenizers into the hash table */
133443   if( rc==SQLITE_OK ){
133444     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
133445      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
133446 
133447 #ifndef SQLITE_DISABLE_FTS3_UNICODE
133448      || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
133449 #endif
133450 #ifdef SQLITE_ENABLE_ICU
133451      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
133452 #endif
133453     ){
133454       rc = SQLITE_NOMEM;
133455     }
133456   }
133457 
133458 #ifdef SQLITE_TEST
133459   if( rc==SQLITE_OK ){
133460     rc = sqlite3Fts3ExprInitTestInterface(db);
133461   }
133462 #endif
133463 
133464   /* Create the virtual table wrapper around the hash-table and overload
133465   ** the two scalar functions. If this is successful, register the
133466   ** module with sqlite.
133467   */
133468   if( SQLITE_OK==rc
133469    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
133470    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
133471    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
133472    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
133473    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
133474    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
133475   ){
133476     rc = sqlite3_create_module_v2(
133477         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
133478     );
133479     if( rc==SQLITE_OK ){
133480       rc = sqlite3_create_module_v2(
133481           db, "fts4", &fts3Module, (void *)pHash, 0
133482       );
133483     }
133484     if( rc==SQLITE_OK ){
133485       rc = sqlite3Fts3InitTok(db, (void *)pHash);
133486     }
133487     return rc;
133488   }
133489 
133490 
133491   /* An error has occurred. Delete the hash table and return the error code. */
133492   assert( rc!=SQLITE_OK );
133493   if( pHash ){
133494     sqlite3Fts3HashClear(pHash);
133495     sqlite3_free(pHash);
133496   }
133497   return rc;
133498 }
133499 
133500 /*
133501 ** Allocate an Fts3MultiSegReader for each token in the expression headed
133502 ** by pExpr.
133503 **
133504 ** An Fts3SegReader object is a cursor that can seek or scan a range of
133505 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
133506 ** Fts3SegReader objects internally to provide an interface to seek or scan
133507 ** within the union of all segments of a b-tree. Hence the name.
133508 **
133509 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
133510 ** segment b-tree (if the term is not a prefix or it is a prefix for which
133511 ** there exists prefix b-tree of the right length) then it may be traversed
133512 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
133513 ** doclist and then traversed.
133514 */
133515 static void fts3EvalAllocateReaders(
133516   Fts3Cursor *pCsr,               /* FTS cursor handle */
133517   Fts3Expr *pExpr,                /* Allocate readers for this expression */
133518   int *pnToken,                   /* OUT: Total number of tokens in phrase. */
133519   int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
133520   int *pRc                        /* IN/OUT: Error code */
133521 ){
133522   if( pExpr && SQLITE_OK==*pRc ){
133523     if( pExpr->eType==FTSQUERY_PHRASE ){
133524       int i;
133525       int nToken = pExpr->pPhrase->nToken;
133526       *pnToken += nToken;
133527       for(i=0; i<nToken; i++){
133528         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
133529         int rc = fts3TermSegReaderCursor(pCsr,
133530             pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
133531         );
133532         if( rc!=SQLITE_OK ){
133533           *pRc = rc;
133534           return;
133535         }
133536       }
133537       assert( pExpr->pPhrase->iDoclistToken==0 );
133538       pExpr->pPhrase->iDoclistToken = -1;
133539     }else{
133540       *pnOr += (pExpr->eType==FTSQUERY_OR);
133541       fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
133542       fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
133543     }
133544   }
133545 }
133546 
133547 /*
133548 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
133549 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
133550 **
133551 ** This function assumes that pList points to a buffer allocated using
133552 ** sqlite3_malloc(). This function takes responsibility for eventually
133553 ** freeing the buffer.
133554 */
133555 static void fts3EvalPhraseMergeToken(
133556   Fts3Table *pTab,                /* FTS Table pointer */
133557   Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
133558   int iToken,                     /* Token pList/nList corresponds to */
133559   char *pList,                    /* Pointer to doclist */
133560   int nList                       /* Number of bytes in pList */
133561 ){
133562   assert( iToken!=p->iDoclistToken );
133563 
133564   if( pList==0 ){
133565     sqlite3_free(p->doclist.aAll);
133566     p->doclist.aAll = 0;
133567     p->doclist.nAll = 0;
133568   }
133569 
133570   else if( p->iDoclistToken<0 ){
133571     p->doclist.aAll = pList;
133572     p->doclist.nAll = nList;
133573   }
133574 
133575   else if( p->doclist.aAll==0 ){
133576     sqlite3_free(pList);
133577   }
133578 
133579   else {
133580     char *pLeft;
133581     char *pRight;
133582     int nLeft;
133583     int nRight;
133584     int nDiff;
133585 
133586     if( p->iDoclistToken<iToken ){
133587       pLeft = p->doclist.aAll;
133588       nLeft = p->doclist.nAll;
133589       pRight = pList;
133590       nRight = nList;
133591       nDiff = iToken - p->iDoclistToken;
133592     }else{
133593       pRight = p->doclist.aAll;
133594       nRight = p->doclist.nAll;
133595       pLeft = pList;
133596       nLeft = nList;
133597       nDiff = p->iDoclistToken - iToken;
133598     }
133599 
133600     fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
133601     sqlite3_free(pLeft);
133602     p->doclist.aAll = pRight;
133603     p->doclist.nAll = nRight;
133604   }
133605 
133606   if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
133607 }
133608 
133609 /*
133610 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
133611 ** does not take deferred tokens into account.
133612 **
133613 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
133614 */
133615 static int fts3EvalPhraseLoad(
133616   Fts3Cursor *pCsr,               /* FTS Cursor handle */
133617   Fts3Phrase *p                   /* Phrase object */
133618 ){
133619   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
133620   int iToken;
133621   int rc = SQLITE_OK;
133622 
133623   for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
133624     Fts3PhraseToken *pToken = &p->aToken[iToken];
133625     assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
133626 
133627     if( pToken->pSegcsr ){
133628       int nThis = 0;
133629       char *pThis = 0;
133630       rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
133631       if( rc==SQLITE_OK ){
133632         fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
133633       }
133634     }
133635     assert( pToken->pSegcsr==0 );
133636   }
133637 
133638   return rc;
133639 }
133640 
133641 /*
133642 ** This function is called on each phrase after the position lists for
133643 ** any deferred tokens have been loaded into memory. It updates the phrases
133644 ** current position list to include only those positions that are really
133645 ** instances of the phrase (after considering deferred tokens). If this
133646 ** means that the phrase does not appear in the current row, doclist.pList
133647 ** and doclist.nList are both zeroed.
133648 **
133649 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
133650 */
133651 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
133652   int iToken;                     /* Used to iterate through phrase tokens */
133653   char *aPoslist = 0;             /* Position list for deferred tokens */
133654   int nPoslist = 0;               /* Number of bytes in aPoslist */
133655   int iPrev = -1;                 /* Token number of previous deferred token */
133656 
133657   assert( pPhrase->doclist.bFreeList==0 );
133658 
133659   for(iToken=0; iToken<pPhrase->nToken; iToken++){
133660     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
133661     Fts3DeferredToken *pDeferred = pToken->pDeferred;
133662 
133663     if( pDeferred ){
133664       char *pList;
133665       int nList;
133666       int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
133667       if( rc!=SQLITE_OK ) return rc;
133668 
133669       if( pList==0 ){
133670         sqlite3_free(aPoslist);
133671         pPhrase->doclist.pList = 0;
133672         pPhrase->doclist.nList = 0;
133673         return SQLITE_OK;
133674 
133675       }else if( aPoslist==0 ){
133676         aPoslist = pList;
133677         nPoslist = nList;
133678 
133679       }else{
133680         char *aOut = pList;
133681         char *p1 = aPoslist;
133682         char *p2 = aOut;
133683 
133684         assert( iPrev>=0 );
133685         fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
133686         sqlite3_free(aPoslist);
133687         aPoslist = pList;
133688         nPoslist = (int)(aOut - aPoslist);
133689         if( nPoslist==0 ){
133690           sqlite3_free(aPoslist);
133691           pPhrase->doclist.pList = 0;
133692           pPhrase->doclist.nList = 0;
133693           return SQLITE_OK;
133694         }
133695       }
133696       iPrev = iToken;
133697     }
133698   }
133699 
133700   if( iPrev>=0 ){
133701     int nMaxUndeferred = pPhrase->iDoclistToken;
133702     if( nMaxUndeferred<0 ){
133703       pPhrase->doclist.pList = aPoslist;
133704       pPhrase->doclist.nList = nPoslist;
133705       pPhrase->doclist.iDocid = pCsr->iPrevId;
133706       pPhrase->doclist.bFreeList = 1;
133707     }else{
133708       int nDistance;
133709       char *p1;
133710       char *p2;
133711       char *aOut;
133712 
133713       if( nMaxUndeferred>iPrev ){
133714         p1 = aPoslist;
133715         p2 = pPhrase->doclist.pList;
133716         nDistance = nMaxUndeferred - iPrev;
133717       }else{
133718         p1 = pPhrase->doclist.pList;
133719         p2 = aPoslist;
133720         nDistance = iPrev - nMaxUndeferred;
133721       }
133722 
133723       aOut = (char *)sqlite3_malloc(nPoslist+8);
133724       if( !aOut ){
133725         sqlite3_free(aPoslist);
133726         return SQLITE_NOMEM;
133727       }
133728 
133729       pPhrase->doclist.pList = aOut;
133730       if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
133731         pPhrase->doclist.bFreeList = 1;
133732         pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
133733       }else{
133734         sqlite3_free(aOut);
133735         pPhrase->doclist.pList = 0;
133736         pPhrase->doclist.nList = 0;
133737       }
133738       sqlite3_free(aPoslist);
133739     }
133740   }
133741 
133742   return SQLITE_OK;
133743 }
133744 
133745 /*
133746 ** Maximum number of tokens a phrase may have to be considered for the
133747 ** incremental doclists strategy.
133748 */
133749 #define MAX_INCR_PHRASE_TOKENS 4
133750 
133751 /*
133752 ** This function is called for each Fts3Phrase in a full-text query
133753 ** expression to initialize the mechanism for returning rows. Once this
133754 ** function has been called successfully on an Fts3Phrase, it may be
133755 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
133756 **
133757 ** If parameter bOptOk is true, then the phrase may (or may not) use the
133758 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
133759 ** memory within this call.
133760 **
133761 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
133762 */
133763 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
133764   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
133765   int rc = SQLITE_OK;             /* Error code */
133766   int i;
133767 
133768   /* Determine if doclists may be loaded from disk incrementally. This is
133769   ** possible if the bOptOk argument is true, the FTS doclists will be
133770   ** scanned in forward order, and the phrase consists of
133771   ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
133772   ** tokens or prefix tokens that cannot use a prefix-index.  */
133773   int bHaveIncr = 0;
133774   int bIncrOk = (bOptOk
133775    && pCsr->bDesc==pTab->bDescIdx
133776    && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
133777    && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
133778 #ifdef SQLITE_TEST
133779    && pTab->bNoIncrDoclist==0
133780 #endif
133781   );
133782   for(i=0; bIncrOk==1 && i<p->nToken; i++){
133783     Fts3PhraseToken *pToken = &p->aToken[i];
133784     if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
133785       bIncrOk = 0;
133786     }
133787     if( pToken->pSegcsr ) bHaveIncr = 1;
133788   }
133789 
133790   if( bIncrOk && bHaveIncr ){
133791     /* Use the incremental approach. */
133792     int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
133793     for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
133794       Fts3PhraseToken *pToken = &p->aToken[i];
133795       Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
133796       if( pSegcsr ){
133797         rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
133798       }
133799     }
133800     p->bIncr = 1;
133801   }else{
133802     /* Load the full doclist for the phrase into memory. */
133803     rc = fts3EvalPhraseLoad(pCsr, p);
133804     p->bIncr = 0;
133805   }
133806 
133807   assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
133808   return rc;
133809 }
133810 
133811 /*
133812 ** This function is used to iterate backwards (from the end to start)
133813 ** through doclists. It is used by this module to iterate through phrase
133814 ** doclists in reverse and by the fts3_write.c module to iterate through
133815 ** pending-terms lists when writing to databases with "order=desc".
133816 **
133817 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
133818 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
133819 ** function iterates from the end of the doclist to the beginning.
133820 */
133821 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
133822   int bDescIdx,                   /* True if the doclist is desc */
133823   char *aDoclist,                 /* Pointer to entire doclist */
133824   int nDoclist,                   /* Length of aDoclist in bytes */
133825   char **ppIter,                  /* IN/OUT: Iterator pointer */
133826   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
133827   int *pnList,                    /* OUT: List length pointer */
133828   u8 *pbEof                       /* OUT: End-of-file flag */
133829 ){
133830   char *p = *ppIter;
133831 
133832   assert( nDoclist>0 );
133833   assert( *pbEof==0 );
133834   assert( p || *piDocid==0 );
133835   assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
133836 
133837   if( p==0 ){
133838     sqlite3_int64 iDocid = 0;
133839     char *pNext = 0;
133840     char *pDocid = aDoclist;
133841     char *pEnd = &aDoclist[nDoclist];
133842     int iMul = 1;
133843 
133844     while( pDocid<pEnd ){
133845       sqlite3_int64 iDelta;
133846       pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
133847       iDocid += (iMul * iDelta);
133848       pNext = pDocid;
133849       fts3PoslistCopy(0, &pDocid);
133850       while( pDocid<pEnd && *pDocid==0 ) pDocid++;
133851       iMul = (bDescIdx ? -1 : 1);
133852     }
133853 
133854     *pnList = (int)(pEnd - pNext);
133855     *ppIter = pNext;
133856     *piDocid = iDocid;
133857   }else{
133858     int iMul = (bDescIdx ? -1 : 1);
133859     sqlite3_int64 iDelta;
133860     fts3GetReverseVarint(&p, aDoclist, &iDelta);
133861     *piDocid -= (iMul * iDelta);
133862 
133863     if( p==aDoclist ){
133864       *pbEof = 1;
133865     }else{
133866       char *pSave = p;
133867       fts3ReversePoslist(aDoclist, &p);
133868       *pnList = (int)(pSave - p);
133869     }
133870     *ppIter = p;
133871   }
133872 }
133873 
133874 /*
133875 ** Iterate forwards through a doclist.
133876 */
133877 SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
133878   int bDescIdx,                   /* True if the doclist is desc */
133879   char *aDoclist,                 /* Pointer to entire doclist */
133880   int nDoclist,                   /* Length of aDoclist in bytes */
133881   char **ppIter,                  /* IN/OUT: Iterator pointer */
133882   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
133883   u8 *pbEof                       /* OUT: End-of-file flag */
133884 ){
133885   char *p = *ppIter;
133886 
133887   assert( nDoclist>0 );
133888   assert( *pbEof==0 );
133889   assert( p || *piDocid==0 );
133890   assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
133891 
133892   if( p==0 ){
133893     p = aDoclist;
133894     p += sqlite3Fts3GetVarint(p, piDocid);
133895   }else{
133896     fts3PoslistCopy(0, &p);
133897     if( p>=&aDoclist[nDoclist] ){
133898       *pbEof = 1;
133899     }else{
133900       sqlite3_int64 iVar;
133901       p += sqlite3Fts3GetVarint(p, &iVar);
133902       *piDocid += ((bDescIdx ? -1 : 1) * iVar);
133903     }
133904   }
133905 
133906   *ppIter = p;
133907 }
133908 
133909 /*
133910 ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
133911 ** to true if EOF is reached.
133912 */
133913 static void fts3EvalDlPhraseNext(
133914   Fts3Table *pTab,
133915   Fts3Doclist *pDL,
133916   u8 *pbEof
133917 ){
133918   char *pIter;                            /* Used to iterate through aAll */
133919   char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
133920 
133921   if( pDL->pNextDocid ){
133922     pIter = pDL->pNextDocid;
133923   }else{
133924     pIter = pDL->aAll;
133925   }
133926 
133927   if( pIter>=pEnd ){
133928     /* We have already reached the end of this doclist. EOF. */
133929     *pbEof = 1;
133930   }else{
133931     sqlite3_int64 iDelta;
133932     pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
133933     if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
133934       pDL->iDocid += iDelta;
133935     }else{
133936       pDL->iDocid -= iDelta;
133937     }
133938     pDL->pList = pIter;
133939     fts3PoslistCopy(0, &pIter);
133940     pDL->nList = (int)(pIter - pDL->pList);
133941 
133942     /* pIter now points just past the 0x00 that terminates the position-
133943     ** list for document pDL->iDocid. However, if this position-list was
133944     ** edited in place by fts3EvalNearTrim(), then pIter may not actually
133945     ** point to the start of the next docid value. The following line deals
133946     ** with this case by advancing pIter past the zero-padding added by
133947     ** fts3EvalNearTrim().  */
133948     while( pIter<pEnd && *pIter==0 ) pIter++;
133949 
133950     pDL->pNextDocid = pIter;
133951     assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
133952     *pbEof = 0;
133953   }
133954 }
133955 
133956 /*
133957 ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
133958 */
133959 typedef struct TokenDoclist TokenDoclist;
133960 struct TokenDoclist {
133961   int bIgnore;
133962   sqlite3_int64 iDocid;
133963   char *pList;
133964   int nList;
133965 };
133966 
133967 /*
133968 ** Token pToken is an incrementally loaded token that is part of a
133969 ** multi-token phrase. Advance it to the next matching document in the
133970 ** database and populate output variable *p with the details of the new
133971 ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
133972 **
133973 ** If an error occurs, return an SQLite error code. Otherwise, return
133974 ** SQLITE_OK.
133975 */
133976 static int incrPhraseTokenNext(
133977   Fts3Table *pTab,                /* Virtual table handle */
133978   Fts3Phrase *pPhrase,            /* Phrase to advance token of */
133979   int iToken,                     /* Specific token to advance */
133980   TokenDoclist *p,                /* OUT: Docid and doclist for new entry */
133981   u8 *pbEof                       /* OUT: True if iterator is at EOF */
133982 ){
133983   int rc = SQLITE_OK;
133984 
133985   if( pPhrase->iDoclistToken==iToken ){
133986     assert( p->bIgnore==0 );
133987     assert( pPhrase->aToken[iToken].pSegcsr==0 );
133988     fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
133989     p->pList = pPhrase->doclist.pList;
133990     p->nList = pPhrase->doclist.nList;
133991     p->iDocid = pPhrase->doclist.iDocid;
133992   }else{
133993     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
133994     assert( pToken->pDeferred==0 );
133995     assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
133996     if( pToken->pSegcsr ){
133997       assert( p->bIgnore==0 );
133998       rc = sqlite3Fts3MsrIncrNext(
133999           pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
134000       );
134001       if( p->pList==0 ) *pbEof = 1;
134002     }else{
134003       p->bIgnore = 1;
134004     }
134005   }
134006 
134007   return rc;
134008 }
134009 
134010 
134011 /*
134012 ** The phrase iterator passed as the second argument:
134013 **
134014 **   * features at least one token that uses an incremental doclist, and
134015 **
134016 **   * does not contain any deferred tokens.
134017 **
134018 ** Advance it to the next matching documnent in the database and populate
134019 ** the Fts3Doclist.pList and nList fields.
134020 **
134021 ** If there is no "next" entry and no error occurs, then *pbEof is set to
134022 ** 1 before returning. Otherwise, if no error occurs and the iterator is
134023 ** successfully advanced, *pbEof is set to 0.
134024 **
134025 ** If an error occurs, return an SQLite error code. Otherwise, return
134026 ** SQLITE_OK.
134027 */
134028 static int fts3EvalIncrPhraseNext(
134029   Fts3Cursor *pCsr,               /* FTS Cursor handle */
134030   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
134031   u8 *pbEof                       /* OUT: Set to 1 if EOF */
134032 ){
134033   int rc = SQLITE_OK;
134034   Fts3Doclist *pDL = &p->doclist;
134035   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
134036   u8 bEof = 0;
134037 
134038   /* This is only called if it is guaranteed that the phrase has at least
134039   ** one incremental token. In which case the bIncr flag is set. */
134040   assert( p->bIncr==1 );
134041 
134042   if( p->nToken==1 && p->bIncr ){
134043     rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
134044         &pDL->iDocid, &pDL->pList, &pDL->nList
134045     );
134046     if( pDL->pList==0 ) bEof = 1;
134047   }else{
134048     int bDescDoclist = pCsr->bDesc;
134049     struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
134050 
134051     memset(a, 0, sizeof(a));
134052     assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
134053     assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
134054 
134055     while( bEof==0 ){
134056       int bMaxSet = 0;
134057       sqlite3_int64 iMax = 0;     /* Largest docid for all iterators */
134058       int i;                      /* Used to iterate through tokens */
134059 
134060       /* Advance the iterator for each token in the phrase once. */
134061       for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
134062         rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
134063         if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
134064           iMax = a[i].iDocid;
134065           bMaxSet = 1;
134066         }
134067       }
134068       assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
134069       assert( rc!=SQLITE_OK || bMaxSet );
134070 
134071       /* Keep advancing iterators until they all point to the same document */
134072       for(i=0; i<p->nToken; i++){
134073         while( rc==SQLITE_OK && bEof==0
134074             && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
134075         ){
134076           rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
134077           if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
134078             iMax = a[i].iDocid;
134079             i = 0;
134080           }
134081         }
134082       }
134083 
134084       /* Check if the current entries really are a phrase match */
134085       if( bEof==0 ){
134086         int nList = 0;
134087         int nByte = a[p->nToken-1].nList;
134088         char *aDoclist = sqlite3_malloc(nByte+1);
134089         if( !aDoclist ) return SQLITE_NOMEM;
134090         memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
134091 
134092         for(i=0; i<(p->nToken-1); i++){
134093           if( a[i].bIgnore==0 ){
134094             char *pL = a[i].pList;
134095             char *pR = aDoclist;
134096             char *pOut = aDoclist;
134097             int nDist = p->nToken-1-i;
134098             int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
134099             if( res==0 ) break;
134100             nList = (int)(pOut - aDoclist);
134101           }
134102         }
134103         if( i==(p->nToken-1) ){
134104           pDL->iDocid = iMax;
134105           pDL->pList = aDoclist;
134106           pDL->nList = nList;
134107           pDL->bFreeList = 1;
134108           break;
134109         }
134110         sqlite3_free(aDoclist);
134111       }
134112     }
134113   }
134114 
134115   *pbEof = bEof;
134116   return rc;
134117 }
134118 
134119 /*
134120 ** Attempt to move the phrase iterator to point to the next matching docid.
134121 ** If an error occurs, return an SQLite error code. Otherwise, return
134122 ** SQLITE_OK.
134123 **
134124 ** If there is no "next" entry and no error occurs, then *pbEof is set to
134125 ** 1 before returning. Otherwise, if no error occurs and the iterator is
134126 ** successfully advanced, *pbEof is set to 0.
134127 */
134128 static int fts3EvalPhraseNext(
134129   Fts3Cursor *pCsr,               /* FTS Cursor handle */
134130   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
134131   u8 *pbEof                       /* OUT: Set to 1 if EOF */
134132 ){
134133   int rc = SQLITE_OK;
134134   Fts3Doclist *pDL = &p->doclist;
134135   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
134136 
134137   if( p->bIncr ){
134138     rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
134139   }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
134140     sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
134141         &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
134142     );
134143     pDL->pList = pDL->pNextDocid;
134144   }else{
134145     fts3EvalDlPhraseNext(pTab, pDL, pbEof);
134146   }
134147 
134148   return rc;
134149 }
134150 
134151 /*
134152 **
134153 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
134154 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
134155 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
134156 ** expressions for which all descendent tokens are deferred.
134157 **
134158 ** If parameter bOptOk is zero, then it is guaranteed that the
134159 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
134160 ** each phrase in the expression (subject to deferred token processing).
134161 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
134162 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
134163 **
134164 ** If an error occurs within this function, *pRc is set to an SQLite error
134165 ** code before returning.
134166 */
134167 static void fts3EvalStartReaders(
134168   Fts3Cursor *pCsr,               /* FTS Cursor handle */
134169   Fts3Expr *pExpr,                /* Expression to initialize phrases in */
134170   int *pRc                        /* IN/OUT: Error code */
134171 ){
134172   if( pExpr && SQLITE_OK==*pRc ){
134173     if( pExpr->eType==FTSQUERY_PHRASE ){
134174       int i;
134175       int nToken = pExpr->pPhrase->nToken;
134176       for(i=0; i<nToken; i++){
134177         if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
134178       }
134179       pExpr->bDeferred = (i==nToken);
134180       *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
134181     }else{
134182       fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
134183       fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
134184       pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
134185     }
134186   }
134187 }
134188 
134189 /*
134190 ** An array of the following structures is assembled as part of the process
134191 ** of selecting tokens to defer before the query starts executing (as part
134192 ** of the xFilter() method). There is one element in the array for each
134193 ** token in the FTS expression.
134194 **
134195 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
134196 ** to phrases that are connected only by AND and NEAR operators (not OR or
134197 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
134198 ** separately. The root of a tokens AND/NEAR cluster is stored in
134199 ** Fts3TokenAndCost.pRoot.
134200 */
134201 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
134202 struct Fts3TokenAndCost {
134203   Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
134204   int iToken;                     /* Position of token in phrase */
134205   Fts3PhraseToken *pToken;        /* The token itself */
134206   Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
134207   int nOvfl;                      /* Number of overflow pages to load doclist */
134208   int iCol;                       /* The column the token must match */
134209 };
134210 
134211 /*
134212 ** This function is used to populate an allocated Fts3TokenAndCost array.
134213 **
134214 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
134215 ** Otherwise, if an error occurs during execution, *pRc is set to an
134216 ** SQLite error code.
134217 */
134218 static void fts3EvalTokenCosts(
134219   Fts3Cursor *pCsr,               /* FTS Cursor handle */
134220   Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
134221   Fts3Expr *pExpr,                /* Expression to consider */
134222   Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
134223   Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
134224   int *pRc                        /* IN/OUT: Error code */
134225 ){
134226   if( *pRc==SQLITE_OK ){
134227     if( pExpr->eType==FTSQUERY_PHRASE ){
134228       Fts3Phrase *pPhrase = pExpr->pPhrase;
134229       int i;
134230       for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
134231         Fts3TokenAndCost *pTC = (*ppTC)++;
134232         pTC->pPhrase = pPhrase;
134233         pTC->iToken = i;
134234         pTC->pRoot = pRoot;
134235         pTC->pToken = &pPhrase->aToken[i];
134236         pTC->iCol = pPhrase->iColumn;
134237         *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
134238       }
134239     }else if( pExpr->eType!=FTSQUERY_NOT ){
134240       assert( pExpr->eType==FTSQUERY_OR
134241            || pExpr->eType==FTSQUERY_AND
134242            || pExpr->eType==FTSQUERY_NEAR
134243       );
134244       assert( pExpr->pLeft && pExpr->pRight );
134245       if( pExpr->eType==FTSQUERY_OR ){
134246         pRoot = pExpr->pLeft;
134247         **ppOr = pRoot;
134248         (*ppOr)++;
134249       }
134250       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
134251       if( pExpr->eType==FTSQUERY_OR ){
134252         pRoot = pExpr->pRight;
134253         **ppOr = pRoot;
134254         (*ppOr)++;
134255       }
134256       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
134257     }
134258   }
134259 }
134260 
134261 /*
134262 ** Determine the average document (row) size in pages. If successful,
134263 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
134264 ** an SQLite error code.
134265 **
134266 ** The average document size in pages is calculated by first calculating
134267 ** determining the average size in bytes, B. If B is less than the amount
134268 ** of data that will fit on a single leaf page of an intkey table in
134269 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
134270 ** the number of overflow pages consumed by a record B bytes in size.
134271 */
134272 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
134273   if( pCsr->nRowAvg==0 ){
134274     /* The average document size, which is required to calculate the cost
134275     ** of each doclist, has not yet been determined. Read the required
134276     ** data from the %_stat table to calculate it.
134277     **
134278     ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
134279     ** varints, where nCol is the number of columns in the FTS3 table.
134280     ** The first varint is the number of documents currently stored in
134281     ** the table. The following nCol varints contain the total amount of
134282     ** data stored in all rows of each column of the table, from left
134283     ** to right.
134284     */
134285     int rc;
134286     Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
134287     sqlite3_stmt *pStmt;
134288     sqlite3_int64 nDoc = 0;
134289     sqlite3_int64 nByte = 0;
134290     const char *pEnd;
134291     const char *a;
134292 
134293     rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
134294     if( rc!=SQLITE_OK ) return rc;
134295     a = sqlite3_column_blob(pStmt, 0);
134296     assert( a );
134297 
134298     pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
134299     a += sqlite3Fts3GetVarint(a, &nDoc);
134300     while( a<pEnd ){
134301       a += sqlite3Fts3GetVarint(a, &nByte);
134302     }
134303     if( nDoc==0 || nByte==0 ){
134304       sqlite3_reset(pStmt);
134305       return FTS_CORRUPT_VTAB;
134306     }
134307 
134308     pCsr->nDoc = nDoc;
134309     pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
134310     assert( pCsr->nRowAvg>0 );
134311     rc = sqlite3_reset(pStmt);
134312     if( rc!=SQLITE_OK ) return rc;
134313   }
134314 
134315   *pnPage = pCsr->nRowAvg;
134316   return SQLITE_OK;
134317 }
134318 
134319 /*
134320 ** This function is called to select the tokens (if any) that will be
134321 ** deferred. The array aTC[] has already been populated when this is
134322 ** called.
134323 **
134324 ** This function is called once for each AND/NEAR cluster in the
134325 ** expression. Each invocation determines which tokens to defer within
134326 ** the cluster with root node pRoot. See comments above the definition
134327 ** of struct Fts3TokenAndCost for more details.
134328 **
134329 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
134330 ** called on each token to defer. Otherwise, an SQLite error code is
134331 ** returned.
134332 */
134333 static int fts3EvalSelectDeferred(
134334   Fts3Cursor *pCsr,               /* FTS Cursor handle */
134335   Fts3Expr *pRoot,                /* Consider tokens with this root node */
134336   Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
134337   int nTC                         /* Number of entries in aTC[] */
134338 ){
134339   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
134340   int nDocSize = 0;               /* Number of pages per doc loaded */
134341   int rc = SQLITE_OK;             /* Return code */
134342   int ii;                         /* Iterator variable for various purposes */
134343   int nOvfl = 0;                  /* Total overflow pages used by doclists */
134344   int nToken = 0;                 /* Total number of tokens in cluster */
134345 
134346   int nMinEst = 0;                /* The minimum count for any phrase so far. */
134347   int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
134348 
134349   /* Tokens are never deferred for FTS tables created using the content=xxx
134350   ** option. The reason being that it is not guaranteed that the content
134351   ** table actually contains the same data as the index. To prevent this from
134352   ** causing any problems, the deferred token optimization is completely
134353   ** disabled for content=xxx tables. */
134354   if( pTab->zContentTbl ){
134355     return SQLITE_OK;
134356   }
134357 
134358   /* Count the tokens in this AND/NEAR cluster. If none of the doclists
134359   ** associated with the tokens spill onto overflow pages, or if there is
134360   ** only 1 token, exit early. No tokens to defer in this case. */
134361   for(ii=0; ii<nTC; ii++){
134362     if( aTC[ii].pRoot==pRoot ){
134363       nOvfl += aTC[ii].nOvfl;
134364       nToken++;
134365     }
134366   }
134367   if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
134368 
134369   /* Obtain the average docsize (in pages). */
134370   rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
134371   assert( rc!=SQLITE_OK || nDocSize>0 );
134372 
134373 
134374   /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
134375   ** of the number of overflow pages that will be loaded by the pager layer
134376   ** to retrieve the entire doclist for the token from the full-text index.
134377   ** Load the doclists for tokens that are either:
134378   **
134379   **   a. The cheapest token in the entire query (i.e. the one visited by the
134380   **      first iteration of this loop), or
134381   **
134382   **   b. Part of a multi-token phrase.
134383   **
134384   ** After each token doclist is loaded, merge it with the others from the
134385   ** same phrase and count the number of documents that the merged doclist
134386   ** contains. Set variable "nMinEst" to the smallest number of documents in
134387   ** any phrase doclist for which 1 or more token doclists have been loaded.
134388   ** Let nOther be the number of other phrases for which it is certain that
134389   ** one or more tokens will not be deferred.
134390   **
134391   ** Then, for each token, defer it if loading the doclist would result in
134392   ** loading N or more overflow pages into memory, where N is computed as:
134393   **
134394   **    (nMinEst + 4^nOther - 1) / (4^nOther)
134395   */
134396   for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
134397     int iTC;                      /* Used to iterate through aTC[] array. */
134398     Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
134399 
134400     /* Set pTC to point to the cheapest remaining token. */
134401     for(iTC=0; iTC<nTC; iTC++){
134402       if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
134403        && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
134404       ){
134405         pTC = &aTC[iTC];
134406       }
134407     }
134408     assert( pTC );
134409 
134410     if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
134411       /* The number of overflow pages to load for this (and therefore all
134412       ** subsequent) tokens is greater than the estimated number of pages
134413       ** that will be loaded if all subsequent tokens are deferred.
134414       */
134415       Fts3PhraseToken *pToken = pTC->pToken;
134416       rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
134417       fts3SegReaderCursorFree(pToken->pSegcsr);
134418       pToken->pSegcsr = 0;
134419     }else{
134420       /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
134421       ** for-loop. Except, limit the value to 2^24 to prevent it from
134422       ** overflowing the 32-bit integer it is stored in. */
134423       if( ii<12 ) nLoad4 = nLoad4*4;
134424 
134425       if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
134426         /* Either this is the cheapest token in the entire query, or it is
134427         ** part of a multi-token phrase. Either way, the entire doclist will
134428         ** (eventually) be loaded into memory. It may as well be now. */
134429         Fts3PhraseToken *pToken = pTC->pToken;
134430         int nList = 0;
134431         char *pList = 0;
134432         rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
134433         assert( rc==SQLITE_OK || pList==0 );
134434         if( rc==SQLITE_OK ){
134435           int nCount;
134436           fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
134437           nCount = fts3DoclistCountDocids(
134438               pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
134439           );
134440           if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
134441         }
134442       }
134443     }
134444     pTC->pToken = 0;
134445   }
134446 
134447   return rc;
134448 }
134449 
134450 /*
134451 ** This function is called from within the xFilter method. It initializes
134452 ** the full-text query currently stored in pCsr->pExpr. To iterate through
134453 ** the results of a query, the caller does:
134454 **
134455 **    fts3EvalStart(pCsr);
134456 **    while( 1 ){
134457 **      fts3EvalNext(pCsr);
134458 **      if( pCsr->bEof ) break;
134459 **      ... return row pCsr->iPrevId to the caller ...
134460 **    }
134461 */
134462 static int fts3EvalStart(Fts3Cursor *pCsr){
134463   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
134464   int rc = SQLITE_OK;
134465   int nToken = 0;
134466   int nOr = 0;
134467 
134468   /* Allocate a MultiSegReader for each token in the expression. */
134469   fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
134470 
134471   /* Determine which, if any, tokens in the expression should be deferred. */
134472 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
134473   if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
134474     Fts3TokenAndCost *aTC;
134475     Fts3Expr **apOr;
134476     aTC = (Fts3TokenAndCost *)sqlite3_malloc(
134477         sizeof(Fts3TokenAndCost) * nToken
134478       + sizeof(Fts3Expr *) * nOr * 2
134479     );
134480     apOr = (Fts3Expr **)&aTC[nToken];
134481 
134482     if( !aTC ){
134483       rc = SQLITE_NOMEM;
134484     }else{
134485       int ii;
134486       Fts3TokenAndCost *pTC = aTC;
134487       Fts3Expr **ppOr = apOr;
134488 
134489       fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
134490       nToken = (int)(pTC-aTC);
134491       nOr = (int)(ppOr-apOr);
134492 
134493       if( rc==SQLITE_OK ){
134494         rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
134495         for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
134496           rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
134497         }
134498       }
134499 
134500       sqlite3_free(aTC);
134501     }
134502   }
134503 #endif
134504 
134505   fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
134506   return rc;
134507 }
134508 
134509 /*
134510 ** Invalidate the current position list for phrase pPhrase.
134511 */
134512 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
134513   if( pPhrase->doclist.bFreeList ){
134514     sqlite3_free(pPhrase->doclist.pList);
134515   }
134516   pPhrase->doclist.pList = 0;
134517   pPhrase->doclist.nList = 0;
134518   pPhrase->doclist.bFreeList = 0;
134519 }
134520 
134521 /*
134522 ** This function is called to edit the position list associated with
134523 ** the phrase object passed as the fifth argument according to a NEAR
134524 ** condition. For example:
134525 **
134526 **     abc NEAR/5 "def ghi"
134527 **
134528 ** Parameter nNear is passed the NEAR distance of the expression (5 in
134529 ** the example above). When this function is called, *paPoslist points to
134530 ** the position list, and *pnToken is the number of phrase tokens in, the
134531 ** phrase on the other side of the NEAR operator to pPhrase. For example,
134532 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
134533 ** the position list associated with phrase "abc".
134534 **
134535 ** All positions in the pPhrase position list that are not sufficiently
134536 ** close to a position in the *paPoslist position list are removed. If this
134537 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
134538 **
134539 ** Before returning, *paPoslist is set to point to the position lsit
134540 ** associated with pPhrase. And *pnToken is set to the number of tokens in
134541 ** pPhrase.
134542 */
134543 static int fts3EvalNearTrim(
134544   int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
134545   char *aTmp,                     /* Temporary space to use */
134546   char **paPoslist,               /* IN/OUT: Position list */
134547   int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
134548   Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
134549 ){
134550   int nParam1 = nNear + pPhrase->nToken;
134551   int nParam2 = nNear + *pnToken;
134552   int nNew;
134553   char *p2;
134554   char *pOut;
134555   int res;
134556 
134557   assert( pPhrase->doclist.pList );
134558 
134559   p2 = pOut = pPhrase->doclist.pList;
134560   res = fts3PoslistNearMerge(
134561     &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
134562   );
134563   if( res ){
134564     nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
134565     assert( pPhrase->doclist.pList[nNew]=='\0' );
134566     assert( nNew<=pPhrase->doclist.nList && nNew>0 );
134567     memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
134568     pPhrase->doclist.nList = nNew;
134569     *paPoslist = pPhrase->doclist.pList;
134570     *pnToken = pPhrase->nToken;
134571   }
134572 
134573   return res;
134574 }
134575 
134576 /*
134577 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
134578 ** Otherwise, it advances the expression passed as the second argument to
134579 ** point to the next matching row in the database. Expressions iterate through
134580 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
134581 ** or descending if it is non-zero.
134582 **
134583 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
134584 ** successful, the following variables in pExpr are set:
134585 **
134586 **   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
134587 **   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
134588 **
134589 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
134590 ** at EOF, then the following variables are populated with the position list
134591 ** for the phrase for the visited row:
134592 **
134593 **   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
134594 **   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
134595 **
134596 ** It says above that this function advances the expression to the next
134597 ** matching row. This is usually true, but there are the following exceptions:
134598 **
134599 **   1. Deferred tokens are not taken into account. If a phrase consists
134600 **      entirely of deferred tokens, it is assumed to match every row in
134601 **      the db. In this case the position-list is not populated at all.
134602 **
134603 **      Or, if a phrase contains one or more deferred tokens and one or
134604 **      more non-deferred tokens, then the expression is advanced to the
134605 **      next possible match, considering only non-deferred tokens. In other
134606 **      words, if the phrase is "A B C", and "B" is deferred, the expression
134607 **      is advanced to the next row that contains an instance of "A * C",
134608 **      where "*" may match any single token. The position list in this case
134609 **      is populated as for "A * C" before returning.
134610 **
134611 **   2. NEAR is treated as AND. If the expression is "x NEAR y", it is
134612 **      advanced to point to the next row that matches "x AND y".
134613 **
134614 ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
134615 ** really a match, taking into account deferred tokens and NEAR operators.
134616 */
134617 static void fts3EvalNextRow(
134618   Fts3Cursor *pCsr,               /* FTS Cursor handle */
134619   Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
134620   int *pRc                        /* IN/OUT: Error code */
134621 ){
134622   if( *pRc==SQLITE_OK ){
134623     int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
134624     assert( pExpr->bEof==0 );
134625     pExpr->bStart = 1;
134626 
134627     switch( pExpr->eType ){
134628       case FTSQUERY_NEAR:
134629       case FTSQUERY_AND: {
134630         Fts3Expr *pLeft = pExpr->pLeft;
134631         Fts3Expr *pRight = pExpr->pRight;
134632         assert( !pLeft->bDeferred || !pRight->bDeferred );
134633 
134634         if( pLeft->bDeferred ){
134635           /* LHS is entirely deferred. So we assume it matches every row.
134636           ** Advance the RHS iterator to find the next row visited. */
134637           fts3EvalNextRow(pCsr, pRight, pRc);
134638           pExpr->iDocid = pRight->iDocid;
134639           pExpr->bEof = pRight->bEof;
134640         }else if( pRight->bDeferred ){
134641           /* RHS is entirely deferred. So we assume it matches every row.
134642           ** Advance the LHS iterator to find the next row visited. */
134643           fts3EvalNextRow(pCsr, pLeft, pRc);
134644           pExpr->iDocid = pLeft->iDocid;
134645           pExpr->bEof = pLeft->bEof;
134646         }else{
134647           /* Neither the RHS or LHS are deferred. */
134648           fts3EvalNextRow(pCsr, pLeft, pRc);
134649           fts3EvalNextRow(pCsr, pRight, pRc);
134650           while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
134651             sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
134652             if( iDiff==0 ) break;
134653             if( iDiff<0 ){
134654               fts3EvalNextRow(pCsr, pLeft, pRc);
134655             }else{
134656               fts3EvalNextRow(pCsr, pRight, pRc);
134657             }
134658           }
134659           pExpr->iDocid = pLeft->iDocid;
134660           pExpr->bEof = (pLeft->bEof || pRight->bEof);
134661         }
134662         break;
134663       }
134664 
134665       case FTSQUERY_OR: {
134666         Fts3Expr *pLeft = pExpr->pLeft;
134667         Fts3Expr *pRight = pExpr->pRight;
134668         sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
134669 
134670         assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
134671         assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
134672 
134673         if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
134674           fts3EvalNextRow(pCsr, pLeft, pRc);
134675         }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
134676           fts3EvalNextRow(pCsr, pRight, pRc);
134677         }else{
134678           fts3EvalNextRow(pCsr, pLeft, pRc);
134679           fts3EvalNextRow(pCsr, pRight, pRc);
134680         }
134681 
134682         pExpr->bEof = (pLeft->bEof && pRight->bEof);
134683         iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
134684         if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
134685           pExpr->iDocid = pLeft->iDocid;
134686         }else{
134687           pExpr->iDocid = pRight->iDocid;
134688         }
134689 
134690         break;
134691       }
134692 
134693       case FTSQUERY_NOT: {
134694         Fts3Expr *pLeft = pExpr->pLeft;
134695         Fts3Expr *pRight = pExpr->pRight;
134696 
134697         if( pRight->bStart==0 ){
134698           fts3EvalNextRow(pCsr, pRight, pRc);
134699           assert( *pRc!=SQLITE_OK || pRight->bStart );
134700         }
134701 
134702         fts3EvalNextRow(pCsr, pLeft, pRc);
134703         if( pLeft->bEof==0 ){
134704           while( !*pRc
134705               && !pRight->bEof
134706               && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
134707           ){
134708             fts3EvalNextRow(pCsr, pRight, pRc);
134709           }
134710         }
134711         pExpr->iDocid = pLeft->iDocid;
134712         pExpr->bEof = pLeft->bEof;
134713         break;
134714       }
134715 
134716       default: {
134717         Fts3Phrase *pPhrase = pExpr->pPhrase;
134718         fts3EvalInvalidatePoslist(pPhrase);
134719         *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
134720         pExpr->iDocid = pPhrase->doclist.iDocid;
134721         break;
134722       }
134723     }
134724   }
134725 }
134726 
134727 /*
134728 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
134729 ** cluster, then this function returns 1 immediately.
134730 **
134731 ** Otherwise, it checks if the current row really does match the NEAR
134732 ** expression, using the data currently stored in the position lists
134733 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
134734 **
134735 ** If the current row is a match, the position list associated with each
134736 ** phrase in the NEAR expression is edited in place to contain only those
134737 ** phrase instances sufficiently close to their peers to satisfy all NEAR
134738 ** constraints. In this case it returns 1. If the NEAR expression does not
134739 ** match the current row, 0 is returned. The position lists may or may not
134740 ** be edited if 0 is returned.
134741 */
134742 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
134743   int res = 1;
134744 
134745   /* The following block runs if pExpr is the root of a NEAR query.
134746   ** For example, the query:
134747   **
134748   **         "w" NEAR "x" NEAR "y" NEAR "z"
134749   **
134750   ** which is represented in tree form as:
134751   **
134752   **                               |
134753   **                          +--NEAR--+      <-- root of NEAR query
134754   **                          |        |
134755   **                     +--NEAR--+   "z"
134756   **                     |        |
134757   **                +--NEAR--+   "y"
134758   **                |        |
134759   **               "w"      "x"
134760   **
134761   ** The right-hand child of a NEAR node is always a phrase. The
134762   ** left-hand child may be either a phrase or a NEAR node. There are
134763   ** no exceptions to this - it's the way the parser in fts3_expr.c works.
134764   */
134765   if( *pRc==SQLITE_OK
134766    && pExpr->eType==FTSQUERY_NEAR
134767    && pExpr->bEof==0
134768    && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
134769   ){
134770     Fts3Expr *p;
134771     int nTmp = 0;                 /* Bytes of temp space */
134772     char *aTmp;                   /* Temp space for PoslistNearMerge() */
134773 
134774     /* Allocate temporary working space. */
134775     for(p=pExpr; p->pLeft; p=p->pLeft){
134776       nTmp += p->pRight->pPhrase->doclist.nList;
134777     }
134778     nTmp += p->pPhrase->doclist.nList;
134779     if( nTmp==0 ){
134780       res = 0;
134781     }else{
134782       aTmp = sqlite3_malloc(nTmp*2);
134783       if( !aTmp ){
134784         *pRc = SQLITE_NOMEM;
134785         res = 0;
134786       }else{
134787         char *aPoslist = p->pPhrase->doclist.pList;
134788         int nToken = p->pPhrase->nToken;
134789 
134790         for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
134791           Fts3Phrase *pPhrase = p->pRight->pPhrase;
134792           int nNear = p->nNear;
134793           res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
134794         }
134795 
134796         aPoslist = pExpr->pRight->pPhrase->doclist.pList;
134797         nToken = pExpr->pRight->pPhrase->nToken;
134798         for(p=pExpr->pLeft; p && res; p=p->pLeft){
134799           int nNear;
134800           Fts3Phrase *pPhrase;
134801           assert( p->pParent && p->pParent->pLeft==p );
134802           nNear = p->pParent->nNear;
134803           pPhrase = (
134804               p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
134805               );
134806           res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
134807         }
134808       }
134809 
134810       sqlite3_free(aTmp);
134811     }
134812   }
134813 
134814   return res;
134815 }
134816 
134817 /*
134818 ** This function is a helper function for fts3EvalTestDeferredAndNear().
134819 ** Assuming no error occurs or has occurred, It returns non-zero if the
134820 ** expression passed as the second argument matches the row that pCsr
134821 ** currently points to, or zero if it does not.
134822 **
134823 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
134824 ** If an error occurs during execution of this function, *pRc is set to
134825 ** the appropriate SQLite error code. In this case the returned value is
134826 ** undefined.
134827 */
134828 static int fts3EvalTestExpr(
134829   Fts3Cursor *pCsr,               /* FTS cursor handle */
134830   Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
134831   int *pRc                        /* IN/OUT: Error code */
134832 ){
134833   int bHit = 1;                   /* Return value */
134834   if( *pRc==SQLITE_OK ){
134835     switch( pExpr->eType ){
134836       case FTSQUERY_NEAR:
134837       case FTSQUERY_AND:
134838         bHit = (
134839             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
134840          && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
134841          && fts3EvalNearTest(pExpr, pRc)
134842         );
134843 
134844         /* If the NEAR expression does not match any rows, zero the doclist for
134845         ** all phrases involved in the NEAR. This is because the snippet(),
134846         ** offsets() and matchinfo() functions are not supposed to recognize
134847         ** any instances of phrases that are part of unmatched NEAR queries.
134848         ** For example if this expression:
134849         **
134850         **    ... MATCH 'a OR (b NEAR c)'
134851         **
134852         ** is matched against a row containing:
134853         **
134854         **        'a b d e'
134855         **
134856         ** then any snippet() should ony highlight the "a" term, not the "b"
134857         ** (as "b" is part of a non-matching NEAR clause).
134858         */
134859         if( bHit==0
134860          && pExpr->eType==FTSQUERY_NEAR
134861          && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
134862         ){
134863           Fts3Expr *p;
134864           for(p=pExpr; p->pPhrase==0; p=p->pLeft){
134865             if( p->pRight->iDocid==pCsr->iPrevId ){
134866               fts3EvalInvalidatePoslist(p->pRight->pPhrase);
134867             }
134868           }
134869           if( p->iDocid==pCsr->iPrevId ){
134870             fts3EvalInvalidatePoslist(p->pPhrase);
134871           }
134872         }
134873 
134874         break;
134875 
134876       case FTSQUERY_OR: {
134877         int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
134878         int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
134879         bHit = bHit1 || bHit2;
134880         break;
134881       }
134882 
134883       case FTSQUERY_NOT:
134884         bHit = (
134885             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
134886          && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
134887         );
134888         break;
134889 
134890       default: {
134891 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
134892         if( pCsr->pDeferred
134893          && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
134894         ){
134895           Fts3Phrase *pPhrase = pExpr->pPhrase;
134896           assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
134897           if( pExpr->bDeferred ){
134898             fts3EvalInvalidatePoslist(pPhrase);
134899           }
134900           *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
134901           bHit = (pPhrase->doclist.pList!=0);
134902           pExpr->iDocid = pCsr->iPrevId;
134903         }else
134904 #endif
134905         {
134906           bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
134907         }
134908         break;
134909       }
134910     }
134911   }
134912   return bHit;
134913 }
134914 
134915 /*
134916 ** This function is called as the second part of each xNext operation when
134917 ** iterating through the results of a full-text query. At this point the
134918 ** cursor points to a row that matches the query expression, with the
134919 ** following caveats:
134920 **
134921 **   * Up until this point, "NEAR" operators in the expression have been
134922 **     treated as "AND".
134923 **
134924 **   * Deferred tokens have not yet been considered.
134925 **
134926 ** If *pRc is not SQLITE_OK when this function is called, it immediately
134927 ** returns 0. Otherwise, it tests whether or not after considering NEAR
134928 ** operators and deferred tokens the current row is still a match for the
134929 ** expression. It returns 1 if both of the following are true:
134930 **
134931 **   1. *pRc is SQLITE_OK when this function returns, and
134932 **
134933 **   2. After scanning the current FTS table row for the deferred tokens,
134934 **      it is determined that the row does *not* match the query.
134935 **
134936 ** Or, if no error occurs and it seems the current row does match the FTS
134937 ** query, return 0.
134938 */
134939 static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
134940   int rc = *pRc;
134941   int bMiss = 0;
134942   if( rc==SQLITE_OK ){
134943 
134944     /* If there are one or more deferred tokens, load the current row into
134945     ** memory and scan it to determine the position list for each deferred
134946     ** token. Then, see if this row is really a match, considering deferred
134947     ** tokens and NEAR operators (neither of which were taken into account
134948     ** earlier, by fts3EvalNextRow()).
134949     */
134950     if( pCsr->pDeferred ){
134951       rc = fts3CursorSeek(0, pCsr);
134952       if( rc==SQLITE_OK ){
134953         rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
134954       }
134955     }
134956     bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
134957 
134958     /* Free the position-lists accumulated for each deferred token above. */
134959     sqlite3Fts3FreeDeferredDoclists(pCsr);
134960     *pRc = rc;
134961   }
134962   return (rc==SQLITE_OK && bMiss);
134963 }
134964 
134965 /*
134966 ** Advance to the next document that matches the FTS expression in
134967 ** Fts3Cursor.pExpr.
134968 */
134969 static int fts3EvalNext(Fts3Cursor *pCsr){
134970   int rc = SQLITE_OK;             /* Return Code */
134971   Fts3Expr *pExpr = pCsr->pExpr;
134972   assert( pCsr->isEof==0 );
134973   if( pExpr==0 ){
134974     pCsr->isEof = 1;
134975   }else{
134976     do {
134977       if( pCsr->isRequireSeek==0 ){
134978         sqlite3_reset(pCsr->pStmt);
134979       }
134980       assert( sqlite3_data_count(pCsr->pStmt)==0 );
134981       fts3EvalNextRow(pCsr, pExpr, &rc);
134982       pCsr->isEof = pExpr->bEof;
134983       pCsr->isRequireSeek = 1;
134984       pCsr->isMatchinfoNeeded = 1;
134985       pCsr->iPrevId = pExpr->iDocid;
134986     }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
134987   }
134988 
134989   /* Check if the cursor is past the end of the docid range specified
134990   ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag.  */
134991   if( rc==SQLITE_OK && (
134992         (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
134993      || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
134994   )){
134995     pCsr->isEof = 1;
134996   }
134997 
134998   return rc;
134999 }
135000 
135001 /*
135002 ** Restart interation for expression pExpr so that the next call to
135003 ** fts3EvalNext() visits the first row. Do not allow incremental
135004 ** loading or merging of phrase doclists for this iteration.
135005 **
135006 ** If *pRc is other than SQLITE_OK when this function is called, it is
135007 ** a no-op. If an error occurs within this function, *pRc is set to an
135008 ** SQLite error code before returning.
135009 */
135010 static void fts3EvalRestart(
135011   Fts3Cursor *pCsr,
135012   Fts3Expr *pExpr,
135013   int *pRc
135014 ){
135015   if( pExpr && *pRc==SQLITE_OK ){
135016     Fts3Phrase *pPhrase = pExpr->pPhrase;
135017 
135018     if( pPhrase ){
135019       fts3EvalInvalidatePoslist(pPhrase);
135020       if( pPhrase->bIncr ){
135021         int i;
135022         for(i=0; i<pPhrase->nToken; i++){
135023           Fts3PhraseToken *pToken = &pPhrase->aToken[i];
135024           assert( pToken->pDeferred==0 );
135025           if( pToken->pSegcsr ){
135026             sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
135027           }
135028         }
135029         *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
135030       }
135031       pPhrase->doclist.pNextDocid = 0;
135032       pPhrase->doclist.iDocid = 0;
135033     }
135034 
135035     pExpr->iDocid = 0;
135036     pExpr->bEof = 0;
135037     pExpr->bStart = 0;
135038 
135039     fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
135040     fts3EvalRestart(pCsr, pExpr->pRight, pRc);
135041   }
135042 }
135043 
135044 /*
135045 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
135046 ** expression rooted at pExpr, the cursor iterates through all rows matched
135047 ** by pExpr, calling this function for each row. This function increments
135048 ** the values in Fts3Expr.aMI[] according to the position-list currently
135049 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
135050 ** expression nodes.
135051 */
135052 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
135053   if( pExpr ){
135054     Fts3Phrase *pPhrase = pExpr->pPhrase;
135055     if( pPhrase && pPhrase->doclist.pList ){
135056       int iCol = 0;
135057       char *p = pPhrase->doclist.pList;
135058 
135059       assert( *p );
135060       while( 1 ){
135061         u8 c = 0;
135062         int iCnt = 0;
135063         while( 0xFE & (*p | c) ){
135064           if( (c&0x80)==0 ) iCnt++;
135065           c = *p++ & 0x80;
135066         }
135067 
135068         /* aMI[iCol*3 + 1] = Number of occurrences
135069         ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
135070         */
135071         pExpr->aMI[iCol*3 + 1] += iCnt;
135072         pExpr->aMI[iCol*3 + 2] += (iCnt>0);
135073         if( *p==0x00 ) break;
135074         p++;
135075         p += fts3GetVarint32(p, &iCol);
135076       }
135077     }
135078 
135079     fts3EvalUpdateCounts(pExpr->pLeft);
135080     fts3EvalUpdateCounts(pExpr->pRight);
135081   }
135082 }
135083 
135084 /*
135085 ** Expression pExpr must be of type FTSQUERY_PHRASE.
135086 **
135087 ** If it is not already allocated and populated, this function allocates and
135088 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
135089 ** of a NEAR expression, then it also allocates and populates the same array
135090 ** for all other phrases that are part of the NEAR expression.
135091 **
135092 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
135093 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
135094 */
135095 static int fts3EvalGatherStats(
135096   Fts3Cursor *pCsr,               /* Cursor object */
135097   Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
135098 ){
135099   int rc = SQLITE_OK;             /* Return code */
135100 
135101   assert( pExpr->eType==FTSQUERY_PHRASE );
135102   if( pExpr->aMI==0 ){
135103     Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
135104     Fts3Expr *pRoot;                /* Root of NEAR expression */
135105     Fts3Expr *p;                    /* Iterator used for several purposes */
135106 
135107     sqlite3_int64 iPrevId = pCsr->iPrevId;
135108     sqlite3_int64 iDocid;
135109     u8 bEof;
135110 
135111     /* Find the root of the NEAR expression */
135112     pRoot = pExpr;
135113     while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
135114       pRoot = pRoot->pParent;
135115     }
135116     iDocid = pRoot->iDocid;
135117     bEof = pRoot->bEof;
135118     assert( pRoot->bStart );
135119 
135120     /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
135121     for(p=pRoot; p; p=p->pLeft){
135122       Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
135123       assert( pE->aMI==0 );
135124       pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
135125       if( !pE->aMI ) return SQLITE_NOMEM;
135126       memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
135127     }
135128 
135129     fts3EvalRestart(pCsr, pRoot, &rc);
135130 
135131     while( pCsr->isEof==0 && rc==SQLITE_OK ){
135132 
135133       do {
135134         /* Ensure the %_content statement is reset. */
135135         if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
135136         assert( sqlite3_data_count(pCsr->pStmt)==0 );
135137 
135138         /* Advance to the next document */
135139         fts3EvalNextRow(pCsr, pRoot, &rc);
135140         pCsr->isEof = pRoot->bEof;
135141         pCsr->isRequireSeek = 1;
135142         pCsr->isMatchinfoNeeded = 1;
135143         pCsr->iPrevId = pRoot->iDocid;
135144       }while( pCsr->isEof==0
135145            && pRoot->eType==FTSQUERY_NEAR
135146            && fts3EvalTestDeferredAndNear(pCsr, &rc)
135147       );
135148 
135149       if( rc==SQLITE_OK && pCsr->isEof==0 ){
135150         fts3EvalUpdateCounts(pRoot);
135151       }
135152     }
135153 
135154     pCsr->isEof = 0;
135155     pCsr->iPrevId = iPrevId;
135156 
135157     if( bEof ){
135158       pRoot->bEof = bEof;
135159     }else{
135160       /* Caution: pRoot may iterate through docids in ascending or descending
135161       ** order. For this reason, even though it seems more defensive, the
135162       ** do loop can not be written:
135163       **
135164       **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
135165       */
135166       fts3EvalRestart(pCsr, pRoot, &rc);
135167       do {
135168         fts3EvalNextRow(pCsr, pRoot, &rc);
135169         assert( pRoot->bEof==0 );
135170       }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
135171       fts3EvalTestDeferredAndNear(pCsr, &rc);
135172     }
135173   }
135174   return rc;
135175 }
135176 
135177 /*
135178 ** This function is used by the matchinfo() module to query a phrase
135179 ** expression node for the following information:
135180 **
135181 **   1. The total number of occurrences of the phrase in each column of
135182 **      the FTS table (considering all rows), and
135183 **
135184 **   2. For each column, the number of rows in the table for which the
135185 **      column contains at least one instance of the phrase.
135186 **
135187 ** If no error occurs, SQLITE_OK is returned and the values for each column
135188 ** written into the array aiOut as follows:
135189 **
135190 **   aiOut[iCol*3 + 1] = Number of occurrences
135191 **   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
135192 **
135193 ** Caveats:
135194 **
135195 **   * If a phrase consists entirely of deferred tokens, then all output
135196 **     values are set to the number of documents in the table. In other
135197 **     words we assume that very common tokens occur exactly once in each
135198 **     column of each row of the table.
135199 **
135200 **   * If a phrase contains some deferred tokens (and some non-deferred
135201 **     tokens), count the potential occurrence identified by considering
135202 **     the non-deferred tokens instead of actual phrase occurrences.
135203 **
135204 **   * If the phrase is part of a NEAR expression, then only phrase instances
135205 **     that meet the NEAR constraint are included in the counts.
135206 */
135207 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
135208   Fts3Cursor *pCsr,               /* FTS cursor handle */
135209   Fts3Expr *pExpr,                /* Phrase expression */
135210   u32 *aiOut                      /* Array to write results into (see above) */
135211 ){
135212   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
135213   int rc = SQLITE_OK;
135214   int iCol;
135215 
135216   if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
135217     assert( pCsr->nDoc>0 );
135218     for(iCol=0; iCol<pTab->nColumn; iCol++){
135219       aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
135220       aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
135221     }
135222   }else{
135223     rc = fts3EvalGatherStats(pCsr, pExpr);
135224     if( rc==SQLITE_OK ){
135225       assert( pExpr->aMI );
135226       for(iCol=0; iCol<pTab->nColumn; iCol++){
135227         aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
135228         aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
135229       }
135230     }
135231   }
135232 
135233   return rc;
135234 }
135235 
135236 /*
135237 ** The expression pExpr passed as the second argument to this function
135238 ** must be of type FTSQUERY_PHRASE.
135239 **
135240 ** The returned value is either NULL or a pointer to a buffer containing
135241 ** a position-list indicating the occurrences of the phrase in column iCol
135242 ** of the current row.
135243 **
135244 ** More specifically, the returned buffer contains 1 varint for each
135245 ** occurrence of the phrase in the column, stored using the normal (delta+2)
135246 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
135247 ** if the requested column contains "a b X c d X X" and the position-list
135248 ** for 'X' is requested, the buffer returned may contain:
135249 **
135250 **     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
135251 **
135252 ** This function works regardless of whether or not the phrase is deferred,
135253 ** incremental, or neither.
135254 */
135255 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
135256   Fts3Cursor *pCsr,               /* FTS3 cursor object */
135257   Fts3Expr *pExpr,                /* Phrase to return doclist for */
135258   int iCol,                       /* Column to return position list for */
135259   char **ppOut                    /* OUT: Pointer to position list */
135260 ){
135261   Fts3Phrase *pPhrase = pExpr->pPhrase;
135262   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
135263   char *pIter;
135264   int iThis;
135265   sqlite3_int64 iDocid;
135266 
135267   /* If this phrase is applies specifically to some column other than
135268   ** column iCol, return a NULL pointer.  */
135269   *ppOut = 0;
135270   assert( iCol>=0 && iCol<pTab->nColumn );
135271   if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
135272     return SQLITE_OK;
135273   }
135274 
135275   iDocid = pExpr->iDocid;
135276   pIter = pPhrase->doclist.pList;
135277   if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
135278     int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
135279     int iMul;                     /* +1 if csr dir matches index dir, else -1 */
135280     int bOr = 0;
135281     u8 bEof = 0;
135282     u8 bTreeEof = 0;
135283     Fts3Expr *p;                  /* Used to iterate from pExpr to root */
135284     Fts3Expr *pNear;              /* Most senior NEAR ancestor (or pExpr) */
135285 
135286     /* Check if this phrase descends from an OR expression node. If not,
135287     ** return NULL. Otherwise, the entry that corresponds to docid
135288     ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
135289     ** tree that the node is part of has been marked as EOF, but the node
135290     ** itself is not EOF, then it may point to an earlier entry. */
135291     pNear = pExpr;
135292     for(p=pExpr->pParent; p; p=p->pParent){
135293       if( p->eType==FTSQUERY_OR ) bOr = 1;
135294       if( p->eType==FTSQUERY_NEAR ) pNear = p;
135295       if( p->bEof ) bTreeEof = 1;
135296     }
135297     if( bOr==0 ) return SQLITE_OK;
135298 
135299     /* This is the descendent of an OR node. In this case we cannot use
135300     ** an incremental phrase. Load the entire doclist for the phrase
135301     ** into memory in this case.  */
135302     if( pPhrase->bIncr ){
135303       int rc = SQLITE_OK;
135304       int bEofSave = pExpr->bEof;
135305       fts3EvalRestart(pCsr, pExpr, &rc);
135306       while( rc==SQLITE_OK && !pExpr->bEof ){
135307         fts3EvalNextRow(pCsr, pExpr, &rc);
135308         if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
135309       }
135310       pIter = pPhrase->doclist.pList;
135311       assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
135312       if( rc!=SQLITE_OK ) return rc;
135313     }
135314 
135315     iMul = ((pCsr->bDesc==bDescDoclist) ? 1 : -1);
135316     while( bTreeEof==1
135317         && pNear->bEof==0
135318         && (DOCID_CMP(pNear->iDocid, pCsr->iPrevId) * iMul)<0
135319     ){
135320       int rc = SQLITE_OK;
135321       fts3EvalNextRow(pCsr, pExpr, &rc);
135322       if( rc!=SQLITE_OK ) return rc;
135323       iDocid = pExpr->iDocid;
135324       pIter = pPhrase->doclist.pList;
135325     }
135326 
135327     bEof = (pPhrase->doclist.nAll==0);
135328     assert( bDescDoclist==0 || bDescDoclist==1 );
135329     assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
135330 
135331     if( bEof==0 ){
135332       if( pCsr->bDesc==bDescDoclist ){
135333         int dummy;
135334         if( pNear->bEof ){
135335           /* This expression is already at EOF. So position it to point to the
135336           ** last entry in the doclist at pPhrase->doclist.aAll[]. Variable
135337           ** iDocid is already set for this entry, so all that is required is
135338           ** to set pIter to point to the first byte of the last position-list
135339           ** in the doclist.
135340           **
135341           ** It would also be correct to set pIter and iDocid to zero. In
135342           ** this case, the first call to sqltie3Fts4DoclistPrev() below
135343           ** would also move the iterator to point to the last entry in the
135344           ** doclist. However, this is expensive, as to do so it has to
135345           ** iterate through the entire doclist from start to finish (since
135346           ** it does not know the docid for the last entry).  */
135347           pIter = &pPhrase->doclist.aAll[pPhrase->doclist.nAll-1];
135348           fts3ReversePoslist(pPhrase->doclist.aAll, &pIter);
135349         }
135350         while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
135351           sqlite3Fts3DoclistPrev(
135352               bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
135353               &pIter, &iDocid, &dummy, &bEof
135354           );
135355         }
135356       }else{
135357         if( pNear->bEof ){
135358           pIter = 0;
135359           iDocid = 0;
135360         }
135361         while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
135362           sqlite3Fts3DoclistNext(
135363               bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
135364               &pIter, &iDocid, &bEof
135365           );
135366         }
135367       }
135368     }
135369 
135370     if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
135371   }
135372   if( pIter==0 ) return SQLITE_OK;
135373 
135374   if( *pIter==0x01 ){
135375     pIter++;
135376     pIter += fts3GetVarint32(pIter, &iThis);
135377   }else{
135378     iThis = 0;
135379   }
135380   while( iThis<iCol ){
135381     fts3ColumnlistCopy(0, &pIter);
135382     if( *pIter==0x00 ) return 0;
135383     pIter++;
135384     pIter += fts3GetVarint32(pIter, &iThis);
135385   }
135386 
135387   *ppOut = ((iCol==iThis)?pIter:0);
135388   return SQLITE_OK;
135389 }
135390 
135391 /*
135392 ** Free all components of the Fts3Phrase structure that were allocated by
135393 ** the eval module. Specifically, this means to free:
135394 **
135395 **   * the contents of pPhrase->doclist, and
135396 **   * any Fts3MultiSegReader objects held by phrase tokens.
135397 */
135398 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
135399   if( pPhrase ){
135400     int i;
135401     sqlite3_free(pPhrase->doclist.aAll);
135402     fts3EvalInvalidatePoslist(pPhrase);
135403     memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
135404     for(i=0; i<pPhrase->nToken; i++){
135405       fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
135406       pPhrase->aToken[i].pSegcsr = 0;
135407     }
135408   }
135409 }
135410 
135411 
135412 /*
135413 ** Return SQLITE_CORRUPT_VTAB.
135414 */
135415 #ifdef SQLITE_DEBUG
135416 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
135417   return SQLITE_CORRUPT_VTAB;
135418 }
135419 #endif
135420 
135421 #if !SQLITE_CORE
135422 /*
135423 ** Initialize API pointer table, if required.
135424 */
135425 #ifdef _WIN32
135426 __declspec(dllexport)
135427 #endif
135428 SQLITE_API int sqlite3_fts3_init(
135429   sqlite3 *db,
135430   char **pzErrMsg,
135431   const sqlite3_api_routines *pApi
135432 ){
135433   SQLITE_EXTENSION_INIT2(pApi)
135434   return sqlite3Fts3Init(db);
135435 }
135436 #endif
135437 
135438 #endif
135439 
135440 /************** End of fts3.c ************************************************/
135441 /************** Begin file fts3_aux.c ****************************************/
135442 /*
135443 ** 2011 Jan 27
135444 **
135445 ** The author disclaims copyright to this source code.  In place of
135446 ** a legal notice, here is a blessing:
135447 **
135448 **    May you do good and not evil.
135449 **    May you find forgiveness for yourself and forgive others.
135450 **    May you share freely, never taking more than you give.
135451 **
135452 ******************************************************************************
135453 **
135454 */
135455 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
135456 
135457 /* #include <string.h> */
135458 /* #include <assert.h> */
135459 
135460 typedef struct Fts3auxTable Fts3auxTable;
135461 typedef struct Fts3auxCursor Fts3auxCursor;
135462 
135463 struct Fts3auxTable {
135464   sqlite3_vtab base;              /* Base class used by SQLite core */
135465   Fts3Table *pFts3Tab;
135466 };
135467 
135468 struct Fts3auxCursor {
135469   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
135470   Fts3MultiSegReader csr;        /* Must be right after "base" */
135471   Fts3SegFilter filter;
135472   char *zStop;
135473   int nStop;                      /* Byte-length of string zStop */
135474   int iLangid;                    /* Language id to query */
135475   int isEof;                      /* True if cursor is at EOF */
135476   sqlite3_int64 iRowid;           /* Current rowid */
135477 
135478   int iCol;                       /* Current value of 'col' column */
135479   int nStat;                      /* Size of aStat[] array */
135480   struct Fts3auxColstats {
135481     sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
135482     sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
135483   } *aStat;
135484 };
135485 
135486 /*
135487 ** Schema of the terms table.
135488 */
135489 #define FTS3_AUX_SCHEMA \
135490   "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
135491 
135492 /*
135493 ** This function does all the work for both the xConnect and xCreate methods.
135494 ** These tables have no persistent representation of their own, so xConnect
135495 ** and xCreate are identical operations.
135496 */
135497 static int fts3auxConnectMethod(
135498   sqlite3 *db,                    /* Database connection */
135499   void *pUnused,                  /* Unused */
135500   int argc,                       /* Number of elements in argv array */
135501   const char * const *argv,       /* xCreate/xConnect argument array */
135502   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
135503   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
135504 ){
135505   char const *zDb;                /* Name of database (e.g. "main") */
135506   char const *zFts3;              /* Name of fts3 table */
135507   int nDb;                        /* Result of strlen(zDb) */
135508   int nFts3;                      /* Result of strlen(zFts3) */
135509   int nByte;                      /* Bytes of space to allocate here */
135510   int rc;                         /* value returned by declare_vtab() */
135511   Fts3auxTable *p;                /* Virtual table object to return */
135512 
135513   UNUSED_PARAMETER(pUnused);
135514 
135515   /* The user should invoke this in one of two forms:
135516   **
135517   **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
135518   **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
135519   */
135520   if( argc!=4 && argc!=5 ) goto bad_args;
135521 
135522   zDb = argv[1];
135523   nDb = (int)strlen(zDb);
135524   if( argc==5 ){
135525     if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
135526       zDb = argv[3];
135527       nDb = (int)strlen(zDb);
135528       zFts3 = argv[4];
135529     }else{
135530       goto bad_args;
135531     }
135532   }else{
135533     zFts3 = argv[3];
135534   }
135535   nFts3 = (int)strlen(zFts3);
135536 
135537   rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
135538   if( rc!=SQLITE_OK ) return rc;
135539 
135540   nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
135541   p = (Fts3auxTable *)sqlite3_malloc(nByte);
135542   if( !p ) return SQLITE_NOMEM;
135543   memset(p, 0, nByte);
135544 
135545   p->pFts3Tab = (Fts3Table *)&p[1];
135546   p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
135547   p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
135548   p->pFts3Tab->db = db;
135549   p->pFts3Tab->nIndex = 1;
135550 
135551   memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
135552   memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
135553   sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
135554 
135555   *ppVtab = (sqlite3_vtab *)p;
135556   return SQLITE_OK;
135557 
135558  bad_args:
135559   *pzErr = sqlite3_mprintf("invalid arguments to fts4aux constructor");
135560   return SQLITE_ERROR;
135561 }
135562 
135563 /*
135564 ** This function does the work for both the xDisconnect and xDestroy methods.
135565 ** These tables have no persistent representation of their own, so xDisconnect
135566 ** and xDestroy are identical operations.
135567 */
135568 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
135569   Fts3auxTable *p = (Fts3auxTable *)pVtab;
135570   Fts3Table *pFts3 = p->pFts3Tab;
135571   int i;
135572 
135573   /* Free any prepared statements held */
135574   for(i=0; i<SizeofArray(pFts3->aStmt); i++){
135575     sqlite3_finalize(pFts3->aStmt[i]);
135576   }
135577   sqlite3_free(pFts3->zSegmentsTbl);
135578   sqlite3_free(p);
135579   return SQLITE_OK;
135580 }
135581 
135582 #define FTS4AUX_EQ_CONSTRAINT 1
135583 #define FTS4AUX_GE_CONSTRAINT 2
135584 #define FTS4AUX_LE_CONSTRAINT 4
135585 
135586 /*
135587 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
135588 */
135589 static int fts3auxBestIndexMethod(
135590   sqlite3_vtab *pVTab,
135591   sqlite3_index_info *pInfo
135592 ){
135593   int i;
135594   int iEq = -1;
135595   int iGe = -1;
135596   int iLe = -1;
135597   int iLangid = -1;
135598   int iNext = 1;                  /* Next free argvIndex value */
135599 
135600   UNUSED_PARAMETER(pVTab);
135601 
135602   /* This vtab delivers always results in "ORDER BY term ASC" order. */
135603   if( pInfo->nOrderBy==1
135604    && pInfo->aOrderBy[0].iColumn==0
135605    && pInfo->aOrderBy[0].desc==0
135606   ){
135607     pInfo->orderByConsumed = 1;
135608   }
135609 
135610   /* Search for equality and range constraints on the "term" column.
135611   ** And equality constraints on the hidden "languageid" column. */
135612   for(i=0; i<pInfo->nConstraint; i++){
135613     if( pInfo->aConstraint[i].usable ){
135614       int op = pInfo->aConstraint[i].op;
135615       int iCol = pInfo->aConstraint[i].iColumn;
135616 
135617       if( iCol==0 ){
135618         if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
135619         if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
135620         if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
135621         if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
135622         if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
135623       }
135624       if( iCol==4 ){
135625         if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
135626       }
135627     }
135628   }
135629 
135630   if( iEq>=0 ){
135631     pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
135632     pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
135633     pInfo->estimatedCost = 5;
135634   }else{
135635     pInfo->idxNum = 0;
135636     pInfo->estimatedCost = 20000;
135637     if( iGe>=0 ){
135638       pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
135639       pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
135640       pInfo->estimatedCost /= 2;
135641     }
135642     if( iLe>=0 ){
135643       pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
135644       pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
135645       pInfo->estimatedCost /= 2;
135646     }
135647   }
135648   if( iLangid>=0 ){
135649     pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
135650     pInfo->estimatedCost--;
135651   }
135652 
135653   return SQLITE_OK;
135654 }
135655 
135656 /*
135657 ** xOpen - Open a cursor.
135658 */
135659 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
135660   Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
135661 
135662   UNUSED_PARAMETER(pVTab);
135663 
135664   pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
135665   if( !pCsr ) return SQLITE_NOMEM;
135666   memset(pCsr, 0, sizeof(Fts3auxCursor));
135667 
135668   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
135669   return SQLITE_OK;
135670 }
135671 
135672 /*
135673 ** xClose - Close a cursor.
135674 */
135675 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
135676   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
135677   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
135678 
135679   sqlite3Fts3SegmentsClose(pFts3);
135680   sqlite3Fts3SegReaderFinish(&pCsr->csr);
135681   sqlite3_free((void *)pCsr->filter.zTerm);
135682   sqlite3_free(pCsr->zStop);
135683   sqlite3_free(pCsr->aStat);
135684   sqlite3_free(pCsr);
135685   return SQLITE_OK;
135686 }
135687 
135688 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
135689   if( nSize>pCsr->nStat ){
135690     struct Fts3auxColstats *aNew;
135691     aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
135692         sizeof(struct Fts3auxColstats) * nSize
135693     );
135694     if( aNew==0 ) return SQLITE_NOMEM;
135695     memset(&aNew[pCsr->nStat], 0,
135696         sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
135697     );
135698     pCsr->aStat = aNew;
135699     pCsr->nStat = nSize;
135700   }
135701   return SQLITE_OK;
135702 }
135703 
135704 /*
135705 ** xNext - Advance the cursor to the next row, if any.
135706 */
135707 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
135708   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
135709   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
135710   int rc;
135711 
135712   /* Increment our pretend rowid value. */
135713   pCsr->iRowid++;
135714 
135715   for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
135716     if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
135717   }
135718 
135719   rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
135720   if( rc==SQLITE_ROW ){
135721     int i = 0;
135722     int nDoclist = pCsr->csr.nDoclist;
135723     char *aDoclist = pCsr->csr.aDoclist;
135724     int iCol;
135725 
135726     int eState = 0;
135727 
135728     if( pCsr->zStop ){
135729       int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
135730       int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
135731       if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
135732         pCsr->isEof = 1;
135733         return SQLITE_OK;
135734       }
135735     }
135736 
135737     if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
135738     memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
135739     iCol = 0;
135740 
135741     while( i<nDoclist ){
135742       sqlite3_int64 v = 0;
135743 
135744       i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
135745       switch( eState ){
135746         /* State 0. In this state the integer just read was a docid. */
135747         case 0:
135748           pCsr->aStat[0].nDoc++;
135749           eState = 1;
135750           iCol = 0;
135751           break;
135752 
135753         /* State 1. In this state we are expecting either a 1, indicating
135754         ** that the following integer will be a column number, or the
135755         ** start of a position list for column 0.
135756         **
135757         ** The only difference between state 1 and state 2 is that if the
135758         ** integer encountered in state 1 is not 0 or 1, then we need to
135759         ** increment the column 0 "nDoc" count for this term.
135760         */
135761         case 1:
135762           assert( iCol==0 );
135763           if( v>1 ){
135764             pCsr->aStat[1].nDoc++;
135765           }
135766           eState = 2;
135767           /* fall through */
135768 
135769         case 2:
135770           if( v==0 ){       /* 0x00. Next integer will be a docid. */
135771             eState = 0;
135772           }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
135773             eState = 3;
135774           }else{            /* 2 or greater. A position. */
135775             pCsr->aStat[iCol+1].nOcc++;
135776             pCsr->aStat[0].nOcc++;
135777           }
135778           break;
135779 
135780         /* State 3. The integer just read is a column number. */
135781         default: assert( eState==3 );
135782           iCol = (int)v;
135783           if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
135784           pCsr->aStat[iCol+1].nDoc++;
135785           eState = 2;
135786           break;
135787       }
135788     }
135789 
135790     pCsr->iCol = 0;
135791     rc = SQLITE_OK;
135792   }else{
135793     pCsr->isEof = 1;
135794   }
135795   return rc;
135796 }
135797 
135798 /*
135799 ** xFilter - Initialize a cursor to point at the start of its data.
135800 */
135801 static int fts3auxFilterMethod(
135802   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
135803   int idxNum,                     /* Strategy index */
135804   const char *idxStr,             /* Unused */
135805   int nVal,                       /* Number of elements in apVal */
135806   sqlite3_value **apVal           /* Arguments for the indexing scheme */
135807 ){
135808   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
135809   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
135810   int rc;
135811   int isScan = 0;
135812   int iLangVal = 0;               /* Language id to query */
135813 
135814   int iEq = -1;                   /* Index of term=? value in apVal */
135815   int iGe = -1;                   /* Index of term>=? value in apVal */
135816   int iLe = -1;                   /* Index of term<=? value in apVal */
135817   int iLangid = -1;               /* Index of languageid=? value in apVal */
135818   int iNext = 0;
135819 
135820   UNUSED_PARAMETER(nVal);
135821   UNUSED_PARAMETER(idxStr);
135822 
135823   assert( idxStr==0 );
135824   assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
135825        || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
135826        || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
135827   );
135828 
135829   if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
135830     iEq = iNext++;
135831   }else{
135832     isScan = 1;
135833     if( idxNum & FTS4AUX_GE_CONSTRAINT ){
135834       iGe = iNext++;
135835     }
135836     if( idxNum & FTS4AUX_LE_CONSTRAINT ){
135837       iLe = iNext++;
135838     }
135839   }
135840   if( iNext<nVal ){
135841     iLangid = iNext++;
135842   }
135843 
135844   /* In case this cursor is being reused, close and zero it. */
135845   testcase(pCsr->filter.zTerm);
135846   sqlite3Fts3SegReaderFinish(&pCsr->csr);
135847   sqlite3_free((void *)pCsr->filter.zTerm);
135848   sqlite3_free(pCsr->aStat);
135849   memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
135850 
135851   pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
135852   if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
135853 
135854   if( iEq>=0 || iGe>=0 ){
135855     const unsigned char *zStr = sqlite3_value_text(apVal[0]);
135856     assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
135857     if( zStr ){
135858       pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
135859       pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
135860       if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
135861     }
135862   }
135863 
135864   if( iLe>=0 ){
135865     pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
135866     pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
135867     if( pCsr->zStop==0 ) return SQLITE_NOMEM;
135868   }
135869 
135870   if( iLangid>=0 ){
135871     iLangVal = sqlite3_value_int(apVal[iLangid]);
135872 
135873     /* If the user specified a negative value for the languageid, use zero
135874     ** instead. This works, as the "languageid=?" constraint will also
135875     ** be tested by the VDBE layer. The test will always be false (since
135876     ** this module will not return a row with a negative languageid), and
135877     ** so the overall query will return zero rows.  */
135878     if( iLangVal<0 ) iLangVal = 0;
135879   }
135880   pCsr->iLangid = iLangVal;
135881 
135882   rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
135883       pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
135884   );
135885   if( rc==SQLITE_OK ){
135886     rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
135887   }
135888 
135889   if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
135890   return rc;
135891 }
135892 
135893 /*
135894 ** xEof - Return true if the cursor is at EOF, or false otherwise.
135895 */
135896 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
135897   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
135898   return pCsr->isEof;
135899 }
135900 
135901 /*
135902 ** xColumn - Return a column value.
135903 */
135904 static int fts3auxColumnMethod(
135905   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
135906   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
135907   int iCol                        /* Index of column to read value from */
135908 ){
135909   Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
135910 
135911   assert( p->isEof==0 );
135912   switch( iCol ){
135913     case 0: /* term */
135914       sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
135915       break;
135916 
135917     case 1: /* col */
135918       if( p->iCol ){
135919         sqlite3_result_int(pCtx, p->iCol-1);
135920       }else{
135921         sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
135922       }
135923       break;
135924 
135925     case 2: /* documents */
135926       sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
135927       break;
135928 
135929     case 3: /* occurrences */
135930       sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
135931       break;
135932 
135933     default: /* languageid */
135934       assert( iCol==4 );
135935       sqlite3_result_int(pCtx, p->iLangid);
135936       break;
135937   }
135938 
135939   return SQLITE_OK;
135940 }
135941 
135942 /*
135943 ** xRowid - Return the current rowid for the cursor.
135944 */
135945 static int fts3auxRowidMethod(
135946   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
135947   sqlite_int64 *pRowid            /* OUT: Rowid value */
135948 ){
135949   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
135950   *pRowid = pCsr->iRowid;
135951   return SQLITE_OK;
135952 }
135953 
135954 /*
135955 ** Register the fts3aux module with database connection db. Return SQLITE_OK
135956 ** if successful or an error code if sqlite3_create_module() fails.
135957 */
135958 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
135959   static const sqlite3_module fts3aux_module = {
135960      0,                           /* iVersion      */
135961      fts3auxConnectMethod,        /* xCreate       */
135962      fts3auxConnectMethod,        /* xConnect      */
135963      fts3auxBestIndexMethod,      /* xBestIndex    */
135964      fts3auxDisconnectMethod,     /* xDisconnect   */
135965      fts3auxDisconnectMethod,     /* xDestroy      */
135966      fts3auxOpenMethod,           /* xOpen         */
135967      fts3auxCloseMethod,          /* xClose        */
135968      fts3auxFilterMethod,         /* xFilter       */
135969      fts3auxNextMethod,           /* xNext         */
135970      fts3auxEofMethod,            /* xEof          */
135971      fts3auxColumnMethod,         /* xColumn       */
135972      fts3auxRowidMethod,          /* xRowid        */
135973      0,                           /* xUpdate       */
135974      0,                           /* xBegin        */
135975      0,                           /* xSync         */
135976      0,                           /* xCommit       */
135977      0,                           /* xRollback     */
135978      0,                           /* xFindFunction */
135979      0,                           /* xRename       */
135980      0,                           /* xSavepoint    */
135981      0,                           /* xRelease      */
135982      0                            /* xRollbackTo   */
135983   };
135984   int rc;                         /* Return code */
135985 
135986   rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
135987   return rc;
135988 }
135989 
135990 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
135991 
135992 /************** End of fts3_aux.c ********************************************/
135993 /************** Begin file fts3_expr.c ***************************************/
135994 /*
135995 ** 2008 Nov 28
135996 **
135997 ** The author disclaims copyright to this source code.  In place of
135998 ** a legal notice, here is a blessing:
135999 **
136000 **    May you do good and not evil.
136001 **    May you find forgiveness for yourself and forgive others.
136002 **    May you share freely, never taking more than you give.
136003 **
136004 ******************************************************************************
136005 **
136006 ** This module contains code that implements a parser for fts3 query strings
136007 ** (the right-hand argument to the MATCH operator). Because the supported
136008 ** syntax is relatively simple, the whole tokenizer/parser system is
136009 ** hand-coded.
136010 */
136011 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
136012 
136013 /*
136014 ** By default, this module parses the legacy syntax that has been
136015 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
136016 ** is defined, then it uses the new syntax. The differences between
136017 ** the new and the old syntaxes are:
136018 **
136019 **  a) The new syntax supports parenthesis. The old does not.
136020 **
136021 **  b) The new syntax supports the AND and NOT operators. The old does not.
136022 **
136023 **  c) The old syntax supports the "-" token qualifier. This is not
136024 **     supported by the new syntax (it is replaced by the NOT operator).
136025 **
136026 **  d) When using the old syntax, the OR operator has a greater precedence
136027 **     than an implicit AND. When using the new, both implicity and explicit
136028 **     AND operators have a higher precedence than OR.
136029 **
136030 ** If compiled with SQLITE_TEST defined, then this module exports the
136031 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
136032 ** to zero causes the module to use the old syntax. If it is set to
136033 ** non-zero the new syntax is activated. This is so both syntaxes can
136034 ** be tested using a single build of testfixture.
136035 **
136036 ** The following describes the syntax supported by the fts3 MATCH
136037 ** operator in a similar format to that used by the lemon parser
136038 ** generator. This module does not use actually lemon, it uses a
136039 ** custom parser.
136040 **
136041 **   query ::= andexpr (OR andexpr)*.
136042 **
136043 **   andexpr ::= notexpr (AND? notexpr)*.
136044 **
136045 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
136046 **   notexpr ::= LP query RP.
136047 **
136048 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
136049 **
136050 **   distance_opt ::= .
136051 **   distance_opt ::= / INTEGER.
136052 **
136053 **   phrase ::= TOKEN.
136054 **   phrase ::= COLUMN:TOKEN.
136055 **   phrase ::= "TOKEN TOKEN TOKEN...".
136056 */
136057 
136058 #ifdef SQLITE_TEST
136059 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
136060 #else
136061 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
136062 #  define sqlite3_fts3_enable_parentheses 1
136063 # else
136064 #  define sqlite3_fts3_enable_parentheses 0
136065 # endif
136066 #endif
136067 
136068 /*
136069 ** Default span for NEAR operators.
136070 */
136071 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
136072 
136073 /* #include <string.h> */
136074 /* #include <assert.h> */
136075 
136076 /*
136077 ** isNot:
136078 **   This variable is used by function getNextNode(). When getNextNode() is
136079 **   called, it sets ParseContext.isNot to true if the 'next node' is a
136080 **   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
136081 **   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
136082 **   zero.
136083 */
136084 typedef struct ParseContext ParseContext;
136085 struct ParseContext {
136086   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
136087   int iLangid;                        /* Language id used with tokenizer */
136088   const char **azCol;                 /* Array of column names for fts3 table */
136089   int bFts4;                          /* True to allow FTS4-only syntax */
136090   int nCol;                           /* Number of entries in azCol[] */
136091   int iDefaultCol;                    /* Default column to query */
136092   int isNot;                          /* True if getNextNode() sees a unary - */
136093   sqlite3_context *pCtx;              /* Write error message here */
136094   int nNest;                          /* Number of nested brackets */
136095 };
136096 
136097 /*
136098 ** This function is equivalent to the standard isspace() function.
136099 **
136100 ** The standard isspace() can be awkward to use safely, because although it
136101 ** is defined to accept an argument of type int, its behavior when passed
136102 ** an integer that falls outside of the range of the unsigned char type
136103 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
136104 ** is defined to accept an argument of type char, and always returns 0 for
136105 ** any values that fall outside of the range of the unsigned char type (i.e.
136106 ** negative values).
136107 */
136108 static int fts3isspace(char c){
136109   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
136110 }
136111 
136112 /*
136113 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
136114 ** zero the memory before returning a pointer to it. If unsuccessful,
136115 ** return NULL.
136116 */
136117 static void *fts3MallocZero(int nByte){
136118   void *pRet = sqlite3_malloc(nByte);
136119   if( pRet ) memset(pRet, 0, nByte);
136120   return pRet;
136121 }
136122 
136123 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
136124   sqlite3_tokenizer *pTokenizer,
136125   int iLangid,
136126   const char *z,
136127   int n,
136128   sqlite3_tokenizer_cursor **ppCsr
136129 ){
136130   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
136131   sqlite3_tokenizer_cursor *pCsr = 0;
136132   int rc;
136133 
136134   rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
136135   assert( rc==SQLITE_OK || pCsr==0 );
136136   if( rc==SQLITE_OK ){
136137     pCsr->pTokenizer = pTokenizer;
136138     if( pModule->iVersion>=1 ){
136139       rc = pModule->xLanguageid(pCsr, iLangid);
136140       if( rc!=SQLITE_OK ){
136141         pModule->xClose(pCsr);
136142         pCsr = 0;
136143       }
136144     }
136145   }
136146   *ppCsr = pCsr;
136147   return rc;
136148 }
136149 
136150 /*
136151 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
136152 ** call fts3ExprParse(). So this forward declaration is required.
136153 */
136154 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
136155 
136156 /*
136157 ** Extract the next token from buffer z (length n) using the tokenizer
136158 ** and other information (column names etc.) in pParse. Create an Fts3Expr
136159 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
136160 ** single token and set *ppExpr to point to it. If the end of the buffer is
136161 ** reached before a token is found, set *ppExpr to zero. It is the
136162 ** responsibility of the caller to eventually deallocate the allocated
136163 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
136164 **
136165 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
136166 ** fails.
136167 */
136168 static int getNextToken(
136169   ParseContext *pParse,                   /* fts3 query parse context */
136170   int iCol,                               /* Value for Fts3Phrase.iColumn */
136171   const char *z, int n,                   /* Input string */
136172   Fts3Expr **ppExpr,                      /* OUT: expression */
136173   int *pnConsumed                         /* OUT: Number of bytes consumed */
136174 ){
136175   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
136176   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
136177   int rc;
136178   sqlite3_tokenizer_cursor *pCursor;
136179   Fts3Expr *pRet = 0;
136180   int i = 0;
136181 
136182   /* Set variable i to the maximum number of bytes of input to tokenize. */
136183   for(i=0; i<n; i++){
136184     if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
136185     if( z[i]=='"' ) break;
136186   }
136187 
136188   *pnConsumed = i;
136189   rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
136190   if( rc==SQLITE_OK ){
136191     const char *zToken;
136192     int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
136193     int nByte;                               /* total space to allocate */
136194 
136195     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
136196     if( rc==SQLITE_OK ){
136197       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
136198       pRet = (Fts3Expr *)fts3MallocZero(nByte);
136199       if( !pRet ){
136200         rc = SQLITE_NOMEM;
136201       }else{
136202         pRet->eType = FTSQUERY_PHRASE;
136203         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
136204         pRet->pPhrase->nToken = 1;
136205         pRet->pPhrase->iColumn = iCol;
136206         pRet->pPhrase->aToken[0].n = nToken;
136207         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
136208         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
136209 
136210         if( iEnd<n && z[iEnd]=='*' ){
136211           pRet->pPhrase->aToken[0].isPrefix = 1;
136212           iEnd++;
136213         }
136214 
136215         while( 1 ){
136216           if( !sqlite3_fts3_enable_parentheses
136217            && iStart>0 && z[iStart-1]=='-'
136218           ){
136219             pParse->isNot = 1;
136220             iStart--;
136221           }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
136222             pRet->pPhrase->aToken[0].bFirst = 1;
136223             iStart--;
136224           }else{
136225             break;
136226           }
136227         }
136228 
136229       }
136230       *pnConsumed = iEnd;
136231     }else if( i && rc==SQLITE_DONE ){
136232       rc = SQLITE_OK;
136233     }
136234 
136235     pModule->xClose(pCursor);
136236   }
136237 
136238   *ppExpr = pRet;
136239   return rc;
136240 }
136241 
136242 
136243 /*
136244 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
136245 ** then free the old allocation.
136246 */
136247 static void *fts3ReallocOrFree(void *pOrig, int nNew){
136248   void *pRet = sqlite3_realloc(pOrig, nNew);
136249   if( !pRet ){
136250     sqlite3_free(pOrig);
136251   }
136252   return pRet;
136253 }
136254 
136255 /*
136256 ** Buffer zInput, length nInput, contains the contents of a quoted string
136257 ** that appeared as part of an fts3 query expression. Neither quote character
136258 ** is included in the buffer. This function attempts to tokenize the entire
136259 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
136260 ** containing the results.
136261 **
136262 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
136263 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
136264 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
136265 ** to 0.
136266 */
136267 static int getNextString(
136268   ParseContext *pParse,                   /* fts3 query parse context */
136269   const char *zInput, int nInput,         /* Input string */
136270   Fts3Expr **ppExpr                       /* OUT: expression */
136271 ){
136272   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
136273   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
136274   int rc;
136275   Fts3Expr *p = 0;
136276   sqlite3_tokenizer_cursor *pCursor = 0;
136277   char *zTemp = 0;
136278   int nTemp = 0;
136279 
136280   const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
136281   int nToken = 0;
136282 
136283   /* The final Fts3Expr data structure, including the Fts3Phrase,
136284   ** Fts3PhraseToken structures token buffers are all stored as a single
136285   ** allocation so that the expression can be freed with a single call to
136286   ** sqlite3_free(). Setting this up requires a two pass approach.
136287   **
136288   ** The first pass, in the block below, uses a tokenizer cursor to iterate
136289   ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
136290   ** to assemble data in two dynamic buffers:
136291   **
136292   **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
136293   **             structure, followed by the array of Fts3PhraseToken
136294   **             structures. This pass only populates the Fts3PhraseToken array.
136295   **
136296   **   Buffer zTemp: Contains copies of all tokens.
136297   **
136298   ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
136299   ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
136300   ** structures.
136301   */
136302   rc = sqlite3Fts3OpenTokenizer(
136303       pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
136304   if( rc==SQLITE_OK ){
136305     int ii;
136306     for(ii=0; rc==SQLITE_OK; ii++){
136307       const char *zByte;
136308       int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
136309       rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
136310       if( rc==SQLITE_OK ){
136311         Fts3PhraseToken *pToken;
136312 
136313         p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
136314         if( !p ) goto no_mem;
136315 
136316         zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
136317         if( !zTemp ) goto no_mem;
136318 
136319         assert( nToken==ii );
136320         pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
136321         memset(pToken, 0, sizeof(Fts3PhraseToken));
136322 
136323         memcpy(&zTemp[nTemp], zByte, nByte);
136324         nTemp += nByte;
136325 
136326         pToken->n = nByte;
136327         pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
136328         pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
136329         nToken = ii+1;
136330       }
136331     }
136332 
136333     pModule->xClose(pCursor);
136334     pCursor = 0;
136335   }
136336 
136337   if( rc==SQLITE_DONE ){
136338     int jj;
136339     char *zBuf = 0;
136340 
136341     p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
136342     if( !p ) goto no_mem;
136343     memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
136344     p->eType = FTSQUERY_PHRASE;
136345     p->pPhrase = (Fts3Phrase *)&p[1];
136346     p->pPhrase->iColumn = pParse->iDefaultCol;
136347     p->pPhrase->nToken = nToken;
136348 
136349     zBuf = (char *)&p->pPhrase->aToken[nToken];
136350     if( zTemp ){
136351       memcpy(zBuf, zTemp, nTemp);
136352       sqlite3_free(zTemp);
136353     }else{
136354       assert( nTemp==0 );
136355     }
136356 
136357     for(jj=0; jj<p->pPhrase->nToken; jj++){
136358       p->pPhrase->aToken[jj].z = zBuf;
136359       zBuf += p->pPhrase->aToken[jj].n;
136360     }
136361     rc = SQLITE_OK;
136362   }
136363 
136364   *ppExpr = p;
136365   return rc;
136366 no_mem:
136367 
136368   if( pCursor ){
136369     pModule->xClose(pCursor);
136370   }
136371   sqlite3_free(zTemp);
136372   sqlite3_free(p);
136373   *ppExpr = 0;
136374   return SQLITE_NOMEM;
136375 }
136376 
136377 /*
136378 ** The output variable *ppExpr is populated with an allocated Fts3Expr
136379 ** structure, or set to 0 if the end of the input buffer is reached.
136380 **
136381 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
136382 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
136383 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
136384 */
136385 static int getNextNode(
136386   ParseContext *pParse,                   /* fts3 query parse context */
136387   const char *z, int n,                   /* Input string */
136388   Fts3Expr **ppExpr,                      /* OUT: expression */
136389   int *pnConsumed                         /* OUT: Number of bytes consumed */
136390 ){
136391   static const struct Fts3Keyword {
136392     char *z;                              /* Keyword text */
136393     unsigned char n;                      /* Length of the keyword */
136394     unsigned char parenOnly;              /* Only valid in paren mode */
136395     unsigned char eType;                  /* Keyword code */
136396   } aKeyword[] = {
136397     { "OR" ,  2, 0, FTSQUERY_OR   },
136398     { "AND",  3, 1, FTSQUERY_AND  },
136399     { "NOT",  3, 1, FTSQUERY_NOT  },
136400     { "NEAR", 4, 0, FTSQUERY_NEAR }
136401   };
136402   int ii;
136403   int iCol;
136404   int iColLen;
136405   int rc;
136406   Fts3Expr *pRet = 0;
136407 
136408   const char *zInput = z;
136409   int nInput = n;
136410 
136411   pParse->isNot = 0;
136412 
136413   /* Skip over any whitespace before checking for a keyword, an open or
136414   ** close bracket, or a quoted string.
136415   */
136416   while( nInput>0 && fts3isspace(*zInput) ){
136417     nInput--;
136418     zInput++;
136419   }
136420   if( nInput==0 ){
136421     return SQLITE_DONE;
136422   }
136423 
136424   /* See if we are dealing with a keyword. */
136425   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
136426     const struct Fts3Keyword *pKey = &aKeyword[ii];
136427 
136428     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
136429       continue;
136430     }
136431 
136432     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
136433       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
136434       int nKey = pKey->n;
136435       char cNext;
136436 
136437       /* If this is a "NEAR" keyword, check for an explicit nearness. */
136438       if( pKey->eType==FTSQUERY_NEAR ){
136439         assert( nKey==4 );
136440         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
136441           nNear = 0;
136442           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
136443             nNear = nNear * 10 + (zInput[nKey] - '0');
136444           }
136445         }
136446       }
136447 
136448       /* At this point this is probably a keyword. But for that to be true,
136449       ** the next byte must contain either whitespace, an open or close
136450       ** parenthesis, a quote character, or EOF.
136451       */
136452       cNext = zInput[nKey];
136453       if( fts3isspace(cNext)
136454        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
136455       ){
136456         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
136457         if( !pRet ){
136458           return SQLITE_NOMEM;
136459         }
136460         pRet->eType = pKey->eType;
136461         pRet->nNear = nNear;
136462         *ppExpr = pRet;
136463         *pnConsumed = (int)((zInput - z) + nKey);
136464         return SQLITE_OK;
136465       }
136466 
136467       /* Turns out that wasn't a keyword after all. This happens if the
136468       ** user has supplied a token such as "ORacle". Continue.
136469       */
136470     }
136471   }
136472 
136473   /* See if we are dealing with a quoted phrase. If this is the case, then
136474   ** search for the closing quote and pass the whole string to getNextString()
136475   ** for processing. This is easy to do, as fts3 has no syntax for escaping
136476   ** a quote character embedded in a string.
136477   */
136478   if( *zInput=='"' ){
136479     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
136480     *pnConsumed = (int)((zInput - z) + ii + 1);
136481     if( ii==nInput ){
136482       return SQLITE_ERROR;
136483     }
136484     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
136485   }
136486 
136487   if( sqlite3_fts3_enable_parentheses ){
136488     if( *zInput=='(' ){
136489       int nConsumed = 0;
136490       pParse->nNest++;
136491       rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
136492       if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
136493       *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
136494       return rc;
136495     }else if( *zInput==')' ){
136496       pParse->nNest--;
136497       *pnConsumed = (int)((zInput - z) + 1);
136498       *ppExpr = 0;
136499       return SQLITE_DONE;
136500     }
136501   }
136502 
136503   /* If control flows to this point, this must be a regular token, or
136504   ** the end of the input. Read a regular token using the sqlite3_tokenizer
136505   ** interface. Before doing so, figure out if there is an explicit
136506   ** column specifier for the token.
136507   **
136508   ** TODO: Strangely, it is not possible to associate a column specifier
136509   ** with a quoted phrase, only with a single token. Not sure if this was
136510   ** an implementation artifact or an intentional decision when fts3 was
136511   ** first implemented. Whichever it was, this module duplicates the
136512   ** limitation.
136513   */
136514   iCol = pParse->iDefaultCol;
136515   iColLen = 0;
136516   for(ii=0; ii<pParse->nCol; ii++){
136517     const char *zStr = pParse->azCol[ii];
136518     int nStr = (int)strlen(zStr);
136519     if( nInput>nStr && zInput[nStr]==':'
136520      && sqlite3_strnicmp(zStr, zInput, nStr)==0
136521     ){
136522       iCol = ii;
136523       iColLen = (int)((zInput - z) + nStr + 1);
136524       break;
136525     }
136526   }
136527   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
136528   *pnConsumed += iColLen;
136529   return rc;
136530 }
136531 
136532 /*
136533 ** The argument is an Fts3Expr structure for a binary operator (any type
136534 ** except an FTSQUERY_PHRASE). Return an integer value representing the
136535 ** precedence of the operator. Lower values have a higher precedence (i.e.
136536 ** group more tightly). For example, in the C language, the == operator
136537 ** groups more tightly than ||, and would therefore have a higher precedence.
136538 **
136539 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
136540 ** is defined), the order of the operators in precedence from highest to
136541 ** lowest is:
136542 **
136543 **   NEAR
136544 **   NOT
136545 **   AND (including implicit ANDs)
136546 **   OR
136547 **
136548 ** Note that when using the old query syntax, the OR operator has a higher
136549 ** precedence than the AND operator.
136550 */
136551 static int opPrecedence(Fts3Expr *p){
136552   assert( p->eType!=FTSQUERY_PHRASE );
136553   if( sqlite3_fts3_enable_parentheses ){
136554     return p->eType;
136555   }else if( p->eType==FTSQUERY_NEAR ){
136556     return 1;
136557   }else if( p->eType==FTSQUERY_OR ){
136558     return 2;
136559   }
136560   assert( p->eType==FTSQUERY_AND );
136561   return 3;
136562 }
136563 
136564 /*
136565 ** Argument ppHead contains a pointer to the current head of a query
136566 ** expression tree being parsed. pPrev is the expression node most recently
136567 ** inserted into the tree. This function adds pNew, which is always a binary
136568 ** operator node, into the expression tree based on the relative precedence
136569 ** of pNew and the existing nodes of the tree. This may result in the head
136570 ** of the tree changing, in which case *ppHead is set to the new root node.
136571 */
136572 static void insertBinaryOperator(
136573   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
136574   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
136575   Fts3Expr *pNew           /* New binary node to insert into expression tree */
136576 ){
136577   Fts3Expr *pSplit = pPrev;
136578   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
136579     pSplit = pSplit->pParent;
136580   }
136581 
136582   if( pSplit->pParent ){
136583     assert( pSplit->pParent->pRight==pSplit );
136584     pSplit->pParent->pRight = pNew;
136585     pNew->pParent = pSplit->pParent;
136586   }else{
136587     *ppHead = pNew;
136588   }
136589   pNew->pLeft = pSplit;
136590   pSplit->pParent = pNew;
136591 }
136592 
136593 /*
136594 ** Parse the fts3 query expression found in buffer z, length n. This function
136595 ** returns either when the end of the buffer is reached or an unmatched
136596 ** closing bracket - ')' - is encountered.
136597 **
136598 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
136599 ** parsed form of the expression and *pnConsumed is set to the number of
136600 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
136601 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
136602 */
136603 static int fts3ExprParse(
136604   ParseContext *pParse,                   /* fts3 query parse context */
136605   const char *z, int n,                   /* Text of MATCH query */
136606   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
136607   int *pnConsumed                         /* OUT: Number of bytes consumed */
136608 ){
136609   Fts3Expr *pRet = 0;
136610   Fts3Expr *pPrev = 0;
136611   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
136612   int nIn = n;
136613   const char *zIn = z;
136614   int rc = SQLITE_OK;
136615   int isRequirePhrase = 1;
136616 
136617   while( rc==SQLITE_OK ){
136618     Fts3Expr *p = 0;
136619     int nByte = 0;
136620 
136621     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
136622     assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
136623     if( rc==SQLITE_OK ){
136624       if( p ){
136625         int isPhrase;
136626 
136627         if( !sqlite3_fts3_enable_parentheses
136628             && p->eType==FTSQUERY_PHRASE && pParse->isNot
136629         ){
136630           /* Create an implicit NOT operator. */
136631           Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
136632           if( !pNot ){
136633             sqlite3Fts3ExprFree(p);
136634             rc = SQLITE_NOMEM;
136635             goto exprparse_out;
136636           }
136637           pNot->eType = FTSQUERY_NOT;
136638           pNot->pRight = p;
136639           p->pParent = pNot;
136640           if( pNotBranch ){
136641             pNot->pLeft = pNotBranch;
136642             pNotBranch->pParent = pNot;
136643           }
136644           pNotBranch = pNot;
136645           p = pPrev;
136646         }else{
136647           int eType = p->eType;
136648           isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
136649 
136650           /* The isRequirePhrase variable is set to true if a phrase or
136651           ** an expression contained in parenthesis is required. If a
136652           ** binary operator (AND, OR, NOT or NEAR) is encounted when
136653           ** isRequirePhrase is set, this is a syntax error.
136654           */
136655           if( !isPhrase && isRequirePhrase ){
136656             sqlite3Fts3ExprFree(p);
136657             rc = SQLITE_ERROR;
136658             goto exprparse_out;
136659           }
136660 
136661           if( isPhrase && !isRequirePhrase ){
136662             /* Insert an implicit AND operator. */
136663             Fts3Expr *pAnd;
136664             assert( pRet && pPrev );
136665             pAnd = fts3MallocZero(sizeof(Fts3Expr));
136666             if( !pAnd ){
136667               sqlite3Fts3ExprFree(p);
136668               rc = SQLITE_NOMEM;
136669               goto exprparse_out;
136670             }
136671             pAnd->eType = FTSQUERY_AND;
136672             insertBinaryOperator(&pRet, pPrev, pAnd);
136673             pPrev = pAnd;
136674           }
136675 
136676           /* This test catches attempts to make either operand of a NEAR
136677            ** operator something other than a phrase. For example, either of
136678            ** the following:
136679            **
136680            **    (bracketed expression) NEAR phrase
136681            **    phrase NEAR (bracketed expression)
136682            **
136683            ** Return an error in either case.
136684            */
136685           if( pPrev && (
136686             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
136687          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
136688           )){
136689             sqlite3Fts3ExprFree(p);
136690             rc = SQLITE_ERROR;
136691             goto exprparse_out;
136692           }
136693 
136694           if( isPhrase ){
136695             if( pRet ){
136696               assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
136697               pPrev->pRight = p;
136698               p->pParent = pPrev;
136699             }else{
136700               pRet = p;
136701             }
136702           }else{
136703             insertBinaryOperator(&pRet, pPrev, p);
136704           }
136705           isRequirePhrase = !isPhrase;
136706         }
136707         pPrev = p;
136708       }
136709       assert( nByte>0 );
136710     }
136711     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
136712     nIn -= nByte;
136713     zIn += nByte;
136714   }
136715 
136716   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
136717     rc = SQLITE_ERROR;
136718   }
136719 
136720   if( rc==SQLITE_DONE ){
136721     rc = SQLITE_OK;
136722     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
136723       if( !pRet ){
136724         rc = SQLITE_ERROR;
136725       }else{
136726         Fts3Expr *pIter = pNotBranch;
136727         while( pIter->pLeft ){
136728           pIter = pIter->pLeft;
136729         }
136730         pIter->pLeft = pRet;
136731         pRet->pParent = pIter;
136732         pRet = pNotBranch;
136733       }
136734     }
136735   }
136736   *pnConsumed = n - nIn;
136737 
136738 exprparse_out:
136739   if( rc!=SQLITE_OK ){
136740     sqlite3Fts3ExprFree(pRet);
136741     sqlite3Fts3ExprFree(pNotBranch);
136742     pRet = 0;
136743   }
136744   *ppExpr = pRet;
136745   return rc;
136746 }
136747 
136748 /*
136749 ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
136750 ** as the only argument is more than nMaxDepth.
136751 */
136752 static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
136753   int rc = SQLITE_OK;
136754   if( p ){
136755     if( nMaxDepth<0 ){
136756       rc = SQLITE_TOOBIG;
136757     }else{
136758       rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
136759       if( rc==SQLITE_OK ){
136760         rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
136761       }
136762     }
136763   }
136764   return rc;
136765 }
136766 
136767 /*
136768 ** This function attempts to transform the expression tree at (*pp) to
136769 ** an equivalent but more balanced form. The tree is modified in place.
136770 ** If successful, SQLITE_OK is returned and (*pp) set to point to the
136771 ** new root expression node.
136772 **
136773 ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
136774 **
136775 ** Otherwise, if an error occurs, an SQLite error code is returned and
136776 ** expression (*pp) freed.
136777 */
136778 static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
136779   int rc = SQLITE_OK;             /* Return code */
136780   Fts3Expr *pRoot = *pp;          /* Initial root node */
136781   Fts3Expr *pFree = 0;            /* List of free nodes. Linked by pParent. */
136782   int eType = pRoot->eType;       /* Type of node in this tree */
136783 
136784   if( nMaxDepth==0 ){
136785     rc = SQLITE_ERROR;
136786   }
136787 
136788   if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
136789     Fts3Expr **apLeaf;
136790     apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
136791     if( 0==apLeaf ){
136792       rc = SQLITE_NOMEM;
136793     }else{
136794       memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
136795     }
136796 
136797     if( rc==SQLITE_OK ){
136798       int i;
136799       Fts3Expr *p;
136800 
136801       /* Set $p to point to the left-most leaf in the tree of eType nodes. */
136802       for(p=pRoot; p->eType==eType; p=p->pLeft){
136803         assert( p->pParent==0 || p->pParent->pLeft==p );
136804         assert( p->pLeft && p->pRight );
136805       }
136806 
136807       /* This loop runs once for each leaf in the tree of eType nodes. */
136808       while( 1 ){
136809         int iLvl;
136810         Fts3Expr *pParent = p->pParent;     /* Current parent of p */
136811 
136812         assert( pParent==0 || pParent->pLeft==p );
136813         p->pParent = 0;
136814         if( pParent ){
136815           pParent->pLeft = 0;
136816         }else{
136817           pRoot = 0;
136818         }
136819         rc = fts3ExprBalance(&p, nMaxDepth-1);
136820         if( rc!=SQLITE_OK ) break;
136821 
136822         for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
136823           if( apLeaf[iLvl]==0 ){
136824             apLeaf[iLvl] = p;
136825             p = 0;
136826           }else{
136827             assert( pFree );
136828             pFree->pLeft = apLeaf[iLvl];
136829             pFree->pRight = p;
136830             pFree->pLeft->pParent = pFree;
136831             pFree->pRight->pParent = pFree;
136832 
136833             p = pFree;
136834             pFree = pFree->pParent;
136835             p->pParent = 0;
136836             apLeaf[iLvl] = 0;
136837           }
136838         }
136839         if( p ){
136840           sqlite3Fts3ExprFree(p);
136841           rc = SQLITE_TOOBIG;
136842           break;
136843         }
136844 
136845         /* If that was the last leaf node, break out of the loop */
136846         if( pParent==0 ) break;
136847 
136848         /* Set $p to point to the next leaf in the tree of eType nodes */
136849         for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
136850 
136851         /* Remove pParent from the original tree. */
136852         assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
136853         pParent->pRight->pParent = pParent->pParent;
136854         if( pParent->pParent ){
136855           pParent->pParent->pLeft = pParent->pRight;
136856         }else{
136857           assert( pParent==pRoot );
136858           pRoot = pParent->pRight;
136859         }
136860 
136861         /* Link pParent into the free node list. It will be used as an
136862         ** internal node of the new tree.  */
136863         pParent->pParent = pFree;
136864         pFree = pParent;
136865       }
136866 
136867       if( rc==SQLITE_OK ){
136868         p = 0;
136869         for(i=0; i<nMaxDepth; i++){
136870           if( apLeaf[i] ){
136871             if( p==0 ){
136872               p = apLeaf[i];
136873               p->pParent = 0;
136874             }else{
136875               assert( pFree!=0 );
136876               pFree->pRight = p;
136877               pFree->pLeft = apLeaf[i];
136878               pFree->pLeft->pParent = pFree;
136879               pFree->pRight->pParent = pFree;
136880 
136881               p = pFree;
136882               pFree = pFree->pParent;
136883               p->pParent = 0;
136884             }
136885           }
136886         }
136887         pRoot = p;
136888       }else{
136889         /* An error occurred. Delete the contents of the apLeaf[] array
136890         ** and pFree list. Everything else is cleaned up by the call to
136891         ** sqlite3Fts3ExprFree(pRoot) below.  */
136892         Fts3Expr *pDel;
136893         for(i=0; i<nMaxDepth; i++){
136894           sqlite3Fts3ExprFree(apLeaf[i]);
136895         }
136896         while( (pDel=pFree)!=0 ){
136897           pFree = pDel->pParent;
136898           sqlite3_free(pDel);
136899         }
136900       }
136901 
136902       assert( pFree==0 );
136903       sqlite3_free( apLeaf );
136904     }
136905   }
136906 
136907   if( rc!=SQLITE_OK ){
136908     sqlite3Fts3ExprFree(pRoot);
136909     pRoot = 0;
136910   }
136911   *pp = pRoot;
136912   return rc;
136913 }
136914 
136915 /*
136916 ** This function is similar to sqlite3Fts3ExprParse(), with the following
136917 ** differences:
136918 **
136919 **   1. It does not do expression rebalancing.
136920 **   2. It does not check that the expression does not exceed the
136921 **      maximum allowable depth.
136922 **   3. Even if it fails, *ppExpr may still be set to point to an
136923 **      expression tree. It should be deleted using sqlite3Fts3ExprFree()
136924 **      in this case.
136925 */
136926 static int fts3ExprParseUnbalanced(
136927   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
136928   int iLangid,                        /* Language id for tokenizer */
136929   char **azCol,                       /* Array of column names for fts3 table */
136930   int bFts4,                          /* True to allow FTS4-only syntax */
136931   int nCol,                           /* Number of entries in azCol[] */
136932   int iDefaultCol,                    /* Default column to query */
136933   const char *z, int n,               /* Text of MATCH query */
136934   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
136935 ){
136936   int nParsed;
136937   int rc;
136938   ParseContext sParse;
136939 
136940   memset(&sParse, 0, sizeof(ParseContext));
136941   sParse.pTokenizer = pTokenizer;
136942   sParse.iLangid = iLangid;
136943   sParse.azCol = (const char **)azCol;
136944   sParse.nCol = nCol;
136945   sParse.iDefaultCol = iDefaultCol;
136946   sParse.bFts4 = bFts4;
136947   if( z==0 ){
136948     *ppExpr = 0;
136949     return SQLITE_OK;
136950   }
136951   if( n<0 ){
136952     n = (int)strlen(z);
136953   }
136954   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
136955   assert( rc==SQLITE_OK || *ppExpr==0 );
136956 
136957   /* Check for mismatched parenthesis */
136958   if( rc==SQLITE_OK && sParse.nNest ){
136959     rc = SQLITE_ERROR;
136960   }
136961 
136962   return rc;
136963 }
136964 
136965 /*
136966 ** Parameters z and n contain a pointer to and length of a buffer containing
136967 ** an fts3 query expression, respectively. This function attempts to parse the
136968 ** query expression and create a tree of Fts3Expr structures representing the
136969 ** parsed expression. If successful, *ppExpr is set to point to the head
136970 ** of the parsed expression tree and SQLITE_OK is returned. If an error
136971 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
136972 ** error) is returned and *ppExpr is set to 0.
136973 **
136974 ** If parameter n is a negative number, then z is assumed to point to a
136975 ** nul-terminated string and the length is determined using strlen().
136976 **
136977 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
136978 ** use to normalize query tokens while parsing the expression. The azCol[]
136979 ** array, which is assumed to contain nCol entries, should contain the names
136980 ** of each column in the target fts3 table, in order from left to right.
136981 ** Column names must be nul-terminated strings.
136982 **
136983 ** The iDefaultCol parameter should be passed the index of the table column
136984 ** that appears on the left-hand-side of the MATCH operator (the default
136985 ** column to match against for tokens for which a column name is not explicitly
136986 ** specified as part of the query string), or -1 if tokens may by default
136987 ** match any table column.
136988 */
136989 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
136990   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
136991   int iLangid,                        /* Language id for tokenizer */
136992   char **azCol,                       /* Array of column names for fts3 table */
136993   int bFts4,                          /* True to allow FTS4-only syntax */
136994   int nCol,                           /* Number of entries in azCol[] */
136995   int iDefaultCol,                    /* Default column to query */
136996   const char *z, int n,               /* Text of MATCH query */
136997   Fts3Expr **ppExpr,                  /* OUT: Parsed query structure */
136998   char **pzErr                        /* OUT: Error message (sqlite3_malloc) */
136999 ){
137000   int rc = fts3ExprParseUnbalanced(
137001       pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
137002   );
137003 
137004   /* Rebalance the expression. And check that its depth does not exceed
137005   ** SQLITE_FTS3_MAX_EXPR_DEPTH.  */
137006   if( rc==SQLITE_OK && *ppExpr ){
137007     rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
137008     if( rc==SQLITE_OK ){
137009       rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
137010     }
137011   }
137012 
137013   if( rc!=SQLITE_OK ){
137014     sqlite3Fts3ExprFree(*ppExpr);
137015     *ppExpr = 0;
137016     if( rc==SQLITE_TOOBIG ){
137017       *pzErr = sqlite3_mprintf(
137018           "FTS expression tree is too large (maximum depth %d)",
137019           SQLITE_FTS3_MAX_EXPR_DEPTH
137020       );
137021       rc = SQLITE_ERROR;
137022     }else if( rc==SQLITE_ERROR ){
137023       *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
137024     }
137025   }
137026 
137027   return rc;
137028 }
137029 
137030 /*
137031 ** Free a single node of an expression tree.
137032 */
137033 static void fts3FreeExprNode(Fts3Expr *p){
137034   assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
137035   sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
137036   sqlite3_free(p->aMI);
137037   sqlite3_free(p);
137038 }
137039 
137040 /*
137041 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
137042 **
137043 ** This function would be simpler if it recursively called itself. But
137044 ** that would mean passing a sufficiently large expression to ExprParse()
137045 ** could cause a stack overflow.
137046 */
137047 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
137048   Fts3Expr *p;
137049   assert( pDel==0 || pDel->pParent==0 );
137050   for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
137051     assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
137052   }
137053   while( p ){
137054     Fts3Expr *pParent = p->pParent;
137055     fts3FreeExprNode(p);
137056     if( pParent && p==pParent->pLeft && pParent->pRight ){
137057       p = pParent->pRight;
137058       while( p && (p->pLeft || p->pRight) ){
137059         assert( p==p->pParent->pRight || p==p->pParent->pLeft );
137060         p = (p->pLeft ? p->pLeft : p->pRight);
137061       }
137062     }else{
137063       p = pParent;
137064     }
137065   }
137066 }
137067 
137068 /****************************************************************************
137069 *****************************************************************************
137070 ** Everything after this point is just test code.
137071 */
137072 
137073 #ifdef SQLITE_TEST
137074 
137075 /* #include <stdio.h> */
137076 
137077 /*
137078 ** Function to query the hash-table of tokenizers (see README.tokenizers).
137079 */
137080 static int queryTestTokenizer(
137081   sqlite3 *db,
137082   const char *zName,
137083   const sqlite3_tokenizer_module **pp
137084 ){
137085   int rc;
137086   sqlite3_stmt *pStmt;
137087   const char zSql[] = "SELECT fts3_tokenizer(?)";
137088 
137089   *pp = 0;
137090   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
137091   if( rc!=SQLITE_OK ){
137092     return rc;
137093   }
137094 
137095   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
137096   if( SQLITE_ROW==sqlite3_step(pStmt) ){
137097     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
137098       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
137099     }
137100   }
137101 
137102   return sqlite3_finalize(pStmt);
137103 }
137104 
137105 /*
137106 ** Return a pointer to a buffer containing a text representation of the
137107 ** expression passed as the first argument. The buffer is obtained from
137108 ** sqlite3_malloc(). It is the responsibility of the caller to use
137109 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
137110 ** NULL is returned.
137111 **
137112 ** If the second argument is not NULL, then its contents are prepended to
137113 ** the returned expression text and then freed using sqlite3_free().
137114 */
137115 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
137116   if( pExpr==0 ){
137117     return sqlite3_mprintf("");
137118   }
137119   switch( pExpr->eType ){
137120     case FTSQUERY_PHRASE: {
137121       Fts3Phrase *pPhrase = pExpr->pPhrase;
137122       int i;
137123       zBuf = sqlite3_mprintf(
137124           "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
137125       for(i=0; zBuf && i<pPhrase->nToken; i++){
137126         zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
137127             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
137128             (pPhrase->aToken[i].isPrefix?"+":"")
137129         );
137130       }
137131       return zBuf;
137132     }
137133 
137134     case FTSQUERY_NEAR:
137135       zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
137136       break;
137137     case FTSQUERY_NOT:
137138       zBuf = sqlite3_mprintf("%zNOT ", zBuf);
137139       break;
137140     case FTSQUERY_AND:
137141       zBuf = sqlite3_mprintf("%zAND ", zBuf);
137142       break;
137143     case FTSQUERY_OR:
137144       zBuf = sqlite3_mprintf("%zOR ", zBuf);
137145       break;
137146   }
137147 
137148   if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
137149   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
137150   if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
137151 
137152   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
137153   if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
137154 
137155   return zBuf;
137156 }
137157 
137158 /*
137159 ** This is the implementation of a scalar SQL function used to test the
137160 ** expression parser. It should be called as follows:
137161 **
137162 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
137163 **
137164 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
137165 ** to parse the query expression (see README.tokenizers). The second argument
137166 ** is the query expression to parse. Each subsequent argument is the name
137167 ** of a column of the fts3 table that the query expression may refer to.
137168 ** For example:
137169 **
137170 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
137171 */
137172 static void fts3ExprTest(
137173   sqlite3_context *context,
137174   int argc,
137175   sqlite3_value **argv
137176 ){
137177   sqlite3_tokenizer_module const *pModule = 0;
137178   sqlite3_tokenizer *pTokenizer = 0;
137179   int rc;
137180   char **azCol = 0;
137181   const char *zExpr;
137182   int nExpr;
137183   int nCol;
137184   int ii;
137185   Fts3Expr *pExpr;
137186   char *zBuf = 0;
137187   sqlite3 *db = sqlite3_context_db_handle(context);
137188 
137189   if( argc<3 ){
137190     sqlite3_result_error(context,
137191         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
137192     );
137193     return;
137194   }
137195 
137196   rc = queryTestTokenizer(db,
137197                           (const char *)sqlite3_value_text(argv[0]), &pModule);
137198   if( rc==SQLITE_NOMEM ){
137199     sqlite3_result_error_nomem(context);
137200     goto exprtest_out;
137201   }else if( !pModule ){
137202     sqlite3_result_error(context, "No such tokenizer module", -1);
137203     goto exprtest_out;
137204   }
137205 
137206   rc = pModule->xCreate(0, 0, &pTokenizer);
137207   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
137208   if( rc==SQLITE_NOMEM ){
137209     sqlite3_result_error_nomem(context);
137210     goto exprtest_out;
137211   }
137212   pTokenizer->pModule = pModule;
137213 
137214   zExpr = (const char *)sqlite3_value_text(argv[1]);
137215   nExpr = sqlite3_value_bytes(argv[1]);
137216   nCol = argc-2;
137217   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
137218   if( !azCol ){
137219     sqlite3_result_error_nomem(context);
137220     goto exprtest_out;
137221   }
137222   for(ii=0; ii<nCol; ii++){
137223     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
137224   }
137225 
137226   if( sqlite3_user_data(context) ){
137227     char *zDummy = 0;
137228     rc = sqlite3Fts3ExprParse(
137229         pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
137230     );
137231     assert( rc==SQLITE_OK || pExpr==0 );
137232     sqlite3_free(zDummy);
137233   }else{
137234     rc = fts3ExprParseUnbalanced(
137235         pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
137236     );
137237   }
137238 
137239   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
137240     sqlite3Fts3ExprFree(pExpr);
137241     sqlite3_result_error(context, "Error parsing expression", -1);
137242   }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
137243     sqlite3_result_error_nomem(context);
137244   }else{
137245     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
137246     sqlite3_free(zBuf);
137247   }
137248 
137249   sqlite3Fts3ExprFree(pExpr);
137250 
137251 exprtest_out:
137252   if( pModule && pTokenizer ){
137253     rc = pModule->xDestroy(pTokenizer);
137254   }
137255   sqlite3_free(azCol);
137256 }
137257 
137258 /*
137259 ** Register the query expression parser test function fts3_exprtest()
137260 ** with database connection db.
137261 */
137262 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
137263   int rc = sqlite3_create_function(
137264       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
137265   );
137266   if( rc==SQLITE_OK ){
137267     rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
137268         -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
137269     );
137270   }
137271   return rc;
137272 }
137273 
137274 #endif
137275 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
137276 
137277 /************** End of fts3_expr.c *******************************************/
137278 /************** Begin file fts3_hash.c ***************************************/
137279 /*
137280 ** 2001 September 22
137281 **
137282 ** The author disclaims copyright to this source code.  In place of
137283 ** a legal notice, here is a blessing:
137284 **
137285 **    May you do good and not evil.
137286 **    May you find forgiveness for yourself and forgive others.
137287 **    May you share freely, never taking more than you give.
137288 **
137289 *************************************************************************
137290 ** This is the implementation of generic hash-tables used in SQLite.
137291 ** We've modified it slightly to serve as a standalone hash table
137292 ** implementation for the full-text indexing module.
137293 */
137294 
137295 /*
137296 ** The code in this file is only compiled if:
137297 **
137298 **     * The FTS3 module is being built as an extension
137299 **       (in which case SQLITE_CORE is not defined), or
137300 **
137301 **     * The FTS3 module is being built into the core of
137302 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
137303 */
137304 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
137305 
137306 /* #include <assert.h> */
137307 /* #include <stdlib.h> */
137308 /* #include <string.h> */
137309 
137310 
137311 /*
137312 ** Malloc and Free functions
137313 */
137314 static void *fts3HashMalloc(int n){
137315   void *p = sqlite3_malloc(n);
137316   if( p ){
137317     memset(p, 0, n);
137318   }
137319   return p;
137320 }
137321 static void fts3HashFree(void *p){
137322   sqlite3_free(p);
137323 }
137324 
137325 /* Turn bulk memory into a hash table object by initializing the
137326 ** fields of the Hash structure.
137327 **
137328 ** "pNew" is a pointer to the hash table that is to be initialized.
137329 ** keyClass is one of the constants
137330 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
137331 ** determines what kind of key the hash table will use.  "copyKey" is
137332 ** true if the hash table should make its own private copy of keys and
137333 ** false if it should just use the supplied pointer.
137334 */
137335 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
137336   assert( pNew!=0 );
137337   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
137338   pNew->keyClass = keyClass;
137339   pNew->copyKey = copyKey;
137340   pNew->first = 0;
137341   pNew->count = 0;
137342   pNew->htsize = 0;
137343   pNew->ht = 0;
137344 }
137345 
137346 /* Remove all entries from a hash table.  Reclaim all memory.
137347 ** Call this routine to delete a hash table or to reset a hash table
137348 ** to the empty state.
137349 */
137350 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
137351   Fts3HashElem *elem;         /* For looping over all elements of the table */
137352 
137353   assert( pH!=0 );
137354   elem = pH->first;
137355   pH->first = 0;
137356   fts3HashFree(pH->ht);
137357   pH->ht = 0;
137358   pH->htsize = 0;
137359   while( elem ){
137360     Fts3HashElem *next_elem = elem->next;
137361     if( pH->copyKey && elem->pKey ){
137362       fts3HashFree(elem->pKey);
137363     }
137364     fts3HashFree(elem);
137365     elem = next_elem;
137366   }
137367   pH->count = 0;
137368 }
137369 
137370 /*
137371 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
137372 */
137373 static int fts3StrHash(const void *pKey, int nKey){
137374   const char *z = (const char *)pKey;
137375   unsigned h = 0;
137376   if( nKey<=0 ) nKey = (int) strlen(z);
137377   while( nKey > 0  ){
137378     h = (h<<3) ^ h ^ *z++;
137379     nKey--;
137380   }
137381   return (int)(h & 0x7fffffff);
137382 }
137383 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
137384   if( n1!=n2 ) return 1;
137385   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
137386 }
137387 
137388 /*
137389 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
137390 */
137391 static int fts3BinHash(const void *pKey, int nKey){
137392   int h = 0;
137393   const char *z = (const char *)pKey;
137394   while( nKey-- > 0 ){
137395     h = (h<<3) ^ h ^ *(z++);
137396   }
137397   return h & 0x7fffffff;
137398 }
137399 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
137400   if( n1!=n2 ) return 1;
137401   return memcmp(pKey1,pKey2,n1);
137402 }
137403 
137404 /*
137405 ** Return a pointer to the appropriate hash function given the key class.
137406 **
137407 ** The C syntax in this function definition may be unfamilar to some
137408 ** programmers, so we provide the following additional explanation:
137409 **
137410 ** The name of the function is "ftsHashFunction".  The function takes a
137411 ** single parameter "keyClass".  The return value of ftsHashFunction()
137412 ** is a pointer to another function.  Specifically, the return value
137413 ** of ftsHashFunction() is a pointer to a function that takes two parameters
137414 ** with types "const void*" and "int" and returns an "int".
137415 */
137416 static int (*ftsHashFunction(int keyClass))(const void*,int){
137417   if( keyClass==FTS3_HASH_STRING ){
137418     return &fts3StrHash;
137419   }else{
137420     assert( keyClass==FTS3_HASH_BINARY );
137421     return &fts3BinHash;
137422   }
137423 }
137424 
137425 /*
137426 ** Return a pointer to the appropriate hash function given the key class.
137427 **
137428 ** For help in interpreted the obscure C code in the function definition,
137429 ** see the header comment on the previous function.
137430 */
137431 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
137432   if( keyClass==FTS3_HASH_STRING ){
137433     return &fts3StrCompare;
137434   }else{
137435     assert( keyClass==FTS3_HASH_BINARY );
137436     return &fts3BinCompare;
137437   }
137438 }
137439 
137440 /* Link an element into the hash table
137441 */
137442 static void fts3HashInsertElement(
137443   Fts3Hash *pH,            /* The complete hash table */
137444   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
137445   Fts3HashElem *pNew       /* The element to be inserted */
137446 ){
137447   Fts3HashElem *pHead;     /* First element already in pEntry */
137448   pHead = pEntry->chain;
137449   if( pHead ){
137450     pNew->next = pHead;
137451     pNew->prev = pHead->prev;
137452     if( pHead->prev ){ pHead->prev->next = pNew; }
137453     else             { pH->first = pNew; }
137454     pHead->prev = pNew;
137455   }else{
137456     pNew->next = pH->first;
137457     if( pH->first ){ pH->first->prev = pNew; }
137458     pNew->prev = 0;
137459     pH->first = pNew;
137460   }
137461   pEntry->count++;
137462   pEntry->chain = pNew;
137463 }
137464 
137465 
137466 /* Resize the hash table so that it cantains "new_size" buckets.
137467 ** "new_size" must be a power of 2.  The hash table might fail
137468 ** to resize if sqliteMalloc() fails.
137469 **
137470 ** Return non-zero if a memory allocation error occurs.
137471 */
137472 static int fts3Rehash(Fts3Hash *pH, int new_size){
137473   struct _fts3ht *new_ht;          /* The new hash table */
137474   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
137475   int (*xHash)(const void*,int);   /* The hash function */
137476 
137477   assert( (new_size & (new_size-1))==0 );
137478   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
137479   if( new_ht==0 ) return 1;
137480   fts3HashFree(pH->ht);
137481   pH->ht = new_ht;
137482   pH->htsize = new_size;
137483   xHash = ftsHashFunction(pH->keyClass);
137484   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
137485     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
137486     next_elem = elem->next;
137487     fts3HashInsertElement(pH, &new_ht[h], elem);
137488   }
137489   return 0;
137490 }
137491 
137492 /* This function (for internal use only) locates an element in an
137493 ** hash table that matches the given key.  The hash for this key has
137494 ** already been computed and is passed as the 4th parameter.
137495 */
137496 static Fts3HashElem *fts3FindElementByHash(
137497   const Fts3Hash *pH, /* The pH to be searched */
137498   const void *pKey,   /* The key we are searching for */
137499   int nKey,
137500   int h               /* The hash for this key. */
137501 ){
137502   Fts3HashElem *elem;            /* Used to loop thru the element list */
137503   int count;                     /* Number of elements left to test */
137504   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
137505 
137506   if( pH->ht ){
137507     struct _fts3ht *pEntry = &pH->ht[h];
137508     elem = pEntry->chain;
137509     count = pEntry->count;
137510     xCompare = ftsCompareFunction(pH->keyClass);
137511     while( count-- && elem ){
137512       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
137513         return elem;
137514       }
137515       elem = elem->next;
137516     }
137517   }
137518   return 0;
137519 }
137520 
137521 /* Remove a single entry from the hash table given a pointer to that
137522 ** element and a hash on the element's key.
137523 */
137524 static void fts3RemoveElementByHash(
137525   Fts3Hash *pH,         /* The pH containing "elem" */
137526   Fts3HashElem* elem,   /* The element to be removed from the pH */
137527   int h                 /* Hash value for the element */
137528 ){
137529   struct _fts3ht *pEntry;
137530   if( elem->prev ){
137531     elem->prev->next = elem->next;
137532   }else{
137533     pH->first = elem->next;
137534   }
137535   if( elem->next ){
137536     elem->next->prev = elem->prev;
137537   }
137538   pEntry = &pH->ht[h];
137539   if( pEntry->chain==elem ){
137540     pEntry->chain = elem->next;
137541   }
137542   pEntry->count--;
137543   if( pEntry->count<=0 ){
137544     pEntry->chain = 0;
137545   }
137546   if( pH->copyKey && elem->pKey ){
137547     fts3HashFree(elem->pKey);
137548   }
137549   fts3HashFree( elem );
137550   pH->count--;
137551   if( pH->count<=0 ){
137552     assert( pH->first==0 );
137553     assert( pH->count==0 );
137554     fts3HashClear(pH);
137555   }
137556 }
137557 
137558 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
137559   const Fts3Hash *pH,
137560   const void *pKey,
137561   int nKey
137562 ){
137563   int h;                          /* A hash on key */
137564   int (*xHash)(const void*,int);  /* The hash function */
137565 
137566   if( pH==0 || pH->ht==0 ) return 0;
137567   xHash = ftsHashFunction(pH->keyClass);
137568   assert( xHash!=0 );
137569   h = (*xHash)(pKey,nKey);
137570   assert( (pH->htsize & (pH->htsize-1))==0 );
137571   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
137572 }
137573 
137574 /*
137575 ** Attempt to locate an element of the hash table pH with a key
137576 ** that matches pKey,nKey.  Return the data for this element if it is
137577 ** found, or NULL if there is no match.
137578 */
137579 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
137580   Fts3HashElem *pElem;            /* The element that matches key (if any) */
137581 
137582   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
137583   return pElem ? pElem->data : 0;
137584 }
137585 
137586 /* Insert an element into the hash table pH.  The key is pKey,nKey
137587 ** and the data is "data".
137588 **
137589 ** If no element exists with a matching key, then a new
137590 ** element is created.  A copy of the key is made if the copyKey
137591 ** flag is set.  NULL is returned.
137592 **
137593 ** If another element already exists with the same key, then the
137594 ** new data replaces the old data and the old data is returned.
137595 ** The key is not copied in this instance.  If a malloc fails, then
137596 ** the new data is returned and the hash table is unchanged.
137597 **
137598 ** If the "data" parameter to this function is NULL, then the
137599 ** element corresponding to "key" is removed from the hash table.
137600 */
137601 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
137602   Fts3Hash *pH,        /* The hash table to insert into */
137603   const void *pKey,    /* The key */
137604   int nKey,            /* Number of bytes in the key */
137605   void *data           /* The data */
137606 ){
137607   int hraw;                 /* Raw hash value of the key */
137608   int h;                    /* the hash of the key modulo hash table size */
137609   Fts3HashElem *elem;       /* Used to loop thru the element list */
137610   Fts3HashElem *new_elem;   /* New element added to the pH */
137611   int (*xHash)(const void*,int);  /* The hash function */
137612 
137613   assert( pH!=0 );
137614   xHash = ftsHashFunction(pH->keyClass);
137615   assert( xHash!=0 );
137616   hraw = (*xHash)(pKey, nKey);
137617   assert( (pH->htsize & (pH->htsize-1))==0 );
137618   h = hraw & (pH->htsize-1);
137619   elem = fts3FindElementByHash(pH,pKey,nKey,h);
137620   if( elem ){
137621     void *old_data = elem->data;
137622     if( data==0 ){
137623       fts3RemoveElementByHash(pH,elem,h);
137624     }else{
137625       elem->data = data;
137626     }
137627     return old_data;
137628   }
137629   if( data==0 ) return 0;
137630   if( (pH->htsize==0 && fts3Rehash(pH,8))
137631    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
137632   ){
137633     pH->count = 0;
137634     return data;
137635   }
137636   assert( pH->htsize>0 );
137637   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
137638   if( new_elem==0 ) return data;
137639   if( pH->copyKey && pKey!=0 ){
137640     new_elem->pKey = fts3HashMalloc( nKey );
137641     if( new_elem->pKey==0 ){
137642       fts3HashFree(new_elem);
137643       return data;
137644     }
137645     memcpy((void*)new_elem->pKey, pKey, nKey);
137646   }else{
137647     new_elem->pKey = (void*)pKey;
137648   }
137649   new_elem->nKey = nKey;
137650   pH->count++;
137651   assert( pH->htsize>0 );
137652   assert( (pH->htsize & (pH->htsize-1))==0 );
137653   h = hraw & (pH->htsize-1);
137654   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
137655   new_elem->data = data;
137656   return 0;
137657 }
137658 
137659 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
137660 
137661 /************** End of fts3_hash.c *******************************************/
137662 /************** Begin file fts3_porter.c *************************************/
137663 /*
137664 ** 2006 September 30
137665 **
137666 ** The author disclaims copyright to this source code.  In place of
137667 ** a legal notice, here is a blessing:
137668 **
137669 **    May you do good and not evil.
137670 **    May you find forgiveness for yourself and forgive others.
137671 **    May you share freely, never taking more than you give.
137672 **
137673 *************************************************************************
137674 ** Implementation of the full-text-search tokenizer that implements
137675 ** a Porter stemmer.
137676 */
137677 
137678 /*
137679 ** The code in this file is only compiled if:
137680 **
137681 **     * The FTS3 module is being built as an extension
137682 **       (in which case SQLITE_CORE is not defined), or
137683 **
137684 **     * The FTS3 module is being built into the core of
137685 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
137686 */
137687 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
137688 
137689 /* #include <assert.h> */
137690 /* #include <stdlib.h> */
137691 /* #include <stdio.h> */
137692 /* #include <string.h> */
137693 
137694 
137695 /*
137696 ** Class derived from sqlite3_tokenizer
137697 */
137698 typedef struct porter_tokenizer {
137699   sqlite3_tokenizer base;      /* Base class */
137700 } porter_tokenizer;
137701 
137702 /*
137703 ** Class derived from sqlite3_tokenizer_cursor
137704 */
137705 typedef struct porter_tokenizer_cursor {
137706   sqlite3_tokenizer_cursor base;
137707   const char *zInput;          /* input we are tokenizing */
137708   int nInput;                  /* size of the input */
137709   int iOffset;                 /* current position in zInput */
137710   int iToken;                  /* index of next token to be returned */
137711   char *zToken;                /* storage for current token */
137712   int nAllocated;              /* space allocated to zToken buffer */
137713 } porter_tokenizer_cursor;
137714 
137715 
137716 /*
137717 ** Create a new tokenizer instance.
137718 */
137719 static int porterCreate(
137720   int argc, const char * const *argv,
137721   sqlite3_tokenizer **ppTokenizer
137722 ){
137723   porter_tokenizer *t;
137724 
137725   UNUSED_PARAMETER(argc);
137726   UNUSED_PARAMETER(argv);
137727 
137728   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
137729   if( t==NULL ) return SQLITE_NOMEM;
137730   memset(t, 0, sizeof(*t));
137731   *ppTokenizer = &t->base;
137732   return SQLITE_OK;
137733 }
137734 
137735 /*
137736 ** Destroy a tokenizer
137737 */
137738 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
137739   sqlite3_free(pTokenizer);
137740   return SQLITE_OK;
137741 }
137742 
137743 /*
137744 ** Prepare to begin tokenizing a particular string.  The input
137745 ** string to be tokenized is zInput[0..nInput-1].  A cursor
137746 ** used to incrementally tokenize this string is returned in
137747 ** *ppCursor.
137748 */
137749 static int porterOpen(
137750   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
137751   const char *zInput, int nInput,        /* String to be tokenized */
137752   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
137753 ){
137754   porter_tokenizer_cursor *c;
137755 
137756   UNUSED_PARAMETER(pTokenizer);
137757 
137758   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
137759   if( c==NULL ) return SQLITE_NOMEM;
137760 
137761   c->zInput = zInput;
137762   if( zInput==0 ){
137763     c->nInput = 0;
137764   }else if( nInput<0 ){
137765     c->nInput = (int)strlen(zInput);
137766   }else{
137767     c->nInput = nInput;
137768   }
137769   c->iOffset = 0;                 /* start tokenizing at the beginning */
137770   c->iToken = 0;
137771   c->zToken = NULL;               /* no space allocated, yet. */
137772   c->nAllocated = 0;
137773 
137774   *ppCursor = &c->base;
137775   return SQLITE_OK;
137776 }
137777 
137778 /*
137779 ** Close a tokenization cursor previously opened by a call to
137780 ** porterOpen() above.
137781 */
137782 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
137783   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
137784   sqlite3_free(c->zToken);
137785   sqlite3_free(c);
137786   return SQLITE_OK;
137787 }
137788 /*
137789 ** Vowel or consonant
137790 */
137791 static const char cType[] = {
137792    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
137793    1, 1, 1, 2, 1
137794 };
137795 
137796 /*
137797 ** isConsonant() and isVowel() determine if their first character in
137798 ** the string they point to is a consonant or a vowel, according
137799 ** to Porter ruls.
137800 **
137801 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
137802 ** 'Y' is a consonant unless it follows another consonant,
137803 ** in which case it is a vowel.
137804 **
137805 ** In these routine, the letters are in reverse order.  So the 'y' rule
137806 ** is that 'y' is a consonant unless it is followed by another
137807 ** consonent.
137808 */
137809 static int isVowel(const char*);
137810 static int isConsonant(const char *z){
137811   int j;
137812   char x = *z;
137813   if( x==0 ) return 0;
137814   assert( x>='a' && x<='z' );
137815   j = cType[x-'a'];
137816   if( j<2 ) return j;
137817   return z[1]==0 || isVowel(z + 1);
137818 }
137819 static int isVowel(const char *z){
137820   int j;
137821   char x = *z;
137822   if( x==0 ) return 0;
137823   assert( x>='a' && x<='z' );
137824   j = cType[x-'a'];
137825   if( j<2 ) return 1-j;
137826   return isConsonant(z + 1);
137827 }
137828 
137829 /*
137830 ** Let any sequence of one or more vowels be represented by V and let
137831 ** C be sequence of one or more consonants.  Then every word can be
137832 ** represented as:
137833 **
137834 **           [C] (VC){m} [V]
137835 **
137836 ** In prose:  A word is an optional consonant followed by zero or
137837 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
137838 ** number of vowel consonant pairs.  This routine computes the value
137839 ** of m for the first i bytes of a word.
137840 **
137841 ** Return true if the m-value for z is 1 or more.  In other words,
137842 ** return true if z contains at least one vowel that is followed
137843 ** by a consonant.
137844 **
137845 ** In this routine z[] is in reverse order.  So we are really looking
137846 ** for an instance of of a consonant followed by a vowel.
137847 */
137848 static int m_gt_0(const char *z){
137849   while( isVowel(z) ){ z++; }
137850   if( *z==0 ) return 0;
137851   while( isConsonant(z) ){ z++; }
137852   return *z!=0;
137853 }
137854 
137855 /* Like mgt0 above except we are looking for a value of m which is
137856 ** exactly 1
137857 */
137858 static int m_eq_1(const char *z){
137859   while( isVowel(z) ){ z++; }
137860   if( *z==0 ) return 0;
137861   while( isConsonant(z) ){ z++; }
137862   if( *z==0 ) return 0;
137863   while( isVowel(z) ){ z++; }
137864   if( *z==0 ) return 1;
137865   while( isConsonant(z) ){ z++; }
137866   return *z==0;
137867 }
137868 
137869 /* Like mgt0 above except we are looking for a value of m>1 instead
137870 ** or m>0
137871 */
137872 static int m_gt_1(const char *z){
137873   while( isVowel(z) ){ z++; }
137874   if( *z==0 ) return 0;
137875   while( isConsonant(z) ){ z++; }
137876   if( *z==0 ) return 0;
137877   while( isVowel(z) ){ z++; }
137878   if( *z==0 ) return 0;
137879   while( isConsonant(z) ){ z++; }
137880   return *z!=0;
137881 }
137882 
137883 /*
137884 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
137885 */
137886 static int hasVowel(const char *z){
137887   while( isConsonant(z) ){ z++; }
137888   return *z!=0;
137889 }
137890 
137891 /*
137892 ** Return TRUE if the word ends in a double consonant.
137893 **
137894 ** The text is reversed here. So we are really looking at
137895 ** the first two characters of z[].
137896 */
137897 static int doubleConsonant(const char *z){
137898   return isConsonant(z) && z[0]==z[1];
137899 }
137900 
137901 /*
137902 ** Return TRUE if the word ends with three letters which
137903 ** are consonant-vowel-consonent and where the final consonant
137904 ** is not 'w', 'x', or 'y'.
137905 **
137906 ** The word is reversed here.  So we are really checking the
137907 ** first three letters and the first one cannot be in [wxy].
137908 */
137909 static int star_oh(const char *z){
137910   return
137911     isConsonant(z) &&
137912     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
137913     isVowel(z+1) &&
137914     isConsonant(z+2);
137915 }
137916 
137917 /*
137918 ** If the word ends with zFrom and xCond() is true for the stem
137919 ** of the word that preceeds the zFrom ending, then change the
137920 ** ending to zTo.
137921 **
137922 ** The input word *pz and zFrom are both in reverse order.  zTo
137923 ** is in normal order.
137924 **
137925 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
137926 ** match.  Not that TRUE is returned even if xCond() fails and
137927 ** no substitution occurs.
137928 */
137929 static int stem(
137930   char **pz,             /* The word being stemmed (Reversed) */
137931   const char *zFrom,     /* If the ending matches this... (Reversed) */
137932   const char *zTo,       /* ... change the ending to this (not reversed) */
137933   int (*xCond)(const char*)   /* Condition that must be true */
137934 ){
137935   char *z = *pz;
137936   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
137937   if( *zFrom!=0 ) return 0;
137938   if( xCond && !xCond(z) ) return 1;
137939   while( *zTo ){
137940     *(--z) = *(zTo++);
137941   }
137942   *pz = z;
137943   return 1;
137944 }
137945 
137946 /*
137947 ** This is the fallback stemmer used when the porter stemmer is
137948 ** inappropriate.  The input word is copied into the output with
137949 ** US-ASCII case folding.  If the input word is too long (more
137950 ** than 20 bytes if it contains no digits or more than 6 bytes if
137951 ** it contains digits) then word is truncated to 20 or 6 bytes
137952 ** by taking 10 or 3 bytes from the beginning and end.
137953 */
137954 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
137955   int i, mx, j;
137956   int hasDigit = 0;
137957   for(i=0; i<nIn; i++){
137958     char c = zIn[i];
137959     if( c>='A' && c<='Z' ){
137960       zOut[i] = c - 'A' + 'a';
137961     }else{
137962       if( c>='0' && c<='9' ) hasDigit = 1;
137963       zOut[i] = c;
137964     }
137965   }
137966   mx = hasDigit ? 3 : 10;
137967   if( nIn>mx*2 ){
137968     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
137969       zOut[j] = zOut[i];
137970     }
137971     i = j;
137972   }
137973   zOut[i] = 0;
137974   *pnOut = i;
137975 }
137976 
137977 
137978 /*
137979 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
137980 ** zOut is at least big enough to hold nIn bytes.  Write the actual
137981 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
137982 **
137983 ** Any upper-case characters in the US-ASCII character set ([A-Z])
137984 ** are converted to lower case.  Upper-case UTF characters are
137985 ** unchanged.
137986 **
137987 ** Words that are longer than about 20 bytes are stemmed by retaining
137988 ** a few bytes from the beginning and the end of the word.  If the
137989 ** word contains digits, 3 bytes are taken from the beginning and
137990 ** 3 bytes from the end.  For long words without digits, 10 bytes
137991 ** are taken from each end.  US-ASCII case folding still applies.
137992 **
137993 ** If the input word contains not digits but does characters not
137994 ** in [a-zA-Z] then no stemming is attempted and this routine just
137995 ** copies the input into the input into the output with US-ASCII
137996 ** case folding.
137997 **
137998 ** Stemming never increases the length of the word.  So there is
137999 ** no chance of overflowing the zOut buffer.
138000 */
138001 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
138002   int i, j;
138003   char zReverse[28];
138004   char *z, *z2;
138005   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
138006     /* The word is too big or too small for the porter stemmer.
138007     ** Fallback to the copy stemmer */
138008     copy_stemmer(zIn, nIn, zOut, pnOut);
138009     return;
138010   }
138011   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
138012     char c = zIn[i];
138013     if( c>='A' && c<='Z' ){
138014       zReverse[j] = c + 'a' - 'A';
138015     }else if( c>='a' && c<='z' ){
138016       zReverse[j] = c;
138017     }else{
138018       /* The use of a character not in [a-zA-Z] means that we fallback
138019       ** to the copy stemmer */
138020       copy_stemmer(zIn, nIn, zOut, pnOut);
138021       return;
138022     }
138023   }
138024   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
138025   z = &zReverse[j+1];
138026 
138027 
138028   /* Step 1a */
138029   if( z[0]=='s' ){
138030     if(
138031      !stem(&z, "sess", "ss", 0) &&
138032      !stem(&z, "sei", "i", 0)  &&
138033      !stem(&z, "ss", "ss", 0)
138034     ){
138035       z++;
138036     }
138037   }
138038 
138039   /* Step 1b */
138040   z2 = z;
138041   if( stem(&z, "dee", "ee", m_gt_0) ){
138042     /* Do nothing.  The work was all in the test */
138043   }else if(
138044      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
138045       && z!=z2
138046   ){
138047      if( stem(&z, "ta", "ate", 0) ||
138048          stem(&z, "lb", "ble", 0) ||
138049          stem(&z, "zi", "ize", 0) ){
138050        /* Do nothing.  The work was all in the test */
138051      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
138052        z++;
138053      }else if( m_eq_1(z) && star_oh(z) ){
138054        *(--z) = 'e';
138055      }
138056   }
138057 
138058   /* Step 1c */
138059   if( z[0]=='y' && hasVowel(z+1) ){
138060     z[0] = 'i';
138061   }
138062 
138063   /* Step 2 */
138064   switch( z[1] ){
138065    case 'a':
138066      if( !stem(&z, "lanoita", "ate", m_gt_0) ){
138067        stem(&z, "lanoit", "tion", m_gt_0);
138068      }
138069      break;
138070    case 'c':
138071      if( !stem(&z, "icne", "ence", m_gt_0) ){
138072        stem(&z, "icna", "ance", m_gt_0);
138073      }
138074      break;
138075    case 'e':
138076      stem(&z, "rezi", "ize", m_gt_0);
138077      break;
138078    case 'g':
138079      stem(&z, "igol", "log", m_gt_0);
138080      break;
138081    case 'l':
138082      if( !stem(&z, "ilb", "ble", m_gt_0)
138083       && !stem(&z, "illa", "al", m_gt_0)
138084       && !stem(&z, "iltne", "ent", m_gt_0)
138085       && !stem(&z, "ile", "e", m_gt_0)
138086      ){
138087        stem(&z, "ilsuo", "ous", m_gt_0);
138088      }
138089      break;
138090    case 'o':
138091      if( !stem(&z, "noitazi", "ize", m_gt_0)
138092       && !stem(&z, "noita", "ate", m_gt_0)
138093      ){
138094        stem(&z, "rota", "ate", m_gt_0);
138095      }
138096      break;
138097    case 's':
138098      if( !stem(&z, "msila", "al", m_gt_0)
138099       && !stem(&z, "ssenevi", "ive", m_gt_0)
138100       && !stem(&z, "ssenluf", "ful", m_gt_0)
138101      ){
138102        stem(&z, "ssensuo", "ous", m_gt_0);
138103      }
138104      break;
138105    case 't':
138106      if( !stem(&z, "itila", "al", m_gt_0)
138107       && !stem(&z, "itivi", "ive", m_gt_0)
138108      ){
138109        stem(&z, "itilib", "ble", m_gt_0);
138110      }
138111      break;
138112   }
138113 
138114   /* Step 3 */
138115   switch( z[0] ){
138116    case 'e':
138117      if( !stem(&z, "etaci", "ic", m_gt_0)
138118       && !stem(&z, "evita", "", m_gt_0)
138119      ){
138120        stem(&z, "ezila", "al", m_gt_0);
138121      }
138122      break;
138123    case 'i':
138124      stem(&z, "itici", "ic", m_gt_0);
138125      break;
138126    case 'l':
138127      if( !stem(&z, "laci", "ic", m_gt_0) ){
138128        stem(&z, "luf", "", m_gt_0);
138129      }
138130      break;
138131    case 's':
138132      stem(&z, "ssen", "", m_gt_0);
138133      break;
138134   }
138135 
138136   /* Step 4 */
138137   switch( z[1] ){
138138    case 'a':
138139      if( z[0]=='l' && m_gt_1(z+2) ){
138140        z += 2;
138141      }
138142      break;
138143    case 'c':
138144      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
138145        z += 4;
138146      }
138147      break;
138148    case 'e':
138149      if( z[0]=='r' && m_gt_1(z+2) ){
138150        z += 2;
138151      }
138152      break;
138153    case 'i':
138154      if( z[0]=='c' && m_gt_1(z+2) ){
138155        z += 2;
138156      }
138157      break;
138158    case 'l':
138159      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
138160        z += 4;
138161      }
138162      break;
138163    case 'n':
138164      if( z[0]=='t' ){
138165        if( z[2]=='a' ){
138166          if( m_gt_1(z+3) ){
138167            z += 3;
138168          }
138169        }else if( z[2]=='e' ){
138170          if( !stem(&z, "tneme", "", m_gt_1)
138171           && !stem(&z, "tnem", "", m_gt_1)
138172          ){
138173            stem(&z, "tne", "", m_gt_1);
138174          }
138175        }
138176      }
138177      break;
138178    case 'o':
138179      if( z[0]=='u' ){
138180        if( m_gt_1(z+2) ){
138181          z += 2;
138182        }
138183      }else if( z[3]=='s' || z[3]=='t' ){
138184        stem(&z, "noi", "", m_gt_1);
138185      }
138186      break;
138187    case 's':
138188      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
138189        z += 3;
138190      }
138191      break;
138192    case 't':
138193      if( !stem(&z, "eta", "", m_gt_1) ){
138194        stem(&z, "iti", "", m_gt_1);
138195      }
138196      break;
138197    case 'u':
138198      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
138199        z += 3;
138200      }
138201      break;
138202    case 'v':
138203    case 'z':
138204      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
138205        z += 3;
138206      }
138207      break;
138208   }
138209 
138210   /* Step 5a */
138211   if( z[0]=='e' ){
138212     if( m_gt_1(z+1) ){
138213       z++;
138214     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
138215       z++;
138216     }
138217   }
138218 
138219   /* Step 5b */
138220   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
138221     z++;
138222   }
138223 
138224   /* z[] is now the stemmed word in reverse order.  Flip it back
138225   ** around into forward order and return.
138226   */
138227   *pnOut = i = (int)strlen(z);
138228   zOut[i] = 0;
138229   while( *z ){
138230     zOut[--i] = *(z++);
138231   }
138232 }
138233 
138234 /*
138235 ** Characters that can be part of a token.  We assume any character
138236 ** whose value is greater than 0x80 (any UTF character) can be
138237 ** part of a token.  In other words, delimiters all must have
138238 ** values of 0x7f or lower.
138239 */
138240 static const char porterIdChar[] = {
138241 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
138242     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
138243     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
138244     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
138245     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
138246     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
138247 };
138248 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
138249 
138250 /*
138251 ** Extract the next token from a tokenization cursor.  The cursor must
138252 ** have been opened by a prior call to porterOpen().
138253 */
138254 static int porterNext(
138255   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
138256   const char **pzToken,               /* OUT: *pzToken is the token text */
138257   int *pnBytes,                       /* OUT: Number of bytes in token */
138258   int *piStartOffset,                 /* OUT: Starting offset of token */
138259   int *piEndOffset,                   /* OUT: Ending offset of token */
138260   int *piPosition                     /* OUT: Position integer of token */
138261 ){
138262   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
138263   const char *z = c->zInput;
138264 
138265   while( c->iOffset<c->nInput ){
138266     int iStartOffset, ch;
138267 
138268     /* Scan past delimiter characters */
138269     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
138270       c->iOffset++;
138271     }
138272 
138273     /* Count non-delimiter characters. */
138274     iStartOffset = c->iOffset;
138275     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
138276       c->iOffset++;
138277     }
138278 
138279     if( c->iOffset>iStartOffset ){
138280       int n = c->iOffset-iStartOffset;
138281       if( n>c->nAllocated ){
138282         char *pNew;
138283         c->nAllocated = n+20;
138284         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
138285         if( !pNew ) return SQLITE_NOMEM;
138286         c->zToken = pNew;
138287       }
138288       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
138289       *pzToken = c->zToken;
138290       *piStartOffset = iStartOffset;
138291       *piEndOffset = c->iOffset;
138292       *piPosition = c->iToken++;
138293       return SQLITE_OK;
138294     }
138295   }
138296   return SQLITE_DONE;
138297 }
138298 
138299 /*
138300 ** The set of routines that implement the porter-stemmer tokenizer
138301 */
138302 static const sqlite3_tokenizer_module porterTokenizerModule = {
138303   0,
138304   porterCreate,
138305   porterDestroy,
138306   porterOpen,
138307   porterClose,
138308   porterNext,
138309   0
138310 };
138311 
138312 /*
138313 ** Allocate a new porter tokenizer.  Return a pointer to the new
138314 ** tokenizer in *ppModule
138315 */
138316 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
138317   sqlite3_tokenizer_module const**ppModule
138318 ){
138319   *ppModule = &porterTokenizerModule;
138320 }
138321 
138322 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
138323 
138324 /************** End of fts3_porter.c *****************************************/
138325 /************** Begin file fts3_tokenizer.c **********************************/
138326 /*
138327 ** 2007 June 22
138328 **
138329 ** The author disclaims copyright to this source code.  In place of
138330 ** a legal notice, here is a blessing:
138331 **
138332 **    May you do good and not evil.
138333 **    May you find forgiveness for yourself and forgive others.
138334 **    May you share freely, never taking more than you give.
138335 **
138336 ******************************************************************************
138337 **
138338 ** This is part of an SQLite module implementing full-text search.
138339 ** This particular file implements the generic tokenizer interface.
138340 */
138341 
138342 /*
138343 ** The code in this file is only compiled if:
138344 **
138345 **     * The FTS3 module is being built as an extension
138346 **       (in which case SQLITE_CORE is not defined), or
138347 **
138348 **     * The FTS3 module is being built into the core of
138349 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
138350 */
138351 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
138352 
138353 /* #include <assert.h> */
138354 /* #include <string.h> */
138355 
138356 /*
138357 ** Implementation of the SQL scalar function for accessing the underlying
138358 ** hash table. This function may be called as follows:
138359 **
138360 **   SELECT <function-name>(<key-name>);
138361 **   SELECT <function-name>(<key-name>, <pointer>);
138362 **
138363 ** where <function-name> is the name passed as the second argument
138364 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
138365 **
138366 ** If the <pointer> argument is specified, it must be a blob value
138367 ** containing a pointer to be stored as the hash data corresponding
138368 ** to the string <key-name>. If <pointer> is not specified, then
138369 ** the string <key-name> must already exist in the has table. Otherwise,
138370 ** an error is returned.
138371 **
138372 ** Whether or not the <pointer> argument is specified, the value returned
138373 ** is a blob containing the pointer stored as the hash data corresponding
138374 ** to string <key-name> (after the hash-table is updated, if applicable).
138375 */
138376 static void scalarFunc(
138377   sqlite3_context *context,
138378   int argc,
138379   sqlite3_value **argv
138380 ){
138381   Fts3Hash *pHash;
138382   void *pPtr = 0;
138383   const unsigned char *zName;
138384   int nName;
138385 
138386   assert( argc==1 || argc==2 );
138387 
138388   pHash = (Fts3Hash *)sqlite3_user_data(context);
138389 
138390   zName = sqlite3_value_text(argv[0]);
138391   nName = sqlite3_value_bytes(argv[0])+1;
138392 
138393   if( argc==2 ){
138394     void *pOld;
138395     int n = sqlite3_value_bytes(argv[1]);
138396     if( n!=sizeof(pPtr) ){
138397       sqlite3_result_error(context, "argument type mismatch", -1);
138398       return;
138399     }
138400     pPtr = *(void **)sqlite3_value_blob(argv[1]);
138401     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
138402     if( pOld==pPtr ){
138403       sqlite3_result_error(context, "out of memory", -1);
138404       return;
138405     }
138406   }else{
138407     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
138408     if( !pPtr ){
138409       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
138410       sqlite3_result_error(context, zErr, -1);
138411       sqlite3_free(zErr);
138412       return;
138413     }
138414   }
138415 
138416   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
138417 }
138418 
138419 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
138420   static const char isFtsIdChar[] = {
138421       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
138422       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
138423       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
138424       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
138425       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
138426       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
138427       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
138428       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
138429   };
138430   return (c&0x80 || isFtsIdChar[(int)(c)]);
138431 }
138432 
138433 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
138434   const char *z1;
138435   const char *z2 = 0;
138436 
138437   /* Find the start of the next token. */
138438   z1 = zStr;
138439   while( z2==0 ){
138440     char c = *z1;
138441     switch( c ){
138442       case '\0': return 0;        /* No more tokens here */
138443       case '\'':
138444       case '"':
138445       case '`': {
138446         z2 = z1;
138447         while( *++z2 && (*z2!=c || *++z2==c) );
138448         break;
138449       }
138450       case '[':
138451         z2 = &z1[1];
138452         while( *z2 && z2[0]!=']' ) z2++;
138453         if( *z2 ) z2++;
138454         break;
138455 
138456       default:
138457         if( sqlite3Fts3IsIdChar(*z1) ){
138458           z2 = &z1[1];
138459           while( sqlite3Fts3IsIdChar(*z2) ) z2++;
138460         }else{
138461           z1++;
138462         }
138463     }
138464   }
138465 
138466   *pn = (int)(z2-z1);
138467   return z1;
138468 }
138469 
138470 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
138471   Fts3Hash *pHash,                /* Tokenizer hash table */
138472   const char *zArg,               /* Tokenizer name */
138473   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
138474   char **pzErr                    /* OUT: Set to malloced error message */
138475 ){
138476   int rc;
138477   char *z = (char *)zArg;
138478   int n = 0;
138479   char *zCopy;
138480   char *zEnd;                     /* Pointer to nul-term of zCopy */
138481   sqlite3_tokenizer_module *m;
138482 
138483   zCopy = sqlite3_mprintf("%s", zArg);
138484   if( !zCopy ) return SQLITE_NOMEM;
138485   zEnd = &zCopy[strlen(zCopy)];
138486 
138487   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
138488   z[n] = '\0';
138489   sqlite3Fts3Dequote(z);
138490 
138491   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
138492   if( !m ){
138493     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
138494     rc = SQLITE_ERROR;
138495   }else{
138496     char const **aArg = 0;
138497     int iArg = 0;
138498     z = &z[n+1];
138499     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
138500       int nNew = sizeof(char *)*(iArg+1);
138501       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
138502       if( !aNew ){
138503         sqlite3_free(zCopy);
138504         sqlite3_free((void *)aArg);
138505         return SQLITE_NOMEM;
138506       }
138507       aArg = aNew;
138508       aArg[iArg++] = z;
138509       z[n] = '\0';
138510       sqlite3Fts3Dequote(z);
138511       z = &z[n+1];
138512     }
138513     rc = m->xCreate(iArg, aArg, ppTok);
138514     assert( rc!=SQLITE_OK || *ppTok );
138515     if( rc!=SQLITE_OK ){
138516       *pzErr = sqlite3_mprintf("unknown tokenizer");
138517     }else{
138518       (*ppTok)->pModule = m;
138519     }
138520     sqlite3_free((void *)aArg);
138521   }
138522 
138523   sqlite3_free(zCopy);
138524   return rc;
138525 }
138526 
138527 
138528 #ifdef SQLITE_TEST
138529 
138530 #include <tcl.h>
138531 /* #include <string.h> */
138532 
138533 /*
138534 ** Implementation of a special SQL scalar function for testing tokenizers
138535 ** designed to be used in concert with the Tcl testing framework. This
138536 ** function must be called with two or more arguments:
138537 **
138538 **   SELECT <function-name>(<key-name>, ..., <input-string>);
138539 **
138540 ** where <function-name> is the name passed as the second argument
138541 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
138542 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
138543 **
138544 ** The return value is a string that may be interpreted as a Tcl
138545 ** list. For each token in the <input-string>, three elements are
138546 ** added to the returned list. The first is the token position, the
138547 ** second is the token text (folded, stemmed, etc.) and the third is the
138548 ** substring of <input-string> associated with the token. For example,
138549 ** using the built-in "simple" tokenizer:
138550 **
138551 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
138552 **
138553 ** will return the string:
138554 **
138555 **   "{0 i I 1 dont don't 2 see see 3 how how}"
138556 **
138557 */
138558 static void testFunc(
138559   sqlite3_context *context,
138560   int argc,
138561   sqlite3_value **argv
138562 ){
138563   Fts3Hash *pHash;
138564   sqlite3_tokenizer_module *p;
138565   sqlite3_tokenizer *pTokenizer = 0;
138566   sqlite3_tokenizer_cursor *pCsr = 0;
138567 
138568   const char *zErr = 0;
138569 
138570   const char *zName;
138571   int nName;
138572   const char *zInput;
138573   int nInput;
138574 
138575   const char *azArg[64];
138576 
138577   const char *zToken;
138578   int nToken = 0;
138579   int iStart = 0;
138580   int iEnd = 0;
138581   int iPos = 0;
138582   int i;
138583 
138584   Tcl_Obj *pRet;
138585 
138586   if( argc<2 ){
138587     sqlite3_result_error(context, "insufficient arguments", -1);
138588     return;
138589   }
138590 
138591   nName = sqlite3_value_bytes(argv[0]);
138592   zName = (const char *)sqlite3_value_text(argv[0]);
138593   nInput = sqlite3_value_bytes(argv[argc-1]);
138594   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
138595 
138596   pHash = (Fts3Hash *)sqlite3_user_data(context);
138597   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
138598 
138599   if( !p ){
138600     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
138601     sqlite3_result_error(context, zErr, -1);
138602     sqlite3_free(zErr);
138603     return;
138604   }
138605 
138606   pRet = Tcl_NewObj();
138607   Tcl_IncrRefCount(pRet);
138608 
138609   for(i=1; i<argc-1; i++){
138610     azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
138611   }
138612 
138613   if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
138614     zErr = "error in xCreate()";
138615     goto finish;
138616   }
138617   pTokenizer->pModule = p;
138618   if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
138619     zErr = "error in xOpen()";
138620     goto finish;
138621   }
138622 
138623   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
138624     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
138625     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
138626     zToken = &zInput[iStart];
138627     nToken = iEnd-iStart;
138628     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
138629   }
138630 
138631   if( SQLITE_OK!=p->xClose(pCsr) ){
138632     zErr = "error in xClose()";
138633     goto finish;
138634   }
138635   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
138636     zErr = "error in xDestroy()";
138637     goto finish;
138638   }
138639 
138640 finish:
138641   if( zErr ){
138642     sqlite3_result_error(context, zErr, -1);
138643   }else{
138644     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
138645   }
138646   Tcl_DecrRefCount(pRet);
138647 }
138648 
138649 static
138650 int registerTokenizer(
138651   sqlite3 *db,
138652   char *zName,
138653   const sqlite3_tokenizer_module *p
138654 ){
138655   int rc;
138656   sqlite3_stmt *pStmt;
138657   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
138658 
138659   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
138660   if( rc!=SQLITE_OK ){
138661     return rc;
138662   }
138663 
138664   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
138665   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
138666   sqlite3_step(pStmt);
138667 
138668   return sqlite3_finalize(pStmt);
138669 }
138670 
138671 static
138672 int queryTokenizer(
138673   sqlite3 *db,
138674   char *zName,
138675   const sqlite3_tokenizer_module **pp
138676 ){
138677   int rc;
138678   sqlite3_stmt *pStmt;
138679   const char zSql[] = "SELECT fts3_tokenizer(?)";
138680 
138681   *pp = 0;
138682   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
138683   if( rc!=SQLITE_OK ){
138684     return rc;
138685   }
138686 
138687   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
138688   if( SQLITE_ROW==sqlite3_step(pStmt) ){
138689     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
138690       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
138691     }
138692   }
138693 
138694   return sqlite3_finalize(pStmt);
138695 }
138696 
138697 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
138698 
138699 /*
138700 ** Implementation of the scalar function fts3_tokenizer_internal_test().
138701 ** This function is used for testing only, it is not included in the
138702 ** build unless SQLITE_TEST is defined.
138703 **
138704 ** The purpose of this is to test that the fts3_tokenizer() function
138705 ** can be used as designed by the C-code in the queryTokenizer and
138706 ** registerTokenizer() functions above. These two functions are repeated
138707 ** in the README.tokenizer file as an example, so it is important to
138708 ** test them.
138709 **
138710 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
138711 ** function with no arguments. An assert() will fail if a problem is
138712 ** detected. i.e.:
138713 **
138714 **     SELECT fts3_tokenizer_internal_test();
138715 **
138716 */
138717 static void intTestFunc(
138718   sqlite3_context *context,
138719   int argc,
138720   sqlite3_value **argv
138721 ){
138722   int rc;
138723   const sqlite3_tokenizer_module *p1;
138724   const sqlite3_tokenizer_module *p2;
138725   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
138726 
138727   UNUSED_PARAMETER(argc);
138728   UNUSED_PARAMETER(argv);
138729 
138730   /* Test the query function */
138731   sqlite3Fts3SimpleTokenizerModule(&p1);
138732   rc = queryTokenizer(db, "simple", &p2);
138733   assert( rc==SQLITE_OK );
138734   assert( p1==p2 );
138735   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
138736   assert( rc==SQLITE_ERROR );
138737   assert( p2==0 );
138738   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
138739 
138740   /* Test the storage function */
138741   rc = registerTokenizer(db, "nosuchtokenizer", p1);
138742   assert( rc==SQLITE_OK );
138743   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
138744   assert( rc==SQLITE_OK );
138745   assert( p2==p1 );
138746 
138747   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
138748 }
138749 
138750 #endif
138751 
138752 /*
138753 ** Set up SQL objects in database db used to access the contents of
138754 ** the hash table pointed to by argument pHash. The hash table must
138755 ** been initialized to use string keys, and to take a private copy
138756 ** of the key when a value is inserted. i.e. by a call similar to:
138757 **
138758 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
138759 **
138760 ** This function adds a scalar function (see header comment above
138761 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
138762 ** defined at compilation time, a temporary virtual table (see header
138763 ** comment above struct HashTableVtab) to the database schema. Both
138764 ** provide read/write access to the contents of *pHash.
138765 **
138766 ** The third argument to this function, zName, is used as the name
138767 ** of both the scalar and, if created, the virtual table.
138768 */
138769 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
138770   sqlite3 *db,
138771   Fts3Hash *pHash,
138772   const char *zName
138773 ){
138774   int rc = SQLITE_OK;
138775   void *p = (void *)pHash;
138776   const int any = SQLITE_ANY;
138777 
138778 #ifdef SQLITE_TEST
138779   char *zTest = 0;
138780   char *zTest2 = 0;
138781   void *pdb = (void *)db;
138782   zTest = sqlite3_mprintf("%s_test", zName);
138783   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
138784   if( !zTest || !zTest2 ){
138785     rc = SQLITE_NOMEM;
138786   }
138787 #endif
138788 
138789   if( SQLITE_OK==rc ){
138790     rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
138791   }
138792   if( SQLITE_OK==rc ){
138793     rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
138794   }
138795 #ifdef SQLITE_TEST
138796   if( SQLITE_OK==rc ){
138797     rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
138798   }
138799   if( SQLITE_OK==rc ){
138800     rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
138801   }
138802 #endif
138803 
138804 #ifdef SQLITE_TEST
138805   sqlite3_free(zTest);
138806   sqlite3_free(zTest2);
138807 #endif
138808 
138809   return rc;
138810 }
138811 
138812 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
138813 
138814 /************** End of fts3_tokenizer.c **************************************/
138815 /************** Begin file fts3_tokenizer1.c *********************************/
138816 /*
138817 ** 2006 Oct 10
138818 **
138819 ** The author disclaims copyright to this source code.  In place of
138820 ** a legal notice, here is a blessing:
138821 **
138822 **    May you do good and not evil.
138823 **    May you find forgiveness for yourself and forgive others.
138824 **    May you share freely, never taking more than you give.
138825 **
138826 ******************************************************************************
138827 **
138828 ** Implementation of the "simple" full-text-search tokenizer.
138829 */
138830 
138831 /*
138832 ** The code in this file is only compiled if:
138833 **
138834 **     * The FTS3 module is being built as an extension
138835 **       (in which case SQLITE_CORE is not defined), or
138836 **
138837 **     * The FTS3 module is being built into the core of
138838 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
138839 */
138840 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
138841 
138842 /* #include <assert.h> */
138843 /* #include <stdlib.h> */
138844 /* #include <stdio.h> */
138845 /* #include <string.h> */
138846 
138847 
138848 typedef struct simple_tokenizer {
138849   sqlite3_tokenizer base;
138850   char delim[128];             /* flag ASCII delimiters */
138851 } simple_tokenizer;
138852 
138853 typedef struct simple_tokenizer_cursor {
138854   sqlite3_tokenizer_cursor base;
138855   const char *pInput;          /* input we are tokenizing */
138856   int nBytes;                  /* size of the input */
138857   int iOffset;                 /* current position in pInput */
138858   int iToken;                  /* index of next token to be returned */
138859   char *pToken;                /* storage for current token */
138860   int nTokenAllocated;         /* space allocated to zToken buffer */
138861 } simple_tokenizer_cursor;
138862 
138863 
138864 static int simpleDelim(simple_tokenizer *t, unsigned char c){
138865   return c<0x80 && t->delim[c];
138866 }
138867 static int fts3_isalnum(int x){
138868   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
138869 }
138870 
138871 /*
138872 ** Create a new tokenizer instance.
138873 */
138874 static int simpleCreate(
138875   int argc, const char * const *argv,
138876   sqlite3_tokenizer **ppTokenizer
138877 ){
138878   simple_tokenizer *t;
138879 
138880   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
138881   if( t==NULL ) return SQLITE_NOMEM;
138882   memset(t, 0, sizeof(*t));
138883 
138884   /* TODO(shess) Delimiters need to remain the same from run to run,
138885   ** else we need to reindex.  One solution would be a meta-table to
138886   ** track such information in the database, then we'd only want this
138887   ** information on the initial create.
138888   */
138889   if( argc>1 ){
138890     int i, n = (int)strlen(argv[1]);
138891     for(i=0; i<n; i++){
138892       unsigned char ch = argv[1][i];
138893       /* We explicitly don't support UTF-8 delimiters for now. */
138894       if( ch>=0x80 ){
138895         sqlite3_free(t);
138896         return SQLITE_ERROR;
138897       }
138898       t->delim[ch] = 1;
138899     }
138900   } else {
138901     /* Mark non-alphanumeric ASCII characters as delimiters */
138902     int i;
138903     for(i=1; i<0x80; i++){
138904       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
138905     }
138906   }
138907 
138908   *ppTokenizer = &t->base;
138909   return SQLITE_OK;
138910 }
138911 
138912 /*
138913 ** Destroy a tokenizer
138914 */
138915 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
138916   sqlite3_free(pTokenizer);
138917   return SQLITE_OK;
138918 }
138919 
138920 /*
138921 ** Prepare to begin tokenizing a particular string.  The input
138922 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
138923 ** used to incrementally tokenize this string is returned in
138924 ** *ppCursor.
138925 */
138926 static int simpleOpen(
138927   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
138928   const char *pInput, int nBytes,        /* String to be tokenized */
138929   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
138930 ){
138931   simple_tokenizer_cursor *c;
138932 
138933   UNUSED_PARAMETER(pTokenizer);
138934 
138935   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
138936   if( c==NULL ) return SQLITE_NOMEM;
138937 
138938   c->pInput = pInput;
138939   if( pInput==0 ){
138940     c->nBytes = 0;
138941   }else if( nBytes<0 ){
138942     c->nBytes = (int)strlen(pInput);
138943   }else{
138944     c->nBytes = nBytes;
138945   }
138946   c->iOffset = 0;                 /* start tokenizing at the beginning */
138947   c->iToken = 0;
138948   c->pToken = NULL;               /* no space allocated, yet. */
138949   c->nTokenAllocated = 0;
138950 
138951   *ppCursor = &c->base;
138952   return SQLITE_OK;
138953 }
138954 
138955 /*
138956 ** Close a tokenization cursor previously opened by a call to
138957 ** simpleOpen() above.
138958 */
138959 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
138960   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
138961   sqlite3_free(c->pToken);
138962   sqlite3_free(c);
138963   return SQLITE_OK;
138964 }
138965 
138966 /*
138967 ** Extract the next token from a tokenization cursor.  The cursor must
138968 ** have been opened by a prior call to simpleOpen().
138969 */
138970 static int simpleNext(
138971   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
138972   const char **ppToken,               /* OUT: *ppToken is the token text */
138973   int *pnBytes,                       /* OUT: Number of bytes in token */
138974   int *piStartOffset,                 /* OUT: Starting offset of token */
138975   int *piEndOffset,                   /* OUT: Ending offset of token */
138976   int *piPosition                     /* OUT: Position integer of token */
138977 ){
138978   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
138979   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
138980   unsigned char *p = (unsigned char *)c->pInput;
138981 
138982   while( c->iOffset<c->nBytes ){
138983     int iStartOffset;
138984 
138985     /* Scan past delimiter characters */
138986     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
138987       c->iOffset++;
138988     }
138989 
138990     /* Count non-delimiter characters. */
138991     iStartOffset = c->iOffset;
138992     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
138993       c->iOffset++;
138994     }
138995 
138996     if( c->iOffset>iStartOffset ){
138997       int i, n = c->iOffset-iStartOffset;
138998       if( n>c->nTokenAllocated ){
138999         char *pNew;
139000         c->nTokenAllocated = n+20;
139001         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
139002         if( !pNew ) return SQLITE_NOMEM;
139003         c->pToken = pNew;
139004       }
139005       for(i=0; i<n; i++){
139006         /* TODO(shess) This needs expansion to handle UTF-8
139007         ** case-insensitivity.
139008         */
139009         unsigned char ch = p[iStartOffset+i];
139010         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
139011       }
139012       *ppToken = c->pToken;
139013       *pnBytes = n;
139014       *piStartOffset = iStartOffset;
139015       *piEndOffset = c->iOffset;
139016       *piPosition = c->iToken++;
139017 
139018       return SQLITE_OK;
139019     }
139020   }
139021   return SQLITE_DONE;
139022 }
139023 
139024 /*
139025 ** The set of routines that implement the simple tokenizer
139026 */
139027 static const sqlite3_tokenizer_module simpleTokenizerModule = {
139028   0,
139029   simpleCreate,
139030   simpleDestroy,
139031   simpleOpen,
139032   simpleClose,
139033   simpleNext,
139034   0,
139035 };
139036 
139037 /*
139038 ** Allocate a new simple tokenizer.  Return a pointer to the new
139039 ** tokenizer in *ppModule
139040 */
139041 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
139042   sqlite3_tokenizer_module const**ppModule
139043 ){
139044   *ppModule = &simpleTokenizerModule;
139045 }
139046 
139047 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
139048 
139049 /************** End of fts3_tokenizer1.c *************************************/
139050 /************** Begin file fts3_tokenize_vtab.c ******************************/
139051 /*
139052 ** 2013 Apr 22
139053 **
139054 ** The author disclaims copyright to this source code.  In place of
139055 ** a legal notice, here is a blessing:
139056 **
139057 **    May you do good and not evil.
139058 **    May you find forgiveness for yourself and forgive others.
139059 **    May you share freely, never taking more than you give.
139060 **
139061 ******************************************************************************
139062 **
139063 ** This file contains code for the "fts3tokenize" virtual table module.
139064 ** An fts3tokenize virtual table is created as follows:
139065 **
139066 **   CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
139067 **       <tokenizer-name>, <arg-1>, ...
139068 **   );
139069 **
139070 ** The table created has the following schema:
139071 **
139072 **   CREATE TABLE <tbl>(input, token, start, end, position)
139073 **
139074 ** When queried, the query must include a WHERE clause of type:
139075 **
139076 **   input = <string>
139077 **
139078 ** The virtual table module tokenizes this <string>, using the FTS3
139079 ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
139080 ** statement and returns one row for each token in the result. With
139081 ** fields set as follows:
139082 **
139083 **   input:   Always set to a copy of <string>
139084 **   token:   A token from the input.
139085 **   start:   Byte offset of the token within the input <string>.
139086 **   end:     Byte offset of the byte immediately following the end of the
139087 **            token within the input string.
139088 **   pos:     Token offset of token within input.
139089 **
139090 */
139091 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
139092 
139093 /* #include <string.h> */
139094 /* #include <assert.h> */
139095 
139096 typedef struct Fts3tokTable Fts3tokTable;
139097 typedef struct Fts3tokCursor Fts3tokCursor;
139098 
139099 /*
139100 ** Virtual table structure.
139101 */
139102 struct Fts3tokTable {
139103   sqlite3_vtab base;              /* Base class used by SQLite core */
139104   const sqlite3_tokenizer_module *pMod;
139105   sqlite3_tokenizer *pTok;
139106 };
139107 
139108 /*
139109 ** Virtual table cursor structure.
139110 */
139111 struct Fts3tokCursor {
139112   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
139113   char *zInput;                   /* Input string */
139114   sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
139115   int iRowid;                     /* Current 'rowid' value */
139116   const char *zToken;             /* Current 'token' value */
139117   int nToken;                     /* Size of zToken in bytes */
139118   int iStart;                     /* Current 'start' value */
139119   int iEnd;                       /* Current 'end' value */
139120   int iPos;                       /* Current 'pos' value */
139121 };
139122 
139123 /*
139124 ** Query FTS for the tokenizer implementation named zName.
139125 */
139126 static int fts3tokQueryTokenizer(
139127   Fts3Hash *pHash,
139128   const char *zName,
139129   const sqlite3_tokenizer_module **pp,
139130   char **pzErr
139131 ){
139132   sqlite3_tokenizer_module *p;
139133   int nName = (int)strlen(zName);
139134 
139135   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
139136   if( !p ){
139137     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
139138     return SQLITE_ERROR;
139139   }
139140 
139141   *pp = p;
139142   return SQLITE_OK;
139143 }
139144 
139145 /*
139146 ** The second argument, argv[], is an array of pointers to nul-terminated
139147 ** strings. This function makes a copy of the array and strings into a
139148 ** single block of memory. It then dequotes any of the strings that appear
139149 ** to be quoted.
139150 **
139151 ** If successful, output parameter *pazDequote is set to point at the
139152 ** array of dequoted strings and SQLITE_OK is returned. The caller is
139153 ** responsible for eventually calling sqlite3_free() to free the array
139154 ** in this case. Or, if an error occurs, an SQLite error code is returned.
139155 ** The final value of *pazDequote is undefined in this case.
139156 */
139157 static int fts3tokDequoteArray(
139158   int argc,                       /* Number of elements in argv[] */
139159   const char * const *argv,       /* Input array */
139160   char ***pazDequote              /* Output array */
139161 ){
139162   int rc = SQLITE_OK;             /* Return code */
139163   if( argc==0 ){
139164     *pazDequote = 0;
139165   }else{
139166     int i;
139167     int nByte = 0;
139168     char **azDequote;
139169 
139170     for(i=0; i<argc; i++){
139171       nByte += (int)(strlen(argv[i]) + 1);
139172     }
139173 
139174     *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
139175     if( azDequote==0 ){
139176       rc = SQLITE_NOMEM;
139177     }else{
139178       char *pSpace = (char *)&azDequote[argc];
139179       for(i=0; i<argc; i++){
139180         int n = (int)strlen(argv[i]);
139181         azDequote[i] = pSpace;
139182         memcpy(pSpace, argv[i], n+1);
139183         sqlite3Fts3Dequote(pSpace);
139184         pSpace += (n+1);
139185       }
139186     }
139187   }
139188 
139189   return rc;
139190 }
139191 
139192 /*
139193 ** Schema of the tokenizer table.
139194 */
139195 #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
139196 
139197 /*
139198 ** This function does all the work for both the xConnect and xCreate methods.
139199 ** These tables have no persistent representation of their own, so xConnect
139200 ** and xCreate are identical operations.
139201 **
139202 **   argv[0]: module name
139203 **   argv[1]: database name
139204 **   argv[2]: table name
139205 **   argv[3]: first argument (tokenizer name)
139206 */
139207 static int fts3tokConnectMethod(
139208   sqlite3 *db,                    /* Database connection */
139209   void *pHash,                    /* Hash table of tokenizers */
139210   int argc,                       /* Number of elements in argv array */
139211   const char * const *argv,       /* xCreate/xConnect argument array */
139212   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
139213   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
139214 ){
139215   Fts3tokTable *pTab;
139216   const sqlite3_tokenizer_module *pMod = 0;
139217   sqlite3_tokenizer *pTok = 0;
139218   int rc;
139219   char **azDequote = 0;
139220   int nDequote;
139221 
139222   rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
139223   if( rc!=SQLITE_OK ) return rc;
139224 
139225   nDequote = argc-3;
139226   rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
139227 
139228   if( rc==SQLITE_OK ){
139229     const char *zModule;
139230     if( nDequote<1 ){
139231       zModule = "simple";
139232     }else{
139233       zModule = azDequote[0];
139234     }
139235     rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
139236   }
139237 
139238   assert( (rc==SQLITE_OK)==(pMod!=0) );
139239   if( rc==SQLITE_OK ){
139240     const char * const *azArg = (const char * const *)&azDequote[1];
139241     rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
139242   }
139243 
139244   if( rc==SQLITE_OK ){
139245     pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
139246     if( pTab==0 ){
139247       rc = SQLITE_NOMEM;
139248     }
139249   }
139250 
139251   if( rc==SQLITE_OK ){
139252     memset(pTab, 0, sizeof(Fts3tokTable));
139253     pTab->pMod = pMod;
139254     pTab->pTok = pTok;
139255     *ppVtab = &pTab->base;
139256   }else{
139257     if( pTok ){
139258       pMod->xDestroy(pTok);
139259     }
139260   }
139261 
139262   sqlite3_free(azDequote);
139263   return rc;
139264 }
139265 
139266 /*
139267 ** This function does the work for both the xDisconnect and xDestroy methods.
139268 ** These tables have no persistent representation of their own, so xDisconnect
139269 ** and xDestroy are identical operations.
139270 */
139271 static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
139272   Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
139273 
139274   pTab->pMod->xDestroy(pTab->pTok);
139275   sqlite3_free(pTab);
139276   return SQLITE_OK;
139277 }
139278 
139279 /*
139280 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
139281 */
139282 static int fts3tokBestIndexMethod(
139283   sqlite3_vtab *pVTab,
139284   sqlite3_index_info *pInfo
139285 ){
139286   int i;
139287   UNUSED_PARAMETER(pVTab);
139288 
139289   for(i=0; i<pInfo->nConstraint; i++){
139290     if( pInfo->aConstraint[i].usable
139291      && pInfo->aConstraint[i].iColumn==0
139292      && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
139293     ){
139294       pInfo->idxNum = 1;
139295       pInfo->aConstraintUsage[i].argvIndex = 1;
139296       pInfo->aConstraintUsage[i].omit = 1;
139297       pInfo->estimatedCost = 1;
139298       return SQLITE_OK;
139299     }
139300   }
139301 
139302   pInfo->idxNum = 0;
139303   assert( pInfo->estimatedCost>1000000.0 );
139304 
139305   return SQLITE_OK;
139306 }
139307 
139308 /*
139309 ** xOpen - Open a cursor.
139310 */
139311 static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
139312   Fts3tokCursor *pCsr;
139313   UNUSED_PARAMETER(pVTab);
139314 
139315   pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
139316   if( pCsr==0 ){
139317     return SQLITE_NOMEM;
139318   }
139319   memset(pCsr, 0, sizeof(Fts3tokCursor));
139320 
139321   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
139322   return SQLITE_OK;
139323 }
139324 
139325 /*
139326 ** Reset the tokenizer cursor passed as the only argument. As if it had
139327 ** just been returned by fts3tokOpenMethod().
139328 */
139329 static void fts3tokResetCursor(Fts3tokCursor *pCsr){
139330   if( pCsr->pCsr ){
139331     Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
139332     pTab->pMod->xClose(pCsr->pCsr);
139333     pCsr->pCsr = 0;
139334   }
139335   sqlite3_free(pCsr->zInput);
139336   pCsr->zInput = 0;
139337   pCsr->zToken = 0;
139338   pCsr->nToken = 0;
139339   pCsr->iStart = 0;
139340   pCsr->iEnd = 0;
139341   pCsr->iPos = 0;
139342   pCsr->iRowid = 0;
139343 }
139344 
139345 /*
139346 ** xClose - Close a cursor.
139347 */
139348 static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
139349   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
139350 
139351   fts3tokResetCursor(pCsr);
139352   sqlite3_free(pCsr);
139353   return SQLITE_OK;
139354 }
139355 
139356 /*
139357 ** xNext - Advance the cursor to the next row, if any.
139358 */
139359 static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
139360   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
139361   Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
139362   int rc;                         /* Return code */
139363 
139364   pCsr->iRowid++;
139365   rc = pTab->pMod->xNext(pCsr->pCsr,
139366       &pCsr->zToken, &pCsr->nToken,
139367       &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
139368   );
139369 
139370   if( rc!=SQLITE_OK ){
139371     fts3tokResetCursor(pCsr);
139372     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
139373   }
139374 
139375   return rc;
139376 }
139377 
139378 /*
139379 ** xFilter - Initialize a cursor to point at the start of its data.
139380 */
139381 static int fts3tokFilterMethod(
139382   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
139383   int idxNum,                     /* Strategy index */
139384   const char *idxStr,             /* Unused */
139385   int nVal,                       /* Number of elements in apVal */
139386   sqlite3_value **apVal           /* Arguments for the indexing scheme */
139387 ){
139388   int rc = SQLITE_ERROR;
139389   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
139390   Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
139391   UNUSED_PARAMETER(idxStr);
139392   UNUSED_PARAMETER(nVal);
139393 
139394   fts3tokResetCursor(pCsr);
139395   if( idxNum==1 ){
139396     const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
139397     int nByte = sqlite3_value_bytes(apVal[0]);
139398     pCsr->zInput = sqlite3_malloc(nByte+1);
139399     if( pCsr->zInput==0 ){
139400       rc = SQLITE_NOMEM;
139401     }else{
139402       memcpy(pCsr->zInput, zByte, nByte);
139403       pCsr->zInput[nByte] = 0;
139404       rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
139405       if( rc==SQLITE_OK ){
139406         pCsr->pCsr->pTokenizer = pTab->pTok;
139407       }
139408     }
139409   }
139410 
139411   if( rc!=SQLITE_OK ) return rc;
139412   return fts3tokNextMethod(pCursor);
139413 }
139414 
139415 /*
139416 ** xEof - Return true if the cursor is at EOF, or false otherwise.
139417 */
139418 static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
139419   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
139420   return (pCsr->zToken==0);
139421 }
139422 
139423 /*
139424 ** xColumn - Return a column value.
139425 */
139426 static int fts3tokColumnMethod(
139427   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
139428   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
139429   int iCol                        /* Index of column to read value from */
139430 ){
139431   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
139432 
139433   /* CREATE TABLE x(input, token, start, end, position) */
139434   switch( iCol ){
139435     case 0:
139436       sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
139437       break;
139438     case 1:
139439       sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
139440       break;
139441     case 2:
139442       sqlite3_result_int(pCtx, pCsr->iStart);
139443       break;
139444     case 3:
139445       sqlite3_result_int(pCtx, pCsr->iEnd);
139446       break;
139447     default:
139448       assert( iCol==4 );
139449       sqlite3_result_int(pCtx, pCsr->iPos);
139450       break;
139451   }
139452   return SQLITE_OK;
139453 }
139454 
139455 /*
139456 ** xRowid - Return the current rowid for the cursor.
139457 */
139458 static int fts3tokRowidMethod(
139459   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
139460   sqlite_int64 *pRowid            /* OUT: Rowid value */
139461 ){
139462   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
139463   *pRowid = (sqlite3_int64)pCsr->iRowid;
139464   return SQLITE_OK;
139465 }
139466 
139467 /*
139468 ** Register the fts3tok module with database connection db. Return SQLITE_OK
139469 ** if successful or an error code if sqlite3_create_module() fails.
139470 */
139471 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
139472   static const sqlite3_module fts3tok_module = {
139473      0,                           /* iVersion      */
139474      fts3tokConnectMethod,        /* xCreate       */
139475      fts3tokConnectMethod,        /* xConnect      */
139476      fts3tokBestIndexMethod,      /* xBestIndex    */
139477      fts3tokDisconnectMethod,     /* xDisconnect   */
139478      fts3tokDisconnectMethod,     /* xDestroy      */
139479      fts3tokOpenMethod,           /* xOpen         */
139480      fts3tokCloseMethod,          /* xClose        */
139481      fts3tokFilterMethod,         /* xFilter       */
139482      fts3tokNextMethod,           /* xNext         */
139483      fts3tokEofMethod,            /* xEof          */
139484      fts3tokColumnMethod,         /* xColumn       */
139485      fts3tokRowidMethod,          /* xRowid        */
139486      0,                           /* xUpdate       */
139487      0,                           /* xBegin        */
139488      0,                           /* xSync         */
139489      0,                           /* xCommit       */
139490      0,                           /* xRollback     */
139491      0,                           /* xFindFunction */
139492      0,                           /* xRename       */
139493      0,                           /* xSavepoint    */
139494      0,                           /* xRelease      */
139495      0                            /* xRollbackTo   */
139496   };
139497   int rc;                         /* Return code */
139498 
139499   rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
139500   return rc;
139501 }
139502 
139503 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
139504 
139505 /************** End of fts3_tokenize_vtab.c **********************************/
139506 /************** Begin file fts3_write.c **************************************/
139507 /*
139508 ** 2009 Oct 23
139509 **
139510 ** The author disclaims copyright to this source code.  In place of
139511 ** a legal notice, here is a blessing:
139512 **
139513 **    May you do good and not evil.
139514 **    May you find forgiveness for yourself and forgive others.
139515 **    May you share freely, never taking more than you give.
139516 **
139517 ******************************************************************************
139518 **
139519 ** This file is part of the SQLite FTS3 extension module. Specifically,
139520 ** this file contains code to insert, update and delete rows from FTS3
139521 ** tables. It also contains code to merge FTS3 b-tree segments. Some
139522 ** of the sub-routines used to merge segments are also used by the query
139523 ** code in fts3.c.
139524 */
139525 
139526 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
139527 
139528 /* #include <string.h> */
139529 /* #include <assert.h> */
139530 /* #include <stdlib.h> */
139531 
139532 
139533 #define FTS_MAX_APPENDABLE_HEIGHT 16
139534 
139535 /*
139536 ** When full-text index nodes are loaded from disk, the buffer that they
139537 ** are loaded into has the following number of bytes of padding at the end
139538 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
139539 ** of 920 bytes is allocated for it.
139540 **
139541 ** This means that if we have a pointer into a buffer containing node data,
139542 ** it is always safe to read up to two varints from it without risking an
139543 ** overread, even if the node data is corrupted.
139544 */
139545 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
139546 
139547 /*
139548 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
139549 ** memory incrementally instead of all at once. This can be a big performance
139550 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
139551 ** method before retrieving all query results (as may happen, for example,
139552 ** if a query has a LIMIT clause).
139553 **
139554 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
139555 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
139556 ** The code is written so that the hard lower-limit for each of these values
139557 ** is 1. Clearly such small values would be inefficient, but can be useful
139558 ** for testing purposes.
139559 **
139560 ** If this module is built with SQLITE_TEST defined, these constants may
139561 ** be overridden at runtime for testing purposes. File fts3_test.c contains
139562 ** a Tcl interface to read and write the values.
139563 */
139564 #ifdef SQLITE_TEST
139565 int test_fts3_node_chunksize = (4*1024);
139566 int test_fts3_node_chunk_threshold = (4*1024)*4;
139567 # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
139568 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
139569 #else
139570 # define FTS3_NODE_CHUNKSIZE (4*1024)
139571 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
139572 #endif
139573 
139574 /*
139575 ** The two values that may be meaningfully bound to the :1 parameter in
139576 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
139577 */
139578 #define FTS_STAT_DOCTOTAL      0
139579 #define FTS_STAT_INCRMERGEHINT 1
139580 #define FTS_STAT_AUTOINCRMERGE 2
139581 
139582 /*
139583 ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
139584 ** and incremental merge operation that takes place. This is used for
139585 ** debugging FTS only, it should not usually be turned on in production
139586 ** systems.
139587 */
139588 #ifdef FTS3_LOG_MERGES
139589 static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
139590   sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
139591 }
139592 #else
139593 #define fts3LogMerge(x, y)
139594 #endif
139595 
139596 
139597 typedef struct PendingList PendingList;
139598 typedef struct SegmentNode SegmentNode;
139599 typedef struct SegmentWriter SegmentWriter;
139600 
139601 /*
139602 ** An instance of the following data structure is used to build doclists
139603 ** incrementally. See function fts3PendingListAppend() for details.
139604 */
139605 struct PendingList {
139606   int nData;
139607   char *aData;
139608   int nSpace;
139609   sqlite3_int64 iLastDocid;
139610   sqlite3_int64 iLastCol;
139611   sqlite3_int64 iLastPos;
139612 };
139613 
139614 
139615 /*
139616 ** Each cursor has a (possibly empty) linked list of the following objects.
139617 */
139618 struct Fts3DeferredToken {
139619   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
139620   int iCol;                       /* Column token must occur in */
139621   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
139622   PendingList *pList;             /* Doclist is assembled here */
139623 };
139624 
139625 /*
139626 ** An instance of this structure is used to iterate through the terms on
139627 ** a contiguous set of segment b-tree leaf nodes. Although the details of
139628 ** this structure are only manipulated by code in this file, opaque handles
139629 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
139630 ** terms when querying the full-text index. See functions:
139631 **
139632 **   sqlite3Fts3SegReaderNew()
139633 **   sqlite3Fts3SegReaderFree()
139634 **   sqlite3Fts3SegReaderIterate()
139635 **
139636 ** Methods used to manipulate Fts3SegReader structures:
139637 **
139638 **   fts3SegReaderNext()
139639 **   fts3SegReaderFirstDocid()
139640 **   fts3SegReaderNextDocid()
139641 */
139642 struct Fts3SegReader {
139643   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
139644   u8 bLookup;                     /* True for a lookup only */
139645   u8 rootOnly;                    /* True for a root-only reader */
139646 
139647   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
139648   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
139649   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
139650   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
139651 
139652   char *aNode;                    /* Pointer to node data (or NULL) */
139653   int nNode;                      /* Size of buffer at aNode (or 0) */
139654   int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
139655   sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
139656 
139657   Fts3HashElem **ppNextElem;
139658 
139659   /* Variables set by fts3SegReaderNext(). These may be read directly
139660   ** by the caller. They are valid from the time SegmentReaderNew() returns
139661   ** until SegmentReaderNext() returns something other than SQLITE_OK
139662   ** (i.e. SQLITE_DONE).
139663   */
139664   int nTerm;                      /* Number of bytes in current term */
139665   char *zTerm;                    /* Pointer to current term */
139666   int nTermAlloc;                 /* Allocated size of zTerm buffer */
139667   char *aDoclist;                 /* Pointer to doclist of current entry */
139668   int nDoclist;                   /* Size of doclist in current entry */
139669 
139670   /* The following variables are used by fts3SegReaderNextDocid() to iterate
139671   ** through the current doclist (aDoclist/nDoclist).
139672   */
139673   char *pOffsetList;
139674   int nOffsetList;                /* For descending pending seg-readers only */
139675   sqlite3_int64 iDocid;
139676 };
139677 
139678 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
139679 #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
139680 
139681 /*
139682 ** An instance of this structure is used to create a segment b-tree in the
139683 ** database. The internal details of this type are only accessed by the
139684 ** following functions:
139685 **
139686 **   fts3SegWriterAdd()
139687 **   fts3SegWriterFlush()
139688 **   fts3SegWriterFree()
139689 */
139690 struct SegmentWriter {
139691   SegmentNode *pTree;             /* Pointer to interior tree structure */
139692   sqlite3_int64 iFirst;           /* First slot in %_segments written */
139693   sqlite3_int64 iFree;            /* Next free slot in %_segments */
139694   char *zTerm;                    /* Pointer to previous term buffer */
139695   int nTerm;                      /* Number of bytes in zTerm */
139696   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
139697   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
139698   int nSize;                      /* Size of allocation at aData */
139699   int nData;                      /* Bytes of data in aData */
139700   char *aData;                    /* Pointer to block from malloc() */
139701   i64 nLeafData;                  /* Number of bytes of leaf data written */
139702 };
139703 
139704 /*
139705 ** Type SegmentNode is used by the following three functions to create
139706 ** the interior part of the segment b+-tree structures (everything except
139707 ** the leaf nodes). These functions and type are only ever used by code
139708 ** within the fts3SegWriterXXX() family of functions described above.
139709 **
139710 **   fts3NodeAddTerm()
139711 **   fts3NodeWrite()
139712 **   fts3NodeFree()
139713 **
139714 ** When a b+tree is written to the database (either as a result of a merge
139715 ** or the pending-terms table being flushed), leaves are written into the
139716 ** database file as soon as they are completely populated. The interior of
139717 ** the tree is assembled in memory and written out only once all leaves have
139718 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
139719 ** very large, meaning that the interior of the tree consumes relatively
139720 ** little memory.
139721 */
139722 struct SegmentNode {
139723   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
139724   SegmentNode *pRight;            /* Pointer to right-sibling */
139725   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
139726   int nEntry;                     /* Number of terms written to node so far */
139727   char *zTerm;                    /* Pointer to previous term buffer */
139728   int nTerm;                      /* Number of bytes in zTerm */
139729   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
139730   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
139731   int nData;                      /* Bytes of valid data so far */
139732   char *aData;                    /* Node data */
139733 };
139734 
139735 /*
139736 ** Valid values for the second argument to fts3SqlStmt().
139737 */
139738 #define SQL_DELETE_CONTENT             0
139739 #define SQL_IS_EMPTY                   1
139740 #define SQL_DELETE_ALL_CONTENT         2
139741 #define SQL_DELETE_ALL_SEGMENTS        3
139742 #define SQL_DELETE_ALL_SEGDIR          4
139743 #define SQL_DELETE_ALL_DOCSIZE         5
139744 #define SQL_DELETE_ALL_STAT            6
139745 #define SQL_SELECT_CONTENT_BY_ROWID    7
139746 #define SQL_NEXT_SEGMENT_INDEX         8
139747 #define SQL_INSERT_SEGMENTS            9
139748 #define SQL_NEXT_SEGMENTS_ID          10
139749 #define SQL_INSERT_SEGDIR             11
139750 #define SQL_SELECT_LEVEL              12
139751 #define SQL_SELECT_LEVEL_RANGE        13
139752 #define SQL_SELECT_LEVEL_COUNT        14
139753 #define SQL_SELECT_SEGDIR_MAX_LEVEL   15
139754 #define SQL_DELETE_SEGDIR_LEVEL       16
139755 #define SQL_DELETE_SEGMENTS_RANGE     17
139756 #define SQL_CONTENT_INSERT            18
139757 #define SQL_DELETE_DOCSIZE            19
139758 #define SQL_REPLACE_DOCSIZE           20
139759 #define SQL_SELECT_DOCSIZE            21
139760 #define SQL_SELECT_STAT               22
139761 #define SQL_REPLACE_STAT              23
139762 
139763 #define SQL_SELECT_ALL_PREFIX_LEVEL   24
139764 #define SQL_DELETE_ALL_TERMS_SEGDIR   25
139765 #define SQL_DELETE_SEGDIR_RANGE       26
139766 #define SQL_SELECT_ALL_LANGID         27
139767 #define SQL_FIND_MERGE_LEVEL          28
139768 #define SQL_MAX_LEAF_NODE_ESTIMATE    29
139769 #define SQL_DELETE_SEGDIR_ENTRY       30
139770 #define SQL_SHIFT_SEGDIR_ENTRY        31
139771 #define SQL_SELECT_SEGDIR             32
139772 #define SQL_CHOMP_SEGDIR              33
139773 #define SQL_SEGMENT_IS_APPENDABLE     34
139774 #define SQL_SELECT_INDEXES            35
139775 #define SQL_SELECT_MXLEVEL            36
139776 
139777 #define SQL_SELECT_LEVEL_RANGE2       37
139778 #define SQL_UPDATE_LEVEL_IDX          38
139779 #define SQL_UPDATE_LEVEL              39
139780 
139781 /*
139782 ** This function is used to obtain an SQLite prepared statement handle
139783 ** for the statement identified by the second argument. If successful,
139784 ** *pp is set to the requested statement handle and SQLITE_OK returned.
139785 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
139786 **
139787 ** If argument apVal is not NULL, then it must point to an array with
139788 ** at least as many entries as the requested statement has bound
139789 ** parameters. The values are bound to the statements parameters before
139790 ** returning.
139791 */
139792 static int fts3SqlStmt(
139793   Fts3Table *p,                   /* Virtual table handle */
139794   int eStmt,                      /* One of the SQL_XXX constants above */
139795   sqlite3_stmt **pp,              /* OUT: Statement handle */
139796   sqlite3_value **apVal           /* Values to bind to statement */
139797 ){
139798   const char *azSql[] = {
139799 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
139800 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
139801 /* 2  */  "DELETE FROM %Q.'%q_content'",
139802 /* 3  */  "DELETE FROM %Q.'%q_segments'",
139803 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
139804 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
139805 /* 6  */  "DELETE FROM %Q.'%q_stat'",
139806 /* 7  */  "SELECT %s WHERE rowid=?",
139807 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
139808 /* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
139809 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
139810 /* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
139811 
139812           /* Return segments in order from oldest to newest.*/
139813 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
139814             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
139815 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
139816             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
139817             "ORDER BY level DESC, idx ASC",
139818 
139819 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
139820 /* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
139821 
139822 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
139823 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
139824 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
139825 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
139826 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
139827 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
139828 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
139829 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
139830 /* 24 */  "",
139831 /* 25 */  "",
139832 
139833 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
139834 /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
139835 
139836 /* This statement is used to determine which level to read the input from
139837 ** when performing an incremental merge. It returns the absolute level number
139838 ** of the oldest level in the db that contains at least ? segments. Or,
139839 ** if no level in the FTS index contains more than ? segments, the statement
139840 ** returns zero rows.  */
139841 /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
139842          "  ORDER BY (level %% 1024) ASC LIMIT 1",
139843 
139844 /* Estimate the upper limit on the number of leaf nodes in a new segment
139845 ** created by merging the oldest :2 segments from absolute level :1. See
139846 ** function sqlite3Fts3Incrmerge() for details.  */
139847 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
139848          "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
139849 
139850 /* SQL_DELETE_SEGDIR_ENTRY
139851 **   Delete the %_segdir entry on absolute level :1 with index :2.  */
139852 /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
139853 
139854 /* SQL_SHIFT_SEGDIR_ENTRY
139855 **   Modify the idx value for the segment with idx=:3 on absolute level :2
139856 **   to :1.  */
139857 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
139858 
139859 /* SQL_SELECT_SEGDIR
139860 **   Read a single entry from the %_segdir table. The entry from absolute
139861 **   level :1 with index value :2.  */
139862 /* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
139863             "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
139864 
139865 /* SQL_CHOMP_SEGDIR
139866 **   Update the start_block (:1) and root (:2) fields of the %_segdir
139867 **   entry located on absolute level :3 with index :4.  */
139868 /* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
139869             "WHERE level = ? AND idx = ?",
139870 
139871 /* SQL_SEGMENT_IS_APPENDABLE
139872 **   Return a single row if the segment with end_block=? is appendable. Or
139873 **   no rows otherwise.  */
139874 /* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
139875 
139876 /* SQL_SELECT_INDEXES
139877 **   Return the list of valid segment indexes for absolute level ?  */
139878 /* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
139879 
139880 /* SQL_SELECT_MXLEVEL
139881 **   Return the largest relative level in the FTS index or indexes.  */
139882 /* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
139883 
139884           /* Return segments in order from oldest to newest.*/
139885 /* 37 */  "SELECT level, idx, end_block "
139886             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
139887             "ORDER BY level DESC, idx ASC",
139888 
139889           /* Update statements used while promoting segments */
139890 /* 38 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
139891             "WHERE level=? AND idx=?",
139892 /* 39 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
139893 
139894   };
139895   int rc = SQLITE_OK;
139896   sqlite3_stmt *pStmt;
139897 
139898   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
139899   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
139900 
139901   pStmt = p->aStmt[eStmt];
139902   if( !pStmt ){
139903     char *zSql;
139904     if( eStmt==SQL_CONTENT_INSERT ){
139905       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
139906     }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
139907       zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
139908     }else{
139909       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
139910     }
139911     if( !zSql ){
139912       rc = SQLITE_NOMEM;
139913     }else{
139914       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
139915       sqlite3_free(zSql);
139916       assert( rc==SQLITE_OK || pStmt==0 );
139917       p->aStmt[eStmt] = pStmt;
139918     }
139919   }
139920   if( apVal ){
139921     int i;
139922     int nParam = sqlite3_bind_parameter_count(pStmt);
139923     for(i=0; rc==SQLITE_OK && i<nParam; i++){
139924       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
139925     }
139926   }
139927   *pp = pStmt;
139928   return rc;
139929 }
139930 
139931 
139932 static int fts3SelectDocsize(
139933   Fts3Table *pTab,                /* FTS3 table handle */
139934   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
139935   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
139936 ){
139937   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
139938   int rc;                         /* Return code */
139939 
139940   rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
139941   if( rc==SQLITE_OK ){
139942     sqlite3_bind_int64(pStmt, 1, iDocid);
139943     rc = sqlite3_step(pStmt);
139944     if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
139945       rc = sqlite3_reset(pStmt);
139946       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
139947       pStmt = 0;
139948     }else{
139949       rc = SQLITE_OK;
139950     }
139951   }
139952 
139953   *ppStmt = pStmt;
139954   return rc;
139955 }
139956 
139957 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
139958   Fts3Table *pTab,                /* Fts3 table handle */
139959   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
139960 ){
139961   sqlite3_stmt *pStmt = 0;
139962   int rc;
139963   rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
139964   if( rc==SQLITE_OK ){
139965     sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
139966     if( sqlite3_step(pStmt)!=SQLITE_ROW
139967      || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
139968     ){
139969       rc = sqlite3_reset(pStmt);
139970       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
139971       pStmt = 0;
139972     }
139973   }
139974   *ppStmt = pStmt;
139975   return rc;
139976 }
139977 
139978 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
139979   Fts3Table *pTab,                /* Fts3 table handle */
139980   sqlite3_int64 iDocid,           /* Docid to read size data for */
139981   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
139982 ){
139983   return fts3SelectDocsize(pTab, iDocid, ppStmt);
139984 }
139985 
139986 /*
139987 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
139988 ** array apVal[] to the SQL statement identified by eStmt, the statement
139989 ** is executed.
139990 **
139991 ** Returns SQLITE_OK if the statement is successfully executed, or an
139992 ** SQLite error code otherwise.
139993 */
139994 static void fts3SqlExec(
139995   int *pRC,                /* Result code */
139996   Fts3Table *p,            /* The FTS3 table */
139997   int eStmt,               /* Index of statement to evaluate */
139998   sqlite3_value **apVal    /* Parameters to bind */
139999 ){
140000   sqlite3_stmt *pStmt;
140001   int rc;
140002   if( *pRC ) return;
140003   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
140004   if( rc==SQLITE_OK ){
140005     sqlite3_step(pStmt);
140006     rc = sqlite3_reset(pStmt);
140007   }
140008   *pRC = rc;
140009 }
140010 
140011 
140012 /*
140013 ** This function ensures that the caller has obtained an exclusive
140014 ** shared-cache table-lock on the %_segdir table. This is required before
140015 ** writing data to the fts3 table. If this lock is not acquired first, then
140016 ** the caller may end up attempting to take this lock as part of committing
140017 ** a transaction, causing SQLite to return SQLITE_LOCKED or
140018 ** LOCKED_SHAREDCACHEto a COMMIT command.
140019 **
140020 ** It is best to avoid this because if FTS3 returns any error when
140021 ** committing a transaction, the whole transaction will be rolled back.
140022 ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
140023 ** It can still happen if the user locks the underlying tables directly
140024 ** instead of accessing them via FTS.
140025 */
140026 static int fts3Writelock(Fts3Table *p){
140027   int rc = SQLITE_OK;
140028 
140029   if( p->nPendingData==0 ){
140030     sqlite3_stmt *pStmt;
140031     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
140032     if( rc==SQLITE_OK ){
140033       sqlite3_bind_null(pStmt, 1);
140034       sqlite3_step(pStmt);
140035       rc = sqlite3_reset(pStmt);
140036     }
140037   }
140038 
140039   return rc;
140040 }
140041 
140042 /*
140043 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
140044 ** Within each language id, a separate index is maintained to store the
140045 ** document terms, and each configured prefix size (configured the FTS
140046 ** "prefix=" option). And each index consists of multiple levels ("relative
140047 ** levels").
140048 **
140049 ** All three of these values (the language id, the specific index and the
140050 ** level within the index) are encoded in 64-bit integer values stored
140051 ** in the %_segdir table on disk. This function is used to convert three
140052 ** separate component values into the single 64-bit integer value that
140053 ** can be used to query the %_segdir table.
140054 **
140055 ** Specifically, each language-id/index combination is allocated 1024
140056 ** 64-bit integer level values ("absolute levels"). The main terms index
140057 ** for language-id 0 is allocate values 0-1023. The first prefix index
140058 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
140059 ** Language 1 indexes are allocated immediately following language 0.
140060 **
140061 ** So, for a system with nPrefix prefix indexes configured, the block of
140062 ** absolute levels that corresponds to language-id iLangid and index
140063 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
140064 */
140065 static sqlite3_int64 getAbsoluteLevel(
140066   Fts3Table *p,                   /* FTS3 table handle */
140067   int iLangid,                    /* Language id */
140068   int iIndex,                     /* Index in p->aIndex[] */
140069   int iLevel                      /* Level of segments */
140070 ){
140071   sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
140072   assert( iLangid>=0 );
140073   assert( p->nIndex>0 );
140074   assert( iIndex>=0 && iIndex<p->nIndex );
140075 
140076   iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
140077   return iBase + iLevel;
140078 }
140079 
140080 /*
140081 ** Set *ppStmt to a statement handle that may be used to iterate through
140082 ** all rows in the %_segdir table, from oldest to newest. If successful,
140083 ** return SQLITE_OK. If an error occurs while preparing the statement,
140084 ** return an SQLite error code.
140085 **
140086 ** There is only ever one instance of this SQL statement compiled for
140087 ** each FTS3 table.
140088 **
140089 ** The statement returns the following columns from the %_segdir table:
140090 **
140091 **   0: idx
140092 **   1: start_block
140093 **   2: leaves_end_block
140094 **   3: end_block
140095 **   4: root
140096 */
140097 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
140098   Fts3Table *p,                   /* FTS3 table */
140099   int iLangid,                    /* Language being queried */
140100   int iIndex,                     /* Index for p->aIndex[] */
140101   int iLevel,                     /* Level to select (relative level) */
140102   sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
140103 ){
140104   int rc;
140105   sqlite3_stmt *pStmt = 0;
140106 
140107   assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
140108   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
140109   assert( iIndex>=0 && iIndex<p->nIndex );
140110 
140111   if( iLevel<0 ){
140112     /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
140113     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
140114     if( rc==SQLITE_OK ){
140115       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
140116       sqlite3_bind_int64(pStmt, 2,
140117           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
140118       );
140119     }
140120   }else{
140121     /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
140122     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
140123     if( rc==SQLITE_OK ){
140124       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
140125     }
140126   }
140127   *ppStmt = pStmt;
140128   return rc;
140129 }
140130 
140131 
140132 /*
140133 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
140134 ** if successful, or an SQLite error code otherwise.
140135 **
140136 ** This function also serves to allocate the PendingList structure itself.
140137 ** For example, to create a new PendingList structure containing two
140138 ** varints:
140139 **
140140 **   PendingList *p = 0;
140141 **   fts3PendingListAppendVarint(&p, 1);
140142 **   fts3PendingListAppendVarint(&p, 2);
140143 */
140144 static int fts3PendingListAppendVarint(
140145   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
140146   sqlite3_int64 i                 /* Value to append to data */
140147 ){
140148   PendingList *p = *pp;
140149 
140150   /* Allocate or grow the PendingList as required. */
140151   if( !p ){
140152     p = sqlite3_malloc(sizeof(*p) + 100);
140153     if( !p ){
140154       return SQLITE_NOMEM;
140155     }
140156     p->nSpace = 100;
140157     p->aData = (char *)&p[1];
140158     p->nData = 0;
140159   }
140160   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
140161     int nNew = p->nSpace * 2;
140162     p = sqlite3_realloc(p, sizeof(*p) + nNew);
140163     if( !p ){
140164       sqlite3_free(*pp);
140165       *pp = 0;
140166       return SQLITE_NOMEM;
140167     }
140168     p->nSpace = nNew;
140169     p->aData = (char *)&p[1];
140170   }
140171 
140172   /* Append the new serialized varint to the end of the list. */
140173   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
140174   p->aData[p->nData] = '\0';
140175   *pp = p;
140176   return SQLITE_OK;
140177 }
140178 
140179 /*
140180 ** Add a docid/column/position entry to a PendingList structure. Non-zero
140181 ** is returned if the structure is sqlite3_realloced as part of adding
140182 ** the entry. Otherwise, zero.
140183 **
140184 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
140185 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
140186 ** it is set to SQLITE_OK.
140187 */
140188 static int fts3PendingListAppend(
140189   PendingList **pp,               /* IN/OUT: PendingList structure */
140190   sqlite3_int64 iDocid,           /* Docid for entry to add */
140191   sqlite3_int64 iCol,             /* Column for entry to add */
140192   sqlite3_int64 iPos,             /* Position of term for entry to add */
140193   int *pRc                        /* OUT: Return code */
140194 ){
140195   PendingList *p = *pp;
140196   int rc = SQLITE_OK;
140197 
140198   assert( !p || p->iLastDocid<=iDocid );
140199 
140200   if( !p || p->iLastDocid!=iDocid ){
140201     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
140202     if( p ){
140203       assert( p->nData<p->nSpace );
140204       assert( p->aData[p->nData]==0 );
140205       p->nData++;
140206     }
140207     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
140208       goto pendinglistappend_out;
140209     }
140210     p->iLastCol = -1;
140211     p->iLastPos = 0;
140212     p->iLastDocid = iDocid;
140213   }
140214   if( iCol>0 && p->iLastCol!=iCol ){
140215     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
140216      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
140217     ){
140218       goto pendinglistappend_out;
140219     }
140220     p->iLastCol = iCol;
140221     p->iLastPos = 0;
140222   }
140223   if( iCol>=0 ){
140224     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
140225     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
140226     if( rc==SQLITE_OK ){
140227       p->iLastPos = iPos;
140228     }
140229   }
140230 
140231  pendinglistappend_out:
140232   *pRc = rc;
140233   if( p!=*pp ){
140234     *pp = p;
140235     return 1;
140236   }
140237   return 0;
140238 }
140239 
140240 /*
140241 ** Free a PendingList object allocated by fts3PendingListAppend().
140242 */
140243 static void fts3PendingListDelete(PendingList *pList){
140244   sqlite3_free(pList);
140245 }
140246 
140247 /*
140248 ** Add an entry to one of the pending-terms hash tables.
140249 */
140250 static int fts3PendingTermsAddOne(
140251   Fts3Table *p,
140252   int iCol,
140253   int iPos,
140254   Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
140255   const char *zToken,
140256   int nToken
140257 ){
140258   PendingList *pList;
140259   int rc = SQLITE_OK;
140260 
140261   pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
140262   if( pList ){
140263     p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
140264   }
140265   if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
140266     if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
140267       /* Malloc failed while inserting the new entry. This can only
140268       ** happen if there was no previous entry for this token.
140269       */
140270       assert( 0==fts3HashFind(pHash, zToken, nToken) );
140271       sqlite3_free(pList);
140272       rc = SQLITE_NOMEM;
140273     }
140274   }
140275   if( rc==SQLITE_OK ){
140276     p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
140277   }
140278   return rc;
140279 }
140280 
140281 /*
140282 ** Tokenize the nul-terminated string zText and add all tokens to the
140283 ** pending-terms hash-table. The docid used is that currently stored in
140284 ** p->iPrevDocid, and the column is specified by argument iCol.
140285 **
140286 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
140287 */
140288 static int fts3PendingTermsAdd(
140289   Fts3Table *p,                   /* Table into which text will be inserted */
140290   int iLangid,                    /* Language id to use */
140291   const char *zText,              /* Text of document to be inserted */
140292   int iCol,                       /* Column into which text is being inserted */
140293   u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
140294 ){
140295   int rc;
140296   int iStart = 0;
140297   int iEnd = 0;
140298   int iPos = 0;
140299   int nWord = 0;
140300 
140301   char const *zToken;
140302   int nToken = 0;
140303 
140304   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
140305   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
140306   sqlite3_tokenizer_cursor *pCsr;
140307   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
140308       const char**,int*,int*,int*,int*);
140309 
140310   assert( pTokenizer && pModule );
140311 
140312   /* If the user has inserted a NULL value, this function may be called with
140313   ** zText==0. In this case, add zero token entries to the hash table and
140314   ** return early. */
140315   if( zText==0 ){
140316     *pnWord = 0;
140317     return SQLITE_OK;
140318   }
140319 
140320   rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
140321   if( rc!=SQLITE_OK ){
140322     return rc;
140323   }
140324 
140325   xNext = pModule->xNext;
140326   while( SQLITE_OK==rc
140327       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
140328   ){
140329     int i;
140330     if( iPos>=nWord ) nWord = iPos+1;
140331 
140332     /* Positions cannot be negative; we use -1 as a terminator internally.
140333     ** Tokens must have a non-zero length.
140334     */
140335     if( iPos<0 || !zToken || nToken<=0 ){
140336       rc = SQLITE_ERROR;
140337       break;
140338     }
140339 
140340     /* Add the term to the terms index */
140341     rc = fts3PendingTermsAddOne(
140342         p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
140343     );
140344 
140345     /* Add the term to each of the prefix indexes that it is not too
140346     ** short for. */
140347     for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
140348       struct Fts3Index *pIndex = &p->aIndex[i];
140349       if( nToken<pIndex->nPrefix ) continue;
140350       rc = fts3PendingTermsAddOne(
140351           p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
140352       );
140353     }
140354   }
140355 
140356   pModule->xClose(pCsr);
140357   *pnWord += nWord;
140358   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
140359 }
140360 
140361 /*
140362 ** Calling this function indicates that subsequent calls to
140363 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
140364 ** contents of the document with docid iDocid.
140365 */
140366 static int fts3PendingTermsDocid(
140367   Fts3Table *p,                   /* Full-text table handle */
140368   int iLangid,                    /* Language id of row being written */
140369   sqlite_int64 iDocid             /* Docid of row being written */
140370 ){
140371   assert( iLangid>=0 );
140372 
140373   /* TODO(shess) Explore whether partially flushing the buffer on
140374   ** forced-flush would provide better performance.  I suspect that if
140375   ** we ordered the doclists by size and flushed the largest until the
140376   ** buffer was half empty, that would let the less frequent terms
140377   ** generate longer doclists.
140378   */
140379   if( iDocid<=p->iPrevDocid
140380    || p->iPrevLangid!=iLangid
140381    || p->nPendingData>p->nMaxPendingData
140382   ){
140383     int rc = sqlite3Fts3PendingTermsFlush(p);
140384     if( rc!=SQLITE_OK ) return rc;
140385   }
140386   p->iPrevDocid = iDocid;
140387   p->iPrevLangid = iLangid;
140388   return SQLITE_OK;
140389 }
140390 
140391 /*
140392 ** Discard the contents of the pending-terms hash tables.
140393 */
140394 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
140395   int i;
140396   for(i=0; i<p->nIndex; i++){
140397     Fts3HashElem *pElem;
140398     Fts3Hash *pHash = &p->aIndex[i].hPending;
140399     for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
140400       PendingList *pList = (PendingList *)fts3HashData(pElem);
140401       fts3PendingListDelete(pList);
140402     }
140403     fts3HashClear(pHash);
140404   }
140405   p->nPendingData = 0;
140406 }
140407 
140408 /*
140409 ** This function is called by the xUpdate() method as part of an INSERT
140410 ** operation. It adds entries for each term in the new record to the
140411 ** pendingTerms hash table.
140412 **
140413 ** Argument apVal is the same as the similarly named argument passed to
140414 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
140415 */
140416 static int fts3InsertTerms(
140417   Fts3Table *p,
140418   int iLangid,
140419   sqlite3_value **apVal,
140420   u32 *aSz
140421 ){
140422   int i;                          /* Iterator variable */
140423   for(i=2; i<p->nColumn+2; i++){
140424     int iCol = i-2;
140425     if( p->abNotindexed[iCol]==0 ){
140426       const char *zText = (const char *)sqlite3_value_text(apVal[i]);
140427       int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
140428       if( rc!=SQLITE_OK ){
140429         return rc;
140430       }
140431       aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
140432     }
140433   }
140434   return SQLITE_OK;
140435 }
140436 
140437 /*
140438 ** This function is called by the xUpdate() method for an INSERT operation.
140439 ** The apVal parameter is passed a copy of the apVal argument passed by
140440 ** SQLite to the xUpdate() method. i.e:
140441 **
140442 **   apVal[0]                Not used for INSERT.
140443 **   apVal[1]                rowid
140444 **   apVal[2]                Left-most user-defined column
140445 **   ...
140446 **   apVal[p->nColumn+1]     Right-most user-defined column
140447 **   apVal[p->nColumn+2]     Hidden column with same name as table
140448 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
140449 **   apVal[p->nColumn+4]     Hidden languageid column
140450 */
140451 static int fts3InsertData(
140452   Fts3Table *p,                   /* Full-text table */
140453   sqlite3_value **apVal,          /* Array of values to insert */
140454   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
140455 ){
140456   int rc;                         /* Return code */
140457   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
140458 
140459   if( p->zContentTbl ){
140460     sqlite3_value *pRowid = apVal[p->nColumn+3];
140461     if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
140462       pRowid = apVal[1];
140463     }
140464     if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
140465       return SQLITE_CONSTRAINT;
140466     }
140467     *piDocid = sqlite3_value_int64(pRowid);
140468     return SQLITE_OK;
140469   }
140470 
140471   /* Locate the statement handle used to insert data into the %_content
140472   ** table. The SQL for this statement is:
140473   **
140474   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
140475   **
140476   ** The statement features N '?' variables, where N is the number of user
140477   ** defined columns in the FTS3 table, plus one for the docid field.
140478   */
140479   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
140480   if( rc==SQLITE_OK && p->zLanguageid ){
140481     rc = sqlite3_bind_int(
140482         pContentInsert, p->nColumn+2,
140483         sqlite3_value_int(apVal[p->nColumn+4])
140484     );
140485   }
140486   if( rc!=SQLITE_OK ) return rc;
140487 
140488   /* There is a quirk here. The users INSERT statement may have specified
140489   ** a value for the "rowid" field, for the "docid" field, or for both.
140490   ** Which is a problem, since "rowid" and "docid" are aliases for the
140491   ** same value. For example:
140492   **
140493   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
140494   **
140495   ** In FTS3, this is an error. It is an error to specify non-NULL values
140496   ** for both docid and some other rowid alias.
140497   */
140498   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
140499     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
140500      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
140501     ){
140502       /* A rowid/docid conflict. */
140503       return SQLITE_ERROR;
140504     }
140505     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
140506     if( rc!=SQLITE_OK ) return rc;
140507   }
140508 
140509   /* Execute the statement to insert the record. Set *piDocid to the
140510   ** new docid value.
140511   */
140512   sqlite3_step(pContentInsert);
140513   rc = sqlite3_reset(pContentInsert);
140514 
140515   *piDocid = sqlite3_last_insert_rowid(p->db);
140516   return rc;
140517 }
140518 
140519 
140520 
140521 /*
140522 ** Remove all data from the FTS3 table. Clear the hash table containing
140523 ** pending terms.
140524 */
140525 static int fts3DeleteAll(Fts3Table *p, int bContent){
140526   int rc = SQLITE_OK;             /* Return code */
140527 
140528   /* Discard the contents of the pending-terms hash table. */
140529   sqlite3Fts3PendingTermsClear(p);
140530 
140531   /* Delete everything from the shadow tables. Except, leave %_content as
140532   ** is if bContent is false.  */
140533   assert( p->zContentTbl==0 || bContent==0 );
140534   if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
140535   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
140536   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
140537   if( p->bHasDocsize ){
140538     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
140539   }
140540   if( p->bHasStat ){
140541     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
140542   }
140543   return rc;
140544 }
140545 
140546 /*
140547 **
140548 */
140549 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
140550   int iLangid = 0;
140551   if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
140552   return iLangid;
140553 }
140554 
140555 /*
140556 ** The first element in the apVal[] array is assumed to contain the docid
140557 ** (an integer) of a row about to be deleted. Remove all terms from the
140558 ** full-text index.
140559 */
140560 static void fts3DeleteTerms(
140561   int *pRC,               /* Result code */
140562   Fts3Table *p,           /* The FTS table to delete from */
140563   sqlite3_value *pRowid,  /* The docid to be deleted */
140564   u32 *aSz,               /* Sizes of deleted document written here */
140565   int *pbFound            /* OUT: Set to true if row really does exist */
140566 ){
140567   int rc;
140568   sqlite3_stmt *pSelect;
140569 
140570   assert( *pbFound==0 );
140571   if( *pRC ) return;
140572   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
140573   if( rc==SQLITE_OK ){
140574     if( SQLITE_ROW==sqlite3_step(pSelect) ){
140575       int i;
140576       int iLangid = langidFromSelect(p, pSelect);
140577       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
140578       for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
140579         int iCol = i-1;
140580         if( p->abNotindexed[iCol]==0 ){
140581           const char *zText = (const char *)sqlite3_column_text(pSelect, i);
140582           rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
140583           aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
140584         }
140585       }
140586       if( rc!=SQLITE_OK ){
140587         sqlite3_reset(pSelect);
140588         *pRC = rc;
140589         return;
140590       }
140591       *pbFound = 1;
140592     }
140593     rc = sqlite3_reset(pSelect);
140594   }else{
140595     sqlite3_reset(pSelect);
140596   }
140597   *pRC = rc;
140598 }
140599 
140600 /*
140601 ** Forward declaration to account for the circular dependency between
140602 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
140603 */
140604 static int fts3SegmentMerge(Fts3Table *, int, int, int);
140605 
140606 /*
140607 ** This function allocates a new level iLevel index in the segdir table.
140608 ** Usually, indexes are allocated within a level sequentially starting
140609 ** with 0, so the allocated index is one greater than the value returned
140610 ** by:
140611 **
140612 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
140613 **
140614 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
140615 ** level, they are merged into a single level (iLevel+1) segment and the
140616 ** allocated index is 0.
140617 **
140618 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
140619 ** returned. Otherwise, an SQLite error code is returned.
140620 */
140621 static int fts3AllocateSegdirIdx(
140622   Fts3Table *p,
140623   int iLangid,                    /* Language id */
140624   int iIndex,                     /* Index for p->aIndex */
140625   int iLevel,
140626   int *piIdx
140627 ){
140628   int rc;                         /* Return Code */
140629   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
140630   int iNext = 0;                  /* Result of query pNextIdx */
140631 
140632   assert( iLangid>=0 );
140633   assert( p->nIndex>=1 );
140634 
140635   /* Set variable iNext to the next available segdir index at level iLevel. */
140636   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
140637   if( rc==SQLITE_OK ){
140638     sqlite3_bind_int64(
140639         pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
140640     );
140641     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
140642       iNext = sqlite3_column_int(pNextIdx, 0);
140643     }
140644     rc = sqlite3_reset(pNextIdx);
140645   }
140646 
140647   if( rc==SQLITE_OK ){
140648     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
140649     ** full, merge all segments in level iLevel into a single iLevel+1
140650     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
140651     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
140652     */
140653     if( iNext>=FTS3_MERGE_COUNT ){
140654       fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
140655       rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
140656       *piIdx = 0;
140657     }else{
140658       *piIdx = iNext;
140659     }
140660   }
140661 
140662   return rc;
140663 }
140664 
140665 /*
140666 ** The %_segments table is declared as follows:
140667 **
140668 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
140669 **
140670 ** This function reads data from a single row of the %_segments table. The
140671 ** specific row is identified by the iBlockid parameter. If paBlob is not
140672 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
140673 ** with the contents of the blob stored in the "block" column of the
140674 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
140675 ** to the size of the blob in bytes before returning.
140676 **
140677 ** If an error occurs, or the table does not contain the specified row,
140678 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
140679 ** paBlob is non-NULL, then it is the responsibility of the caller to
140680 ** eventually free the returned buffer.
140681 **
140682 ** This function may leave an open sqlite3_blob* handle in the
140683 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
140684 ** to this function. The handle may be closed by calling the
140685 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
140686 ** performance improvement, but the blob handle should always be closed
140687 ** before control is returned to the user (to prevent a lock being held
140688 ** on the database file for longer than necessary). Thus, any virtual table
140689 ** method (xFilter etc.) that may directly or indirectly call this function
140690 ** must call sqlite3Fts3SegmentsClose() before returning.
140691 */
140692 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
140693   Fts3Table *p,                   /* FTS3 table handle */
140694   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
140695   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
140696   int *pnBlob,                    /* OUT: Size of blob data */
140697   int *pnLoad                     /* OUT: Bytes actually loaded */
140698 ){
140699   int rc;                         /* Return code */
140700 
140701   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
140702   assert( pnBlob );
140703 
140704   if( p->pSegments ){
140705     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
140706   }else{
140707     if( 0==p->zSegmentsTbl ){
140708       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
140709       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
140710     }
140711     rc = sqlite3_blob_open(
140712        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
140713     );
140714   }
140715 
140716   if( rc==SQLITE_OK ){
140717     int nByte = sqlite3_blob_bytes(p->pSegments);
140718     *pnBlob = nByte;
140719     if( paBlob ){
140720       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
140721       if( !aByte ){
140722         rc = SQLITE_NOMEM;
140723       }else{
140724         if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
140725           nByte = FTS3_NODE_CHUNKSIZE;
140726           *pnLoad = nByte;
140727         }
140728         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
140729         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
140730         if( rc!=SQLITE_OK ){
140731           sqlite3_free(aByte);
140732           aByte = 0;
140733         }
140734       }
140735       *paBlob = aByte;
140736     }
140737   }
140738 
140739   return rc;
140740 }
140741 
140742 /*
140743 ** Close the blob handle at p->pSegments, if it is open. See comments above
140744 ** the sqlite3Fts3ReadBlock() function for details.
140745 */
140746 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
140747   sqlite3_blob_close(p->pSegments);
140748   p->pSegments = 0;
140749 }
140750 
140751 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
140752   int nRead;                      /* Number of bytes to read */
140753   int rc;                         /* Return code */
140754 
140755   nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
140756   rc = sqlite3_blob_read(
140757       pReader->pBlob,
140758       &pReader->aNode[pReader->nPopulate],
140759       nRead,
140760       pReader->nPopulate
140761   );
140762 
140763   if( rc==SQLITE_OK ){
140764     pReader->nPopulate += nRead;
140765     memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
140766     if( pReader->nPopulate==pReader->nNode ){
140767       sqlite3_blob_close(pReader->pBlob);
140768       pReader->pBlob = 0;
140769       pReader->nPopulate = 0;
140770     }
140771   }
140772   return rc;
140773 }
140774 
140775 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
140776   int rc = SQLITE_OK;
140777   assert( !pReader->pBlob
140778        || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
140779   );
140780   while( pReader->pBlob && rc==SQLITE_OK
140781      &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
140782   ){
140783     rc = fts3SegReaderIncrRead(pReader);
140784   }
140785   return rc;
140786 }
140787 
140788 /*
140789 ** Set an Fts3SegReader cursor to point at EOF.
140790 */
140791 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
140792   if( !fts3SegReaderIsRootOnly(pSeg) ){
140793     sqlite3_free(pSeg->aNode);
140794     sqlite3_blob_close(pSeg->pBlob);
140795     pSeg->pBlob = 0;
140796   }
140797   pSeg->aNode = 0;
140798 }
140799 
140800 /*
140801 ** Move the iterator passed as the first argument to the next term in the
140802 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
140803 ** SQLITE_DONE. Otherwise, an SQLite error code.
140804 */
140805 static int fts3SegReaderNext(
140806   Fts3Table *p,
140807   Fts3SegReader *pReader,
140808   int bIncr
140809 ){
140810   int rc;                         /* Return code of various sub-routines */
140811   char *pNext;                    /* Cursor variable */
140812   int nPrefix;                    /* Number of bytes in term prefix */
140813   int nSuffix;                    /* Number of bytes in term suffix */
140814 
140815   if( !pReader->aDoclist ){
140816     pNext = pReader->aNode;
140817   }else{
140818     pNext = &pReader->aDoclist[pReader->nDoclist];
140819   }
140820 
140821   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
140822 
140823     if( fts3SegReaderIsPending(pReader) ){
140824       Fts3HashElem *pElem = *(pReader->ppNextElem);
140825       if( pElem==0 ){
140826         pReader->aNode = 0;
140827       }else{
140828         PendingList *pList = (PendingList *)fts3HashData(pElem);
140829         pReader->zTerm = (char *)fts3HashKey(pElem);
140830         pReader->nTerm = fts3HashKeysize(pElem);
140831         pReader->nNode = pReader->nDoclist = pList->nData + 1;
140832         pReader->aNode = pReader->aDoclist = pList->aData;
140833         pReader->ppNextElem++;
140834         assert( pReader->aNode );
140835       }
140836       return SQLITE_OK;
140837     }
140838 
140839     fts3SegReaderSetEof(pReader);
140840 
140841     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
140842     ** blocks have already been traversed.  */
140843     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
140844     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
140845       return SQLITE_OK;
140846     }
140847 
140848     rc = sqlite3Fts3ReadBlock(
140849         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
140850         (bIncr ? &pReader->nPopulate : 0)
140851     );
140852     if( rc!=SQLITE_OK ) return rc;
140853     assert( pReader->pBlob==0 );
140854     if( bIncr && pReader->nPopulate<pReader->nNode ){
140855       pReader->pBlob = p->pSegments;
140856       p->pSegments = 0;
140857     }
140858     pNext = pReader->aNode;
140859   }
140860 
140861   assert( !fts3SegReaderIsPending(pReader) );
140862 
140863   rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
140864   if( rc!=SQLITE_OK ) return rc;
140865 
140866   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
140867   ** safe (no risk of overread) even if the node data is corrupted. */
140868   pNext += fts3GetVarint32(pNext, &nPrefix);
140869   pNext += fts3GetVarint32(pNext, &nSuffix);
140870   if( nPrefix<0 || nSuffix<=0
140871    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
140872   ){
140873     return FTS_CORRUPT_VTAB;
140874   }
140875 
140876   if( nPrefix+nSuffix>pReader->nTermAlloc ){
140877     int nNew = (nPrefix+nSuffix)*2;
140878     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
140879     if( !zNew ){
140880       return SQLITE_NOMEM;
140881     }
140882     pReader->zTerm = zNew;
140883     pReader->nTermAlloc = nNew;
140884   }
140885 
140886   rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
140887   if( rc!=SQLITE_OK ) return rc;
140888 
140889   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
140890   pReader->nTerm = nPrefix+nSuffix;
140891   pNext += nSuffix;
140892   pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
140893   pReader->aDoclist = pNext;
140894   pReader->pOffsetList = 0;
140895 
140896   /* Check that the doclist does not appear to extend past the end of the
140897   ** b-tree node. And that the final byte of the doclist is 0x00. If either
140898   ** of these statements is untrue, then the data structure is corrupt.
140899   */
140900   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
140901    || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
140902   ){
140903     return FTS_CORRUPT_VTAB;
140904   }
140905   return SQLITE_OK;
140906 }
140907 
140908 /*
140909 ** Set the SegReader to point to the first docid in the doclist associated
140910 ** with the current term.
140911 */
140912 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
140913   int rc = SQLITE_OK;
140914   assert( pReader->aDoclist );
140915   assert( !pReader->pOffsetList );
140916   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
140917     u8 bEof = 0;
140918     pReader->iDocid = 0;
140919     pReader->nOffsetList = 0;
140920     sqlite3Fts3DoclistPrev(0,
140921         pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
140922         &pReader->iDocid, &pReader->nOffsetList, &bEof
140923     );
140924   }else{
140925     rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
140926     if( rc==SQLITE_OK ){
140927       int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
140928       pReader->pOffsetList = &pReader->aDoclist[n];
140929     }
140930   }
140931   return rc;
140932 }
140933 
140934 /*
140935 ** Advance the SegReader to point to the next docid in the doclist
140936 ** associated with the current term.
140937 **
140938 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
140939 ** *ppOffsetList is set to point to the first column-offset list
140940 ** in the doclist entry (i.e. immediately past the docid varint).
140941 ** *pnOffsetList is set to the length of the set of column-offset
140942 ** lists, not including the nul-terminator byte. For example:
140943 */
140944 static int fts3SegReaderNextDocid(
140945   Fts3Table *pTab,
140946   Fts3SegReader *pReader,         /* Reader to advance to next docid */
140947   char **ppOffsetList,            /* OUT: Pointer to current position-list */
140948   int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
140949 ){
140950   int rc = SQLITE_OK;
140951   char *p = pReader->pOffsetList;
140952   char c = 0;
140953 
140954   assert( p );
140955 
140956   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
140957     /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
140958     ** Pending-terms doclists are always built up in ascending order, so
140959     ** we have to iterate through them backwards here. */
140960     u8 bEof = 0;
140961     if( ppOffsetList ){
140962       *ppOffsetList = pReader->pOffsetList;
140963       *pnOffsetList = pReader->nOffsetList - 1;
140964     }
140965     sqlite3Fts3DoclistPrev(0,
140966         pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
140967         &pReader->nOffsetList, &bEof
140968     );
140969     if( bEof ){
140970       pReader->pOffsetList = 0;
140971     }else{
140972       pReader->pOffsetList = p;
140973     }
140974   }else{
140975     char *pEnd = &pReader->aDoclist[pReader->nDoclist];
140976 
140977     /* Pointer p currently points at the first byte of an offset list. The
140978     ** following block advances it to point one byte past the end of
140979     ** the same offset list. */
140980     while( 1 ){
140981 
140982       /* The following line of code (and the "p++" below the while() loop) is
140983       ** normally all that is required to move pointer p to the desired
140984       ** position. The exception is if this node is being loaded from disk
140985       ** incrementally and pointer "p" now points to the first byte past
140986       ** the populated part of pReader->aNode[].
140987       */
140988       while( *p | c ) c = *p++ & 0x80;
140989       assert( *p==0 );
140990 
140991       if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
140992       rc = fts3SegReaderIncrRead(pReader);
140993       if( rc!=SQLITE_OK ) return rc;
140994     }
140995     p++;
140996 
140997     /* If required, populate the output variables with a pointer to and the
140998     ** size of the previous offset-list.
140999     */
141000     if( ppOffsetList ){
141001       *ppOffsetList = pReader->pOffsetList;
141002       *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
141003     }
141004 
141005     /* List may have been edited in place by fts3EvalNearTrim() */
141006     while( p<pEnd && *p==0 ) p++;
141007 
141008     /* If there are no more entries in the doclist, set pOffsetList to
141009     ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
141010     ** Fts3SegReader.pOffsetList to point to the next offset list before
141011     ** returning.
141012     */
141013     if( p>=pEnd ){
141014       pReader->pOffsetList = 0;
141015     }else{
141016       rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
141017       if( rc==SQLITE_OK ){
141018         sqlite3_int64 iDelta;
141019         pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
141020         if( pTab->bDescIdx ){
141021           pReader->iDocid -= iDelta;
141022         }else{
141023           pReader->iDocid += iDelta;
141024         }
141025       }
141026     }
141027   }
141028 
141029   return SQLITE_OK;
141030 }
141031 
141032 
141033 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
141034   Fts3Cursor *pCsr,
141035   Fts3MultiSegReader *pMsr,
141036   int *pnOvfl
141037 ){
141038   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
141039   int nOvfl = 0;
141040   int ii;
141041   int rc = SQLITE_OK;
141042   int pgsz = p->nPgsz;
141043 
141044   assert( p->bFts4 );
141045   assert( pgsz>0 );
141046 
141047   for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
141048     Fts3SegReader *pReader = pMsr->apSegment[ii];
141049     if( !fts3SegReaderIsPending(pReader)
141050      && !fts3SegReaderIsRootOnly(pReader)
141051     ){
141052       sqlite3_int64 jj;
141053       for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
141054         int nBlob;
141055         rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
141056         if( rc!=SQLITE_OK ) break;
141057         if( (nBlob+35)>pgsz ){
141058           nOvfl += (nBlob + 34)/pgsz;
141059         }
141060       }
141061     }
141062   }
141063   *pnOvfl = nOvfl;
141064   return rc;
141065 }
141066 
141067 /*
141068 ** Free all allocations associated with the iterator passed as the
141069 ** second argument.
141070 */
141071 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
141072   if( pReader && !fts3SegReaderIsPending(pReader) ){
141073     sqlite3_free(pReader->zTerm);
141074     if( !fts3SegReaderIsRootOnly(pReader) ){
141075       sqlite3_free(pReader->aNode);
141076       sqlite3_blob_close(pReader->pBlob);
141077     }
141078   }
141079   sqlite3_free(pReader);
141080 }
141081 
141082 /*
141083 ** Allocate a new SegReader object.
141084 */
141085 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
141086   int iAge,                       /* Segment "age". */
141087   int bLookup,                    /* True for a lookup only */
141088   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
141089   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
141090   sqlite3_int64 iEndBlock,        /* Final block of segment */
141091   const char *zRoot,              /* Buffer containing root node */
141092   int nRoot,                      /* Size of buffer containing root node */
141093   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
141094 ){
141095   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
141096   int nExtra = 0;                 /* Bytes to allocate segment root node */
141097 
141098   assert( iStartLeaf<=iEndLeaf );
141099   if( iStartLeaf==0 ){
141100     nExtra = nRoot + FTS3_NODE_PADDING;
141101   }
141102 
141103   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
141104   if( !pReader ){
141105     return SQLITE_NOMEM;
141106   }
141107   memset(pReader, 0, sizeof(Fts3SegReader));
141108   pReader->iIdx = iAge;
141109   pReader->bLookup = bLookup!=0;
141110   pReader->iStartBlock = iStartLeaf;
141111   pReader->iLeafEndBlock = iEndLeaf;
141112   pReader->iEndBlock = iEndBlock;
141113 
141114   if( nExtra ){
141115     /* The entire segment is stored in the root node. */
141116     pReader->aNode = (char *)&pReader[1];
141117     pReader->rootOnly = 1;
141118     pReader->nNode = nRoot;
141119     memcpy(pReader->aNode, zRoot, nRoot);
141120     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
141121   }else{
141122     pReader->iCurrentBlock = iStartLeaf-1;
141123   }
141124   *ppReader = pReader;
141125   return SQLITE_OK;
141126 }
141127 
141128 /*
141129 ** This is a comparison function used as a qsort() callback when sorting
141130 ** an array of pending terms by term. This occurs as part of flushing
141131 ** the contents of the pending-terms hash table to the database.
141132 */
141133 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
141134   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
141135   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
141136   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
141137   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
141138 
141139   int n = (n1<n2 ? n1 : n2);
141140   int c = memcmp(z1, z2, n);
141141   if( c==0 ){
141142     c = n1 - n2;
141143   }
141144   return c;
141145 }
141146 
141147 /*
141148 ** This function is used to allocate an Fts3SegReader that iterates through
141149 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
141150 **
141151 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
141152 ** through each term in the pending-terms table. Or, if isPrefixIter is
141153 ** non-zero, it iterates through each term and its prefixes. For example, if
141154 ** the pending terms hash table contains the terms "sqlite", "mysql" and
141155 ** "firebird", then the iterator visits the following 'terms' (in the order
141156 ** shown):
141157 **
141158 **   f fi fir fire fireb firebi firebir firebird
141159 **   m my mys mysq mysql
141160 **   s sq sql sqli sqlit sqlite
141161 **
141162 ** Whereas if isPrefixIter is zero, the terms visited are:
141163 **
141164 **   firebird mysql sqlite
141165 */
141166 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
141167   Fts3Table *p,                   /* Virtual table handle */
141168   int iIndex,                     /* Index for p->aIndex */
141169   const char *zTerm,              /* Term to search for */
141170   int nTerm,                      /* Size of buffer zTerm */
141171   int bPrefix,                    /* True for a prefix iterator */
141172   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
141173 ){
141174   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
141175   Fts3HashElem *pE;               /* Iterator variable */
141176   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
141177   int nElem = 0;                  /* Size of array at aElem */
141178   int rc = SQLITE_OK;             /* Return Code */
141179   Fts3Hash *pHash;
141180 
141181   pHash = &p->aIndex[iIndex].hPending;
141182   if( bPrefix ){
141183     int nAlloc = 0;               /* Size of allocated array at aElem */
141184 
141185     for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
141186       char *zKey = (char *)fts3HashKey(pE);
141187       int nKey = fts3HashKeysize(pE);
141188       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
141189         if( nElem==nAlloc ){
141190           Fts3HashElem **aElem2;
141191           nAlloc += 16;
141192           aElem2 = (Fts3HashElem **)sqlite3_realloc(
141193               aElem, nAlloc*sizeof(Fts3HashElem *)
141194           );
141195           if( !aElem2 ){
141196             rc = SQLITE_NOMEM;
141197             nElem = 0;
141198             break;
141199           }
141200           aElem = aElem2;
141201         }
141202 
141203         aElem[nElem++] = pE;
141204       }
141205     }
141206 
141207     /* If more than one term matches the prefix, sort the Fts3HashElem
141208     ** objects in term order using qsort(). This uses the same comparison
141209     ** callback as is used when flushing terms to disk.
141210     */
141211     if( nElem>1 ){
141212       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
141213     }
141214 
141215   }else{
141216     /* The query is a simple term lookup that matches at most one term in
141217     ** the index. All that is required is a straight hash-lookup.
141218     **
141219     ** Because the stack address of pE may be accessed via the aElem pointer
141220     ** below, the "Fts3HashElem *pE" must be declared so that it is valid
141221     ** within this entire function, not just this "else{...}" block.
141222     */
141223     pE = fts3HashFindElem(pHash, zTerm, nTerm);
141224     if( pE ){
141225       aElem = &pE;
141226       nElem = 1;
141227     }
141228   }
141229 
141230   if( nElem>0 ){
141231     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
141232     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
141233     if( !pReader ){
141234       rc = SQLITE_NOMEM;
141235     }else{
141236       memset(pReader, 0, nByte);
141237       pReader->iIdx = 0x7FFFFFFF;
141238       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
141239       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
141240     }
141241   }
141242 
141243   if( bPrefix ){
141244     sqlite3_free(aElem);
141245   }
141246   *ppReader = pReader;
141247   return rc;
141248 }
141249 
141250 /*
141251 ** Compare the entries pointed to by two Fts3SegReader structures.
141252 ** Comparison is as follows:
141253 **
141254 **   1) EOF is greater than not EOF.
141255 **
141256 **   2) The current terms (if any) are compared using memcmp(). If one
141257 **      term is a prefix of another, the longer term is considered the
141258 **      larger.
141259 **
141260 **   3) By segment age. An older segment is considered larger.
141261 */
141262 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
141263   int rc;
141264   if( pLhs->aNode && pRhs->aNode ){
141265     int rc2 = pLhs->nTerm - pRhs->nTerm;
141266     if( rc2<0 ){
141267       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
141268     }else{
141269       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
141270     }
141271     if( rc==0 ){
141272       rc = rc2;
141273     }
141274   }else{
141275     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
141276   }
141277   if( rc==0 ){
141278     rc = pRhs->iIdx - pLhs->iIdx;
141279   }
141280   assert( rc!=0 );
141281   return rc;
141282 }
141283 
141284 /*
141285 ** A different comparison function for SegReader structures. In this
141286 ** version, it is assumed that each SegReader points to an entry in
141287 ** a doclist for identical terms. Comparison is made as follows:
141288 **
141289 **   1) EOF (end of doclist in this case) is greater than not EOF.
141290 **
141291 **   2) By current docid.
141292 **
141293 **   3) By segment age. An older segment is considered larger.
141294 */
141295 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
141296   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
141297   if( rc==0 ){
141298     if( pLhs->iDocid==pRhs->iDocid ){
141299       rc = pRhs->iIdx - pLhs->iIdx;
141300     }else{
141301       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
141302     }
141303   }
141304   assert( pLhs->aNode && pRhs->aNode );
141305   return rc;
141306 }
141307 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
141308   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
141309   if( rc==0 ){
141310     if( pLhs->iDocid==pRhs->iDocid ){
141311       rc = pRhs->iIdx - pLhs->iIdx;
141312     }else{
141313       rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
141314     }
141315   }
141316   assert( pLhs->aNode && pRhs->aNode );
141317   return rc;
141318 }
141319 
141320 /*
141321 ** Compare the term that the Fts3SegReader object passed as the first argument
141322 ** points to with the term specified by arguments zTerm and nTerm.
141323 **
141324 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
141325 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
141326 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
141327 */
141328 static int fts3SegReaderTermCmp(
141329   Fts3SegReader *pSeg,            /* Segment reader object */
141330   const char *zTerm,              /* Term to compare to */
141331   int nTerm                       /* Size of term zTerm in bytes */
141332 ){
141333   int res = 0;
141334   if( pSeg->aNode ){
141335     if( pSeg->nTerm>nTerm ){
141336       res = memcmp(pSeg->zTerm, zTerm, nTerm);
141337     }else{
141338       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
141339     }
141340     if( res==0 ){
141341       res = pSeg->nTerm-nTerm;
141342     }
141343   }
141344   return res;
141345 }
141346 
141347 /*
141348 ** Argument apSegment is an array of nSegment elements. It is known that
141349 ** the final (nSegment-nSuspect) members are already in sorted order
141350 ** (according to the comparison function provided). This function shuffles
141351 ** the array around until all entries are in sorted order.
141352 */
141353 static void fts3SegReaderSort(
141354   Fts3SegReader **apSegment,                     /* Array to sort entries of */
141355   int nSegment,                                  /* Size of apSegment array */
141356   int nSuspect,                                  /* Unsorted entry count */
141357   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
141358 ){
141359   int i;                          /* Iterator variable */
141360 
141361   assert( nSuspect<=nSegment );
141362 
141363   if( nSuspect==nSegment ) nSuspect--;
141364   for(i=nSuspect-1; i>=0; i--){
141365     int j;
141366     for(j=i; j<(nSegment-1); j++){
141367       Fts3SegReader *pTmp;
141368       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
141369       pTmp = apSegment[j+1];
141370       apSegment[j+1] = apSegment[j];
141371       apSegment[j] = pTmp;
141372     }
141373   }
141374 
141375 #ifndef NDEBUG
141376   /* Check that the list really is sorted now. */
141377   for(i=0; i<(nSuspect-1); i++){
141378     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
141379   }
141380 #endif
141381 }
141382 
141383 /*
141384 ** Insert a record into the %_segments table.
141385 */
141386 static int fts3WriteSegment(
141387   Fts3Table *p,                   /* Virtual table handle */
141388   sqlite3_int64 iBlock,           /* Block id for new block */
141389   char *z,                        /* Pointer to buffer containing block data */
141390   int n                           /* Size of buffer z in bytes */
141391 ){
141392   sqlite3_stmt *pStmt;
141393   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
141394   if( rc==SQLITE_OK ){
141395     sqlite3_bind_int64(pStmt, 1, iBlock);
141396     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
141397     sqlite3_step(pStmt);
141398     rc = sqlite3_reset(pStmt);
141399   }
141400   return rc;
141401 }
141402 
141403 /*
141404 ** Find the largest relative level number in the table. If successful, set
141405 ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
141406 ** set *pnMax to zero and return an SQLite error code.
141407 */
141408 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
141409   int rc;
141410   int mxLevel = 0;
141411   sqlite3_stmt *pStmt = 0;
141412 
141413   rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
141414   if( rc==SQLITE_OK ){
141415     if( SQLITE_ROW==sqlite3_step(pStmt) ){
141416       mxLevel = sqlite3_column_int(pStmt, 0);
141417     }
141418     rc = sqlite3_reset(pStmt);
141419   }
141420   *pnMax = mxLevel;
141421   return rc;
141422 }
141423 
141424 /*
141425 ** Insert a record into the %_segdir table.
141426 */
141427 static int fts3WriteSegdir(
141428   Fts3Table *p,                   /* Virtual table handle */
141429   sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
141430   int iIdx,                       /* Value for "idx" field */
141431   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
141432   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
141433   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
141434   sqlite3_int64 nLeafData,        /* Bytes of leaf data in segment */
141435   char *zRoot,                    /* Blob value for "root" field */
141436   int nRoot                       /* Number of bytes in buffer zRoot */
141437 ){
141438   sqlite3_stmt *pStmt;
141439   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
141440   if( rc==SQLITE_OK ){
141441     sqlite3_bind_int64(pStmt, 1, iLevel);
141442     sqlite3_bind_int(pStmt, 2, iIdx);
141443     sqlite3_bind_int64(pStmt, 3, iStartBlock);
141444     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
141445     if( nLeafData==0 ){
141446       sqlite3_bind_int64(pStmt, 5, iEndBlock);
141447     }else{
141448       char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
141449       if( !zEnd ) return SQLITE_NOMEM;
141450       sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
141451     }
141452     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
141453     sqlite3_step(pStmt);
141454     rc = sqlite3_reset(pStmt);
141455   }
141456   return rc;
141457 }
141458 
141459 /*
141460 ** Return the size of the common prefix (if any) shared by zPrev and
141461 ** zNext, in bytes. For example,
141462 **
141463 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
141464 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
141465 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
141466 */
141467 static int fts3PrefixCompress(
141468   const char *zPrev,              /* Buffer containing previous term */
141469   int nPrev,                      /* Size of buffer zPrev in bytes */
141470   const char *zNext,              /* Buffer containing next term */
141471   int nNext                       /* Size of buffer zNext in bytes */
141472 ){
141473   int n;
141474   UNUSED_PARAMETER(nNext);
141475   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
141476   return n;
141477 }
141478 
141479 /*
141480 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
141481 ** (according to memcmp) than the previous term.
141482 */
141483 static int fts3NodeAddTerm(
141484   Fts3Table *p,                   /* Virtual table handle */
141485   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
141486   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
141487   const char *zTerm,              /* Pointer to buffer containing term */
141488   int nTerm                       /* Size of term in bytes */
141489 ){
141490   SegmentNode *pTree = *ppTree;
141491   int rc;
141492   SegmentNode *pNew;
141493 
141494   /* First try to append the term to the current node. Return early if
141495   ** this is possible.
141496   */
141497   if( pTree ){
141498     int nData = pTree->nData;     /* Current size of node in bytes */
141499     int nReq = nData;             /* Required space after adding zTerm */
141500     int nPrefix;                  /* Number of bytes of prefix compression */
141501     int nSuffix;                  /* Suffix length */
141502 
141503     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
141504     nSuffix = nTerm-nPrefix;
141505 
141506     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
141507     if( nReq<=p->nNodeSize || !pTree->zTerm ){
141508 
141509       if( nReq>p->nNodeSize ){
141510         /* An unusual case: this is the first term to be added to the node
141511         ** and the static node buffer (p->nNodeSize bytes) is not large
141512         ** enough. Use a separately malloced buffer instead This wastes
141513         ** p->nNodeSize bytes, but since this scenario only comes about when
141514         ** the database contain two terms that share a prefix of almost 2KB,
141515         ** this is not expected to be a serious problem.
141516         */
141517         assert( pTree->aData==(char *)&pTree[1] );
141518         pTree->aData = (char *)sqlite3_malloc(nReq);
141519         if( !pTree->aData ){
141520           return SQLITE_NOMEM;
141521         }
141522       }
141523 
141524       if( pTree->zTerm ){
141525         /* There is no prefix-length field for first term in a node */
141526         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
141527       }
141528 
141529       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
141530       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
141531       pTree->nData = nData + nSuffix;
141532       pTree->nEntry++;
141533 
141534       if( isCopyTerm ){
141535         if( pTree->nMalloc<nTerm ){
141536           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
141537           if( !zNew ){
141538             return SQLITE_NOMEM;
141539           }
141540           pTree->nMalloc = nTerm*2;
141541           pTree->zMalloc = zNew;
141542         }
141543         pTree->zTerm = pTree->zMalloc;
141544         memcpy(pTree->zTerm, zTerm, nTerm);
141545         pTree->nTerm = nTerm;
141546       }else{
141547         pTree->zTerm = (char *)zTerm;
141548         pTree->nTerm = nTerm;
141549       }
141550       return SQLITE_OK;
141551     }
141552   }
141553 
141554   /* If control flows to here, it was not possible to append zTerm to the
141555   ** current node. Create a new node (a right-sibling of the current node).
141556   ** If this is the first node in the tree, the term is added to it.
141557   **
141558   ** Otherwise, the term is not added to the new node, it is left empty for
141559   ** now. Instead, the term is inserted into the parent of pTree. If pTree
141560   ** has no parent, one is created here.
141561   */
141562   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
141563   if( !pNew ){
141564     return SQLITE_NOMEM;
141565   }
141566   memset(pNew, 0, sizeof(SegmentNode));
141567   pNew->nData = 1 + FTS3_VARINT_MAX;
141568   pNew->aData = (char *)&pNew[1];
141569 
141570   if( pTree ){
141571     SegmentNode *pParent = pTree->pParent;
141572     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
141573     if( pTree->pParent==0 ){
141574       pTree->pParent = pParent;
141575     }
141576     pTree->pRight = pNew;
141577     pNew->pLeftmost = pTree->pLeftmost;
141578     pNew->pParent = pParent;
141579     pNew->zMalloc = pTree->zMalloc;
141580     pNew->nMalloc = pTree->nMalloc;
141581     pTree->zMalloc = 0;
141582   }else{
141583     pNew->pLeftmost = pNew;
141584     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
141585   }
141586 
141587   *ppTree = pNew;
141588   return rc;
141589 }
141590 
141591 /*
141592 ** Helper function for fts3NodeWrite().
141593 */
141594 static int fts3TreeFinishNode(
141595   SegmentNode *pTree,
141596   int iHeight,
141597   sqlite3_int64 iLeftChild
141598 ){
141599   int nStart;
141600   assert( iHeight>=1 && iHeight<128 );
141601   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
141602   pTree->aData[nStart] = (char)iHeight;
141603   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
141604   return nStart;
141605 }
141606 
141607 /*
141608 ** Write the buffer for the segment node pTree and all of its peers to the
141609 ** database. Then call this function recursively to write the parent of
141610 ** pTree and its peers to the database.
141611 **
141612 ** Except, if pTree is a root node, do not write it to the database. Instead,
141613 ** set output variables *paRoot and *pnRoot to contain the root node.
141614 **
141615 ** If successful, SQLITE_OK is returned and output variable *piLast is
141616 ** set to the largest blockid written to the database (or zero if no
141617 ** blocks were written to the db). Otherwise, an SQLite error code is
141618 ** returned.
141619 */
141620 static int fts3NodeWrite(
141621   Fts3Table *p,                   /* Virtual table handle */
141622   SegmentNode *pTree,             /* SegmentNode handle */
141623   int iHeight,                    /* Height of this node in tree */
141624   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
141625   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
141626   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
141627   char **paRoot,                  /* OUT: Data for root node */
141628   int *pnRoot                     /* OUT: Size of root node in bytes */
141629 ){
141630   int rc = SQLITE_OK;
141631 
141632   if( !pTree->pParent ){
141633     /* Root node of the tree. */
141634     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
141635     *piLast = iFree-1;
141636     *pnRoot = pTree->nData - nStart;
141637     *paRoot = &pTree->aData[nStart];
141638   }else{
141639     SegmentNode *pIter;
141640     sqlite3_int64 iNextFree = iFree;
141641     sqlite3_int64 iNextLeaf = iLeaf;
141642     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
141643       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
141644       int nWrite = pIter->nData - nStart;
141645 
141646       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
141647       iNextFree++;
141648       iNextLeaf += (pIter->nEntry+1);
141649     }
141650     if( rc==SQLITE_OK ){
141651       assert( iNextLeaf==iFree );
141652       rc = fts3NodeWrite(
141653           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
141654       );
141655     }
141656   }
141657 
141658   return rc;
141659 }
141660 
141661 /*
141662 ** Free all memory allocations associated with the tree pTree.
141663 */
141664 static void fts3NodeFree(SegmentNode *pTree){
141665   if( pTree ){
141666     SegmentNode *p = pTree->pLeftmost;
141667     fts3NodeFree(p->pParent);
141668     while( p ){
141669       SegmentNode *pRight = p->pRight;
141670       if( p->aData!=(char *)&p[1] ){
141671         sqlite3_free(p->aData);
141672       }
141673       assert( pRight==0 || p->zMalloc==0 );
141674       sqlite3_free(p->zMalloc);
141675       sqlite3_free(p);
141676       p = pRight;
141677     }
141678   }
141679 }
141680 
141681 /*
141682 ** Add a term to the segment being constructed by the SegmentWriter object
141683 ** *ppWriter. When adding the first term to a segment, *ppWriter should
141684 ** be passed NULL. This function will allocate a new SegmentWriter object
141685 ** and return it via the input/output variable *ppWriter in this case.
141686 **
141687 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
141688 */
141689 static int fts3SegWriterAdd(
141690   Fts3Table *p,                   /* Virtual table handle */
141691   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
141692   int isCopyTerm,                 /* True if buffer zTerm must be copied */
141693   const char *zTerm,              /* Pointer to buffer containing term */
141694   int nTerm,                      /* Size of term in bytes */
141695   const char *aDoclist,           /* Pointer to buffer containing doclist */
141696   int nDoclist                    /* Size of doclist in bytes */
141697 ){
141698   int nPrefix;                    /* Size of term prefix in bytes */
141699   int nSuffix;                    /* Size of term suffix in bytes */
141700   int nReq;                       /* Number of bytes required on leaf page */
141701   int nData;
141702   SegmentWriter *pWriter = *ppWriter;
141703 
141704   if( !pWriter ){
141705     int rc;
141706     sqlite3_stmt *pStmt;
141707 
141708     /* Allocate the SegmentWriter structure */
141709     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
141710     if( !pWriter ) return SQLITE_NOMEM;
141711     memset(pWriter, 0, sizeof(SegmentWriter));
141712     *ppWriter = pWriter;
141713 
141714     /* Allocate a buffer in which to accumulate data */
141715     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
141716     if( !pWriter->aData ) return SQLITE_NOMEM;
141717     pWriter->nSize = p->nNodeSize;
141718 
141719     /* Find the next free blockid in the %_segments table */
141720     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
141721     if( rc!=SQLITE_OK ) return rc;
141722     if( SQLITE_ROW==sqlite3_step(pStmt) ){
141723       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
141724       pWriter->iFirst = pWriter->iFree;
141725     }
141726     rc = sqlite3_reset(pStmt);
141727     if( rc!=SQLITE_OK ) return rc;
141728   }
141729   nData = pWriter->nData;
141730 
141731   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
141732   nSuffix = nTerm-nPrefix;
141733 
141734   /* Figure out how many bytes are required by this new entry */
141735   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
141736     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
141737     nSuffix +                               /* Term suffix */
141738     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
141739     nDoclist;                               /* Doclist data */
141740 
141741   if( nData>0 && nData+nReq>p->nNodeSize ){
141742     int rc;
141743 
141744     /* The current leaf node is full. Write it out to the database. */
141745     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
141746     if( rc!=SQLITE_OK ) return rc;
141747     p->nLeafAdd++;
141748 
141749     /* Add the current term to the interior node tree. The term added to
141750     ** the interior tree must:
141751     **
141752     **   a) be greater than the largest term on the leaf node just written
141753     **      to the database (still available in pWriter->zTerm), and
141754     **
141755     **   b) be less than or equal to the term about to be added to the new
141756     **      leaf node (zTerm/nTerm).
141757     **
141758     ** In other words, it must be the prefix of zTerm 1 byte longer than
141759     ** the common prefix (if any) of zTerm and pWriter->zTerm.
141760     */
141761     assert( nPrefix<nTerm );
141762     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
141763     if( rc!=SQLITE_OK ) return rc;
141764 
141765     nData = 0;
141766     pWriter->nTerm = 0;
141767 
141768     nPrefix = 0;
141769     nSuffix = nTerm;
141770     nReq = 1 +                              /* varint containing prefix size */
141771       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
141772       nTerm +                               /* Term suffix */
141773       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
141774       nDoclist;                             /* Doclist data */
141775   }
141776 
141777   /* Increase the total number of bytes written to account for the new entry. */
141778   pWriter->nLeafData += nReq;
141779 
141780   /* If the buffer currently allocated is too small for this entry, realloc
141781   ** the buffer to make it large enough.
141782   */
141783   if( nReq>pWriter->nSize ){
141784     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
141785     if( !aNew ) return SQLITE_NOMEM;
141786     pWriter->aData = aNew;
141787     pWriter->nSize = nReq;
141788   }
141789   assert( nData+nReq<=pWriter->nSize );
141790 
141791   /* Append the prefix-compressed term and doclist to the buffer. */
141792   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
141793   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
141794   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
141795   nData += nSuffix;
141796   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
141797   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
141798   pWriter->nData = nData + nDoclist;
141799 
141800   /* Save the current term so that it can be used to prefix-compress the next.
141801   ** If the isCopyTerm parameter is true, then the buffer pointed to by
141802   ** zTerm is transient, so take a copy of the term data. Otherwise, just
141803   ** store a copy of the pointer.
141804   */
141805   if( isCopyTerm ){
141806     if( nTerm>pWriter->nMalloc ){
141807       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
141808       if( !zNew ){
141809         return SQLITE_NOMEM;
141810       }
141811       pWriter->nMalloc = nTerm*2;
141812       pWriter->zMalloc = zNew;
141813       pWriter->zTerm = zNew;
141814     }
141815     assert( pWriter->zTerm==pWriter->zMalloc );
141816     memcpy(pWriter->zTerm, zTerm, nTerm);
141817   }else{
141818     pWriter->zTerm = (char *)zTerm;
141819   }
141820   pWriter->nTerm = nTerm;
141821 
141822   return SQLITE_OK;
141823 }
141824 
141825 /*
141826 ** Flush all data associated with the SegmentWriter object pWriter to the
141827 ** database. This function must be called after all terms have been added
141828 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
141829 ** returned. Otherwise, an SQLite error code.
141830 */
141831 static int fts3SegWriterFlush(
141832   Fts3Table *p,                   /* Virtual table handle */
141833   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
141834   sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
141835   int iIdx                        /* Value for 'idx' column of %_segdir */
141836 ){
141837   int rc;                         /* Return code */
141838   if( pWriter->pTree ){
141839     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
141840     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
141841     char *zRoot = NULL;           /* Pointer to buffer containing root node */
141842     int nRoot = 0;                /* Size of buffer zRoot */
141843 
141844     iLastLeaf = pWriter->iFree;
141845     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
141846     if( rc==SQLITE_OK ){
141847       rc = fts3NodeWrite(p, pWriter->pTree, 1,
141848           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
141849     }
141850     if( rc==SQLITE_OK ){
141851       rc = fts3WriteSegdir(p, iLevel, iIdx,
141852           pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
141853     }
141854   }else{
141855     /* The entire tree fits on the root node. Write it to the segdir table. */
141856     rc = fts3WriteSegdir(p, iLevel, iIdx,
141857         0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
141858   }
141859   p->nLeafAdd++;
141860   return rc;
141861 }
141862 
141863 /*
141864 ** Release all memory held by the SegmentWriter object passed as the
141865 ** first argument.
141866 */
141867 static void fts3SegWriterFree(SegmentWriter *pWriter){
141868   if( pWriter ){
141869     sqlite3_free(pWriter->aData);
141870     sqlite3_free(pWriter->zMalloc);
141871     fts3NodeFree(pWriter->pTree);
141872     sqlite3_free(pWriter);
141873   }
141874 }
141875 
141876 /*
141877 ** The first value in the apVal[] array is assumed to contain an integer.
141878 ** This function tests if there exist any documents with docid values that
141879 ** are different from that integer. i.e. if deleting the document with docid
141880 ** pRowid would mean the FTS3 table were empty.
141881 **
141882 ** If successful, *pisEmpty is set to true if the table is empty except for
141883 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
141884 ** error occurs, an SQLite error code is returned.
141885 */
141886 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
141887   sqlite3_stmt *pStmt;
141888   int rc;
141889   if( p->zContentTbl ){
141890     /* If using the content=xxx option, assume the table is never empty */
141891     *pisEmpty = 0;
141892     rc = SQLITE_OK;
141893   }else{
141894     rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
141895     if( rc==SQLITE_OK ){
141896       if( SQLITE_ROW==sqlite3_step(pStmt) ){
141897         *pisEmpty = sqlite3_column_int(pStmt, 0);
141898       }
141899       rc = sqlite3_reset(pStmt);
141900     }
141901   }
141902   return rc;
141903 }
141904 
141905 /*
141906 ** Set *pnMax to the largest segment level in the database for the index
141907 ** iIndex.
141908 **
141909 ** Segment levels are stored in the 'level' column of the %_segdir table.
141910 **
141911 ** Return SQLITE_OK if successful, or an SQLite error code if not.
141912 */
141913 static int fts3SegmentMaxLevel(
141914   Fts3Table *p,
141915   int iLangid,
141916   int iIndex,
141917   sqlite3_int64 *pnMax
141918 ){
141919   sqlite3_stmt *pStmt;
141920   int rc;
141921   assert( iIndex>=0 && iIndex<p->nIndex );
141922 
141923   /* Set pStmt to the compiled version of:
141924   **
141925   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
141926   **
141927   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
141928   */
141929   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
141930   if( rc!=SQLITE_OK ) return rc;
141931   sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
141932   sqlite3_bind_int64(pStmt, 2,
141933       getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
141934   );
141935   if( SQLITE_ROW==sqlite3_step(pStmt) ){
141936     *pnMax = sqlite3_column_int64(pStmt, 0);
141937   }
141938   return sqlite3_reset(pStmt);
141939 }
141940 
141941 /*
141942 ** iAbsLevel is an absolute level that may be assumed to exist within
141943 ** the database. This function checks if it is the largest level number
141944 ** within its index. Assuming no error occurs, *pbMax is set to 1 if
141945 ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
141946 ** is returned. If an error occurs, an error code is returned and the
141947 ** final value of *pbMax is undefined.
141948 */
141949 static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
141950 
141951   /* Set pStmt to the compiled version of:
141952   **
141953   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
141954   **
141955   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
141956   */
141957   sqlite3_stmt *pStmt;
141958   int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
141959   if( rc!=SQLITE_OK ) return rc;
141960   sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
141961   sqlite3_bind_int64(pStmt, 2,
141962       ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
141963   );
141964 
141965   *pbMax = 0;
141966   if( SQLITE_ROW==sqlite3_step(pStmt) ){
141967     *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
141968   }
141969   return sqlite3_reset(pStmt);
141970 }
141971 
141972 /*
141973 ** Delete all entries in the %_segments table associated with the segment
141974 ** opened with seg-reader pSeg. This function does not affect the contents
141975 ** of the %_segdir table.
141976 */
141977 static int fts3DeleteSegment(
141978   Fts3Table *p,                   /* FTS table handle */
141979   Fts3SegReader *pSeg             /* Segment to delete */
141980 ){
141981   int rc = SQLITE_OK;             /* Return code */
141982   if( pSeg->iStartBlock ){
141983     sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
141984     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
141985     if( rc==SQLITE_OK ){
141986       sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
141987       sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
141988       sqlite3_step(pDelete);
141989       rc = sqlite3_reset(pDelete);
141990     }
141991   }
141992   return rc;
141993 }
141994 
141995 /*
141996 ** This function is used after merging multiple segments into a single large
141997 ** segment to delete the old, now redundant, segment b-trees. Specifically,
141998 ** it:
141999 **
142000 **   1) Deletes all %_segments entries for the segments associated with
142001 **      each of the SegReader objects in the array passed as the third
142002 **      argument, and
142003 **
142004 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
142005 **      entries regardless of level if (iLevel<0).
142006 **
142007 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
142008 */
142009 static int fts3DeleteSegdir(
142010   Fts3Table *p,                   /* Virtual table handle */
142011   int iLangid,                    /* Language id */
142012   int iIndex,                     /* Index for p->aIndex */
142013   int iLevel,                     /* Level of %_segdir entries to delete */
142014   Fts3SegReader **apSegment,      /* Array of SegReader objects */
142015   int nReader                     /* Size of array apSegment */
142016 ){
142017   int rc = SQLITE_OK;             /* Return Code */
142018   int i;                          /* Iterator variable */
142019   sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
142020 
142021   for(i=0; rc==SQLITE_OK && i<nReader; i++){
142022     rc = fts3DeleteSegment(p, apSegment[i]);
142023   }
142024   if( rc!=SQLITE_OK ){
142025     return rc;
142026   }
142027 
142028   assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
142029   if( iLevel==FTS3_SEGCURSOR_ALL ){
142030     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
142031     if( rc==SQLITE_OK ){
142032       sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
142033       sqlite3_bind_int64(pDelete, 2,
142034           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
142035       );
142036     }
142037   }else{
142038     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
142039     if( rc==SQLITE_OK ){
142040       sqlite3_bind_int64(
142041           pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
142042       );
142043     }
142044   }
142045 
142046   if( rc==SQLITE_OK ){
142047     sqlite3_step(pDelete);
142048     rc = sqlite3_reset(pDelete);
142049   }
142050 
142051   return rc;
142052 }
142053 
142054 /*
142055 ** When this function is called, buffer *ppList (size *pnList bytes) contains
142056 ** a position list that may (or may not) feature multiple columns. This
142057 ** function adjusts the pointer *ppList and the length *pnList so that they
142058 ** identify the subset of the position list that corresponds to column iCol.
142059 **
142060 ** If there are no entries in the input position list for column iCol, then
142061 ** *pnList is set to zero before returning.
142062 **
142063 ** If parameter bZero is non-zero, then any part of the input list following
142064 ** the end of the output list is zeroed before returning.
142065 */
142066 static void fts3ColumnFilter(
142067   int iCol,                       /* Column to filter on */
142068   int bZero,                      /* Zero out anything following *ppList */
142069   char **ppList,                  /* IN/OUT: Pointer to position list */
142070   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
142071 ){
142072   char *pList = *ppList;
142073   int nList = *pnList;
142074   char *pEnd = &pList[nList];
142075   int iCurrent = 0;
142076   char *p = pList;
142077 
142078   assert( iCol>=0 );
142079   while( 1 ){
142080     char c = 0;
142081     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
142082 
142083     if( iCol==iCurrent ){
142084       nList = (int)(p - pList);
142085       break;
142086     }
142087 
142088     nList -= (int)(p - pList);
142089     pList = p;
142090     if( nList==0 ){
142091       break;
142092     }
142093     p = &pList[1];
142094     p += fts3GetVarint32(p, &iCurrent);
142095   }
142096 
142097   if( bZero && &pList[nList]!=pEnd ){
142098     memset(&pList[nList], 0, pEnd - &pList[nList]);
142099   }
142100   *ppList = pList;
142101   *pnList = nList;
142102 }
142103 
142104 /*
142105 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
142106 ** existing data). Grow the buffer if required.
142107 **
142108 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
142109 ** trying to resize the buffer, return SQLITE_NOMEM.
142110 */
142111 static int fts3MsrBufferData(
142112   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
142113   char *pList,
142114   int nList
142115 ){
142116   if( nList>pMsr->nBuffer ){
142117     char *pNew;
142118     pMsr->nBuffer = nList*2;
142119     pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
142120     if( !pNew ) return SQLITE_NOMEM;
142121     pMsr->aBuffer = pNew;
142122   }
142123 
142124   memcpy(pMsr->aBuffer, pList, nList);
142125   return SQLITE_OK;
142126 }
142127 
142128 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
142129   Fts3Table *p,                   /* Virtual table handle */
142130   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
142131   sqlite3_int64 *piDocid,         /* OUT: Docid value */
142132   char **paPoslist,               /* OUT: Pointer to position list */
142133   int *pnPoslist                  /* OUT: Size of position list in bytes */
142134 ){
142135   int nMerge = pMsr->nAdvance;
142136   Fts3SegReader **apSegment = pMsr->apSegment;
142137   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
142138     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
142139   );
142140 
142141   if( nMerge==0 ){
142142     *paPoslist = 0;
142143     return SQLITE_OK;
142144   }
142145 
142146   while( 1 ){
142147     Fts3SegReader *pSeg;
142148     pSeg = pMsr->apSegment[0];
142149 
142150     if( pSeg->pOffsetList==0 ){
142151       *paPoslist = 0;
142152       break;
142153     }else{
142154       int rc;
142155       char *pList;
142156       int nList;
142157       int j;
142158       sqlite3_int64 iDocid = apSegment[0]->iDocid;
142159 
142160       rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
142161       j = 1;
142162       while( rc==SQLITE_OK
142163         && j<nMerge
142164         && apSegment[j]->pOffsetList
142165         && apSegment[j]->iDocid==iDocid
142166       ){
142167         rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
142168         j++;
142169       }
142170       if( rc!=SQLITE_OK ) return rc;
142171       fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
142172 
142173       if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
142174         rc = fts3MsrBufferData(pMsr, pList, nList+1);
142175         if( rc!=SQLITE_OK ) return rc;
142176         assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
142177         pList = pMsr->aBuffer;
142178       }
142179 
142180       if( pMsr->iColFilter>=0 ){
142181         fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
142182       }
142183 
142184       if( nList>0 ){
142185         *paPoslist = pList;
142186         *piDocid = iDocid;
142187         *pnPoslist = nList;
142188         break;
142189       }
142190     }
142191   }
142192 
142193   return SQLITE_OK;
142194 }
142195 
142196 static int fts3SegReaderStart(
142197   Fts3Table *p,                   /* Virtual table handle */
142198   Fts3MultiSegReader *pCsr,       /* Cursor object */
142199   const char *zTerm,              /* Term searched for (or NULL) */
142200   int nTerm                       /* Length of zTerm in bytes */
142201 ){
142202   int i;
142203   int nSeg = pCsr->nSegment;
142204 
142205   /* If the Fts3SegFilter defines a specific term (or term prefix) to search
142206   ** for, then advance each segment iterator until it points to a term of
142207   ** equal or greater value than the specified term. This prevents many
142208   ** unnecessary merge/sort operations for the case where single segment
142209   ** b-tree leaf nodes contain more than one term.
142210   */
142211   for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
142212     int res = 0;
142213     Fts3SegReader *pSeg = pCsr->apSegment[i];
142214     do {
142215       int rc = fts3SegReaderNext(p, pSeg, 0);
142216       if( rc!=SQLITE_OK ) return rc;
142217     }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
142218 
142219     if( pSeg->bLookup && res!=0 ){
142220       fts3SegReaderSetEof(pSeg);
142221     }
142222   }
142223   fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
142224 
142225   return SQLITE_OK;
142226 }
142227 
142228 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
142229   Fts3Table *p,                   /* Virtual table handle */
142230   Fts3MultiSegReader *pCsr,       /* Cursor object */
142231   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
142232 ){
142233   pCsr->pFilter = pFilter;
142234   return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
142235 }
142236 
142237 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
142238   Fts3Table *p,                   /* Virtual table handle */
142239   Fts3MultiSegReader *pCsr,       /* Cursor object */
142240   int iCol,                       /* Column to match on. */
142241   const char *zTerm,              /* Term to iterate through a doclist for */
142242   int nTerm                       /* Number of bytes in zTerm */
142243 ){
142244   int i;
142245   int rc;
142246   int nSegment = pCsr->nSegment;
142247   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
142248     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
142249   );
142250 
142251   assert( pCsr->pFilter==0 );
142252   assert( zTerm && nTerm>0 );
142253 
142254   /* Advance each segment iterator until it points to the term zTerm/nTerm. */
142255   rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
142256   if( rc!=SQLITE_OK ) return rc;
142257 
142258   /* Determine how many of the segments actually point to zTerm/nTerm. */
142259   for(i=0; i<nSegment; i++){
142260     Fts3SegReader *pSeg = pCsr->apSegment[i];
142261     if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
142262       break;
142263     }
142264   }
142265   pCsr->nAdvance = i;
142266 
142267   /* Advance each of the segments to point to the first docid. */
142268   for(i=0; i<pCsr->nAdvance; i++){
142269     rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
142270     if( rc!=SQLITE_OK ) return rc;
142271   }
142272   fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
142273 
142274   assert( iCol<0 || iCol<p->nColumn );
142275   pCsr->iColFilter = iCol;
142276 
142277   return SQLITE_OK;
142278 }
142279 
142280 /*
142281 ** This function is called on a MultiSegReader that has been started using
142282 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
142283 ** have been made. Calling this function puts the MultiSegReader in such
142284 ** a state that if the next two calls are:
142285 **
142286 **   sqlite3Fts3SegReaderStart()
142287 **   sqlite3Fts3SegReaderStep()
142288 **
142289 ** then the entire doclist for the term is available in
142290 ** MultiSegReader.aDoclist/nDoclist.
142291 */
142292 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
142293   int i;                          /* Used to iterate through segment-readers */
142294 
142295   assert( pCsr->zTerm==0 );
142296   assert( pCsr->nTerm==0 );
142297   assert( pCsr->aDoclist==0 );
142298   assert( pCsr->nDoclist==0 );
142299 
142300   pCsr->nAdvance = 0;
142301   pCsr->bRestart = 1;
142302   for(i=0; i<pCsr->nSegment; i++){
142303     pCsr->apSegment[i]->pOffsetList = 0;
142304     pCsr->apSegment[i]->nOffsetList = 0;
142305     pCsr->apSegment[i]->iDocid = 0;
142306   }
142307 
142308   return SQLITE_OK;
142309 }
142310 
142311 
142312 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
142313   Fts3Table *p,                   /* Virtual table handle */
142314   Fts3MultiSegReader *pCsr        /* Cursor object */
142315 ){
142316   int rc = SQLITE_OK;
142317 
142318   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
142319   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
142320   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
142321   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
142322   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
142323   int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
142324 
142325   Fts3SegReader **apSegment = pCsr->apSegment;
142326   int nSegment = pCsr->nSegment;
142327   Fts3SegFilter *pFilter = pCsr->pFilter;
142328   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
142329     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
142330   );
142331 
142332   if( pCsr->nSegment==0 ) return SQLITE_OK;
142333 
142334   do {
142335     int nMerge;
142336     int i;
142337 
142338     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
142339     ** forward. Then sort the list in order of current term again.
142340     */
142341     for(i=0; i<pCsr->nAdvance; i++){
142342       Fts3SegReader *pSeg = apSegment[i];
142343       if( pSeg->bLookup ){
142344         fts3SegReaderSetEof(pSeg);
142345       }else{
142346         rc = fts3SegReaderNext(p, pSeg, 0);
142347       }
142348       if( rc!=SQLITE_OK ) return rc;
142349     }
142350     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
142351     pCsr->nAdvance = 0;
142352 
142353     /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
142354     assert( rc==SQLITE_OK );
142355     if( apSegment[0]->aNode==0 ) break;
142356 
142357     pCsr->nTerm = apSegment[0]->nTerm;
142358     pCsr->zTerm = apSegment[0]->zTerm;
142359 
142360     /* If this is a prefix-search, and if the term that apSegment[0] points
142361     ** to does not share a suffix with pFilter->zTerm/nTerm, then all
142362     ** required callbacks have been made. In this case exit early.
142363     **
142364     ** Similarly, if this is a search for an exact match, and the first term
142365     ** of segment apSegment[0] is not a match, exit early.
142366     */
142367     if( pFilter->zTerm && !isScan ){
142368       if( pCsr->nTerm<pFilter->nTerm
142369        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
142370        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
142371       ){
142372         break;
142373       }
142374     }
142375 
142376     nMerge = 1;
142377     while( nMerge<nSegment
142378         && apSegment[nMerge]->aNode
142379         && apSegment[nMerge]->nTerm==pCsr->nTerm
142380         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
142381     ){
142382       nMerge++;
142383     }
142384 
142385     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
142386     if( nMerge==1
142387      && !isIgnoreEmpty
142388      && !isFirst
142389      && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
142390     ){
142391       pCsr->nDoclist = apSegment[0]->nDoclist;
142392       if( fts3SegReaderIsPending(apSegment[0]) ){
142393         rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
142394         pCsr->aDoclist = pCsr->aBuffer;
142395       }else{
142396         pCsr->aDoclist = apSegment[0]->aDoclist;
142397       }
142398       if( rc==SQLITE_OK ) rc = SQLITE_ROW;
142399     }else{
142400       int nDoclist = 0;           /* Size of doclist */
142401       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
142402 
142403       /* The current term of the first nMerge entries in the array
142404       ** of Fts3SegReader objects is the same. The doclists must be merged
142405       ** and a single term returned with the merged doclist.
142406       */
142407       for(i=0; i<nMerge; i++){
142408         fts3SegReaderFirstDocid(p, apSegment[i]);
142409       }
142410       fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
142411       while( apSegment[0]->pOffsetList ){
142412         int j;                    /* Number of segments that share a docid */
142413         char *pList = 0;
142414         int nList = 0;
142415         int nByte;
142416         sqlite3_int64 iDocid = apSegment[0]->iDocid;
142417         fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
142418         j = 1;
142419         while( j<nMerge
142420             && apSegment[j]->pOffsetList
142421             && apSegment[j]->iDocid==iDocid
142422         ){
142423           fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
142424           j++;
142425         }
142426 
142427         if( isColFilter ){
142428           fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
142429         }
142430 
142431         if( !isIgnoreEmpty || nList>0 ){
142432 
142433           /* Calculate the 'docid' delta value to write into the merged
142434           ** doclist. */
142435           sqlite3_int64 iDelta;
142436           if( p->bDescIdx && nDoclist>0 ){
142437             iDelta = iPrev - iDocid;
142438           }else{
142439             iDelta = iDocid - iPrev;
142440           }
142441           assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
142442           assert( nDoclist>0 || iDelta==iDocid );
142443 
142444           nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
142445           if( nDoclist+nByte>pCsr->nBuffer ){
142446             char *aNew;
142447             pCsr->nBuffer = (nDoclist+nByte)*2;
142448             aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
142449             if( !aNew ){
142450               return SQLITE_NOMEM;
142451             }
142452             pCsr->aBuffer = aNew;
142453           }
142454 
142455           if( isFirst ){
142456             char *a = &pCsr->aBuffer[nDoclist];
142457             int nWrite;
142458 
142459             nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
142460             if( nWrite ){
142461               iPrev = iDocid;
142462               nDoclist += nWrite;
142463             }
142464           }else{
142465             nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
142466             iPrev = iDocid;
142467             if( isRequirePos ){
142468               memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
142469               nDoclist += nList;
142470               pCsr->aBuffer[nDoclist++] = '\0';
142471             }
142472           }
142473         }
142474 
142475         fts3SegReaderSort(apSegment, nMerge, j, xCmp);
142476       }
142477       if( nDoclist>0 ){
142478         pCsr->aDoclist = pCsr->aBuffer;
142479         pCsr->nDoclist = nDoclist;
142480         rc = SQLITE_ROW;
142481       }
142482     }
142483     pCsr->nAdvance = nMerge;
142484   }while( rc==SQLITE_OK );
142485 
142486   return rc;
142487 }
142488 
142489 
142490 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
142491   Fts3MultiSegReader *pCsr       /* Cursor object */
142492 ){
142493   if( pCsr ){
142494     int i;
142495     for(i=0; i<pCsr->nSegment; i++){
142496       sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
142497     }
142498     sqlite3_free(pCsr->apSegment);
142499     sqlite3_free(pCsr->aBuffer);
142500 
142501     pCsr->nSegment = 0;
142502     pCsr->apSegment = 0;
142503     pCsr->aBuffer = 0;
142504   }
142505 }
142506 
142507 /*
142508 ** Decode the "end_block" field, selected by column iCol of the SELECT
142509 ** statement passed as the first argument.
142510 **
142511 ** The "end_block" field may contain either an integer, or a text field
142512 ** containing the text representation of two non-negative integers separated
142513 ** by one or more space (0x20) characters. In the first case, set *piEndBlock
142514 ** to the integer value and *pnByte to zero before returning. In the second,
142515 ** set *piEndBlock to the first value and *pnByte to the second.
142516 */
142517 static void fts3ReadEndBlockField(
142518   sqlite3_stmt *pStmt,
142519   int iCol,
142520   i64 *piEndBlock,
142521   i64 *pnByte
142522 ){
142523   const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
142524   if( zText ){
142525     int i;
142526     int iMul = 1;
142527     i64 iVal = 0;
142528     for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
142529       iVal = iVal*10 + (zText[i] - '0');
142530     }
142531     *piEndBlock = iVal;
142532     while( zText[i]==' ' ) i++;
142533     iVal = 0;
142534     if( zText[i]=='-' ){
142535       i++;
142536       iMul = -1;
142537     }
142538     for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
142539       iVal = iVal*10 + (zText[i] - '0');
142540     }
142541     *pnByte = (iVal * (i64)iMul);
142542   }
142543 }
142544 
142545 
142546 /*
142547 ** A segment of size nByte bytes has just been written to absolute level
142548 ** iAbsLevel. Promote any segments that should be promoted as a result.
142549 */
142550 static int fts3PromoteSegments(
142551   Fts3Table *p,                   /* FTS table handle */
142552   sqlite3_int64 iAbsLevel,        /* Absolute level just updated */
142553   sqlite3_int64 nByte             /* Size of new segment at iAbsLevel */
142554 ){
142555   int rc = SQLITE_OK;
142556   sqlite3_stmt *pRange;
142557 
142558   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
142559 
142560   if( rc==SQLITE_OK ){
142561     int bOk = 0;
142562     i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
142563     i64 nLimit = (nByte*3)/2;
142564 
142565     /* Loop through all entries in the %_segdir table corresponding to
142566     ** segments in this index on levels greater than iAbsLevel. If there is
142567     ** at least one such segment, and it is possible to determine that all
142568     ** such segments are smaller than nLimit bytes in size, they will be
142569     ** promoted to level iAbsLevel.  */
142570     sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
142571     sqlite3_bind_int64(pRange, 2, iLast);
142572     while( SQLITE_ROW==sqlite3_step(pRange) ){
142573       i64 nSize = 0, dummy;
142574       fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
142575       if( nSize<=0 || nSize>nLimit ){
142576         /* If nSize==0, then the %_segdir.end_block field does not not
142577         ** contain a size value. This happens if it was written by an
142578         ** old version of FTS. In this case it is not possible to determine
142579         ** the size of the segment, and so segment promotion does not
142580         ** take place.  */
142581         bOk = 0;
142582         break;
142583       }
142584       bOk = 1;
142585     }
142586     rc = sqlite3_reset(pRange);
142587 
142588     if( bOk ){
142589       int iIdx = 0;
142590       sqlite3_stmt *pUpdate1;
142591       sqlite3_stmt *pUpdate2;
142592 
142593       if( rc==SQLITE_OK ){
142594         rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
142595       }
142596       if( rc==SQLITE_OK ){
142597         rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
142598       }
142599 
142600       if( rc==SQLITE_OK ){
142601 
142602         /* Loop through all %_segdir entries for segments in this index with
142603         ** levels equal to or greater than iAbsLevel. As each entry is visited,
142604         ** updated it to set (level = -1) and (idx = N), where N is 0 for the
142605         ** oldest segment in the range, 1 for the next oldest, and so on.
142606         **
142607         ** In other words, move all segments being promoted to level -1,
142608         ** setting the "idx" fields as appropriate to keep them in the same
142609         ** order. The contents of level -1 (which is never used, except
142610         ** transiently here), will be moved back to level iAbsLevel below.  */
142611         sqlite3_bind_int64(pRange, 1, iAbsLevel);
142612         while( SQLITE_ROW==sqlite3_step(pRange) ){
142613           sqlite3_bind_int(pUpdate1, 1, iIdx++);
142614           sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
142615           sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
142616           sqlite3_step(pUpdate1);
142617           rc = sqlite3_reset(pUpdate1);
142618           if( rc!=SQLITE_OK ){
142619             sqlite3_reset(pRange);
142620             break;
142621           }
142622         }
142623       }
142624       if( rc==SQLITE_OK ){
142625         rc = sqlite3_reset(pRange);
142626       }
142627 
142628       /* Move level -1 to level iAbsLevel */
142629       if( rc==SQLITE_OK ){
142630         sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
142631         sqlite3_step(pUpdate2);
142632         rc = sqlite3_reset(pUpdate2);
142633       }
142634     }
142635   }
142636 
142637 
142638   return rc;
142639 }
142640 
142641 /*
142642 ** Merge all level iLevel segments in the database into a single
142643 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
142644 ** single segment with a level equal to the numerically largest level
142645 ** currently present in the database.
142646 **
142647 ** If this function is called with iLevel<0, but there is only one
142648 ** segment in the database, SQLITE_DONE is returned immediately.
142649 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
142650 ** an SQLite error code is returned.
142651 */
142652 static int fts3SegmentMerge(
142653   Fts3Table *p,
142654   int iLangid,                    /* Language id to merge */
142655   int iIndex,                     /* Index in p->aIndex[] to merge */
142656   int iLevel                      /* Level to merge */
142657 ){
142658   int rc;                         /* Return code */
142659   int iIdx = 0;                   /* Index of new segment */
142660   sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
142661   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
142662   Fts3SegFilter filter;           /* Segment term filter condition */
142663   Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
142664   int bIgnoreEmpty = 0;           /* True to ignore empty segments */
142665   i64 iMaxLevel = 0;              /* Max level number for this index/langid */
142666 
142667   assert( iLevel==FTS3_SEGCURSOR_ALL
142668        || iLevel==FTS3_SEGCURSOR_PENDING
142669        || iLevel>=0
142670   );
142671   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
142672   assert( iIndex>=0 && iIndex<p->nIndex );
142673 
142674   rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
142675   if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
142676 
142677   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
142678     rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
142679     if( rc!=SQLITE_OK ) goto finished;
142680   }
142681 
142682   if( iLevel==FTS3_SEGCURSOR_ALL ){
142683     /* This call is to merge all segments in the database to a single
142684     ** segment. The level of the new segment is equal to the numerically
142685     ** greatest segment level currently present in the database for this
142686     ** index. The idx of the new segment is always 0.  */
142687     if( csr.nSegment==1 ){
142688       rc = SQLITE_DONE;
142689       goto finished;
142690     }
142691     iNewLevel = iMaxLevel;
142692     bIgnoreEmpty = 1;
142693 
142694   }else{
142695     /* This call is to merge all segments at level iLevel. find the next
142696     ** available segment index at level iLevel+1. The call to
142697     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
142698     ** a single iLevel+2 segment if necessary.  */
142699     assert( FTS3_SEGCURSOR_PENDING==-1 );
142700     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
142701     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
142702     bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
142703   }
142704   if( rc!=SQLITE_OK ) goto finished;
142705 
142706   assert( csr.nSegment>0 );
142707   assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
142708   assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
142709 
142710   memset(&filter, 0, sizeof(Fts3SegFilter));
142711   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
142712   filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
142713 
142714   rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
142715   while( SQLITE_OK==rc ){
142716     rc = sqlite3Fts3SegReaderStep(p, &csr);
142717     if( rc!=SQLITE_ROW ) break;
142718     rc = fts3SegWriterAdd(p, &pWriter, 1,
142719         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
142720   }
142721   if( rc!=SQLITE_OK ) goto finished;
142722   assert( pWriter || bIgnoreEmpty );
142723 
142724   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
142725     rc = fts3DeleteSegdir(
142726         p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
142727     );
142728     if( rc!=SQLITE_OK ) goto finished;
142729   }
142730   if( pWriter ){
142731     rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
142732     if( rc==SQLITE_OK ){
142733       if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
142734         rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
142735       }
142736     }
142737   }
142738 
142739  finished:
142740   fts3SegWriterFree(pWriter);
142741   sqlite3Fts3SegReaderFinish(&csr);
142742   return rc;
142743 }
142744 
142745 
142746 /*
142747 ** Flush the contents of pendingTerms to level 0 segments.
142748 */
142749 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
142750   int rc = SQLITE_OK;
142751   int i;
142752 
142753   for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
142754     rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
142755     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
142756   }
142757   sqlite3Fts3PendingTermsClear(p);
142758 
142759   /* Determine the auto-incr-merge setting if unknown.  If enabled,
142760   ** estimate the number of leaf blocks of content to be written
142761   */
142762   if( rc==SQLITE_OK && p->bHasStat
142763    && p->nAutoincrmerge==0xff && p->nLeafAdd>0
142764   ){
142765     sqlite3_stmt *pStmt = 0;
142766     rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
142767     if( rc==SQLITE_OK ){
142768       sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
142769       rc = sqlite3_step(pStmt);
142770       if( rc==SQLITE_ROW ){
142771         p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
142772         if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
142773       }else if( rc==SQLITE_DONE ){
142774         p->nAutoincrmerge = 0;
142775       }
142776       rc = sqlite3_reset(pStmt);
142777     }
142778   }
142779   return rc;
142780 }
142781 
142782 /*
142783 ** Encode N integers as varints into a blob.
142784 */
142785 static void fts3EncodeIntArray(
142786   int N,             /* The number of integers to encode */
142787   u32 *a,            /* The integer values */
142788   char *zBuf,        /* Write the BLOB here */
142789   int *pNBuf         /* Write number of bytes if zBuf[] used here */
142790 ){
142791   int i, j;
142792   for(i=j=0; i<N; i++){
142793     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
142794   }
142795   *pNBuf = j;
142796 }
142797 
142798 /*
142799 ** Decode a blob of varints into N integers
142800 */
142801 static void fts3DecodeIntArray(
142802   int N,             /* The number of integers to decode */
142803   u32 *a,            /* Write the integer values */
142804   const char *zBuf,  /* The BLOB containing the varints */
142805   int nBuf           /* size of the BLOB */
142806 ){
142807   int i, j;
142808   UNUSED_PARAMETER(nBuf);
142809   for(i=j=0; i<N; i++){
142810     sqlite3_int64 x;
142811     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
142812     assert(j<=nBuf);
142813     a[i] = (u32)(x & 0xffffffff);
142814   }
142815 }
142816 
142817 /*
142818 ** Insert the sizes (in tokens) for each column of the document
142819 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
142820 ** a blob of varints.
142821 */
142822 static void fts3InsertDocsize(
142823   int *pRC,                       /* Result code */
142824   Fts3Table *p,                   /* Table into which to insert */
142825   u32 *aSz                        /* Sizes of each column, in tokens */
142826 ){
142827   char *pBlob;             /* The BLOB encoding of the document size */
142828   int nBlob;               /* Number of bytes in the BLOB */
142829   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
142830   int rc;                  /* Result code from subfunctions */
142831 
142832   if( *pRC ) return;
142833   pBlob = sqlite3_malloc( 10*p->nColumn );
142834   if( pBlob==0 ){
142835     *pRC = SQLITE_NOMEM;
142836     return;
142837   }
142838   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
142839   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
142840   if( rc ){
142841     sqlite3_free(pBlob);
142842     *pRC = rc;
142843     return;
142844   }
142845   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
142846   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
142847   sqlite3_step(pStmt);
142848   *pRC = sqlite3_reset(pStmt);
142849 }
142850 
142851 /*
142852 ** Record 0 of the %_stat table contains a blob consisting of N varints,
142853 ** where N is the number of user defined columns in the fts3 table plus
142854 ** two. If nCol is the number of user defined columns, then values of the
142855 ** varints are set as follows:
142856 **
142857 **   Varint 0:       Total number of rows in the table.
142858 **
142859 **   Varint 1..nCol: For each column, the total number of tokens stored in
142860 **                   the column for all rows of the table.
142861 **
142862 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
142863 **                   columns of all rows of the table.
142864 **
142865 */
142866 static void fts3UpdateDocTotals(
142867   int *pRC,                       /* The result code */
142868   Fts3Table *p,                   /* Table being updated */
142869   u32 *aSzIns,                    /* Size increases */
142870   u32 *aSzDel,                    /* Size decreases */
142871   int nChng                       /* Change in the number of documents */
142872 ){
142873   char *pBlob;             /* Storage for BLOB written into %_stat */
142874   int nBlob;               /* Size of BLOB written into %_stat */
142875   u32 *a;                  /* Array of integers that becomes the BLOB */
142876   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
142877   int i;                   /* Loop counter */
142878   int rc;                  /* Result code from subfunctions */
142879 
142880   const int nStat = p->nColumn+2;
142881 
142882   if( *pRC ) return;
142883   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
142884   if( a==0 ){
142885     *pRC = SQLITE_NOMEM;
142886     return;
142887   }
142888   pBlob = (char*)&a[nStat];
142889   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
142890   if( rc ){
142891     sqlite3_free(a);
142892     *pRC = rc;
142893     return;
142894   }
142895   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
142896   if( sqlite3_step(pStmt)==SQLITE_ROW ){
142897     fts3DecodeIntArray(nStat, a,
142898          sqlite3_column_blob(pStmt, 0),
142899          sqlite3_column_bytes(pStmt, 0));
142900   }else{
142901     memset(a, 0, sizeof(u32)*(nStat) );
142902   }
142903   rc = sqlite3_reset(pStmt);
142904   if( rc!=SQLITE_OK ){
142905     sqlite3_free(a);
142906     *pRC = rc;
142907     return;
142908   }
142909   if( nChng<0 && a[0]<(u32)(-nChng) ){
142910     a[0] = 0;
142911   }else{
142912     a[0] += nChng;
142913   }
142914   for(i=0; i<p->nColumn+1; i++){
142915     u32 x = a[i+1];
142916     if( x+aSzIns[i] < aSzDel[i] ){
142917       x = 0;
142918     }else{
142919       x = x + aSzIns[i] - aSzDel[i];
142920     }
142921     a[i+1] = x;
142922   }
142923   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
142924   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
142925   if( rc ){
142926     sqlite3_free(a);
142927     *pRC = rc;
142928     return;
142929   }
142930   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
142931   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
142932   sqlite3_step(pStmt);
142933   *pRC = sqlite3_reset(pStmt);
142934   sqlite3_free(a);
142935 }
142936 
142937 /*
142938 ** Merge the entire database so that there is one segment for each
142939 ** iIndex/iLangid combination.
142940 */
142941 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
142942   int bSeenDone = 0;
142943   int rc;
142944   sqlite3_stmt *pAllLangid = 0;
142945 
142946   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
142947   if( rc==SQLITE_OK ){
142948     int rc2;
142949     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
142950     while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
142951       int i;
142952       int iLangid = sqlite3_column_int(pAllLangid, 0);
142953       for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
142954         rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
142955         if( rc==SQLITE_DONE ){
142956           bSeenDone = 1;
142957           rc = SQLITE_OK;
142958         }
142959       }
142960     }
142961     rc2 = sqlite3_reset(pAllLangid);
142962     if( rc==SQLITE_OK ) rc = rc2;
142963   }
142964 
142965   sqlite3Fts3SegmentsClose(p);
142966   sqlite3Fts3PendingTermsClear(p);
142967 
142968   return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
142969 }
142970 
142971 /*
142972 ** This function is called when the user executes the following statement:
142973 **
142974 **     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
142975 **
142976 ** The entire FTS index is discarded and rebuilt. If the table is one
142977 ** created using the content=xxx option, then the new index is based on
142978 ** the current contents of the xxx table. Otherwise, it is rebuilt based
142979 ** on the contents of the %_content table.
142980 */
142981 static int fts3DoRebuild(Fts3Table *p){
142982   int rc;                         /* Return Code */
142983 
142984   rc = fts3DeleteAll(p, 0);
142985   if( rc==SQLITE_OK ){
142986     u32 *aSz = 0;
142987     u32 *aSzIns = 0;
142988     u32 *aSzDel = 0;
142989     sqlite3_stmt *pStmt = 0;
142990     int nEntry = 0;
142991 
142992     /* Compose and prepare an SQL statement to loop through the content table */
142993     char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
142994     if( !zSql ){
142995       rc = SQLITE_NOMEM;
142996     }else{
142997       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
142998       sqlite3_free(zSql);
142999     }
143000 
143001     if( rc==SQLITE_OK ){
143002       int nByte = sizeof(u32) * (p->nColumn+1)*3;
143003       aSz = (u32 *)sqlite3_malloc(nByte);
143004       if( aSz==0 ){
143005         rc = SQLITE_NOMEM;
143006       }else{
143007         memset(aSz, 0, nByte);
143008         aSzIns = &aSz[p->nColumn+1];
143009         aSzDel = &aSzIns[p->nColumn+1];
143010       }
143011     }
143012 
143013     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
143014       int iCol;
143015       int iLangid = langidFromSelect(p, pStmt);
143016       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
143017       memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
143018       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
143019         if( p->abNotindexed[iCol]==0 ){
143020           const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
143021           rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
143022           aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
143023         }
143024       }
143025       if( p->bHasDocsize ){
143026         fts3InsertDocsize(&rc, p, aSz);
143027       }
143028       if( rc!=SQLITE_OK ){
143029         sqlite3_finalize(pStmt);
143030         pStmt = 0;
143031       }else{
143032         nEntry++;
143033         for(iCol=0; iCol<=p->nColumn; iCol++){
143034           aSzIns[iCol] += aSz[iCol];
143035         }
143036       }
143037     }
143038     if( p->bFts4 ){
143039       fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
143040     }
143041     sqlite3_free(aSz);
143042 
143043     if( pStmt ){
143044       int rc2 = sqlite3_finalize(pStmt);
143045       if( rc==SQLITE_OK ){
143046         rc = rc2;
143047       }
143048     }
143049   }
143050 
143051   return rc;
143052 }
143053 
143054 
143055 /*
143056 ** This function opens a cursor used to read the input data for an
143057 ** incremental merge operation. Specifically, it opens a cursor to scan
143058 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
143059 ** level iAbsLevel.
143060 */
143061 static int fts3IncrmergeCsr(
143062   Fts3Table *p,                   /* FTS3 table handle */
143063   sqlite3_int64 iAbsLevel,        /* Absolute level to open */
143064   int nSeg,                       /* Number of segments to merge */
143065   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
143066 ){
143067   int rc;                         /* Return Code */
143068   sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */
143069   int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
143070 
143071   /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
143072   memset(pCsr, 0, sizeof(*pCsr));
143073   nByte = sizeof(Fts3SegReader *) * nSeg;
143074   pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
143075 
143076   if( pCsr->apSegment==0 ){
143077     rc = SQLITE_NOMEM;
143078   }else{
143079     memset(pCsr->apSegment, 0, nByte);
143080     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
143081   }
143082   if( rc==SQLITE_OK ){
143083     int i;
143084     int rc2;
143085     sqlite3_bind_int64(pStmt, 1, iAbsLevel);
143086     assert( pCsr->nSegment==0 );
143087     for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
143088       rc = sqlite3Fts3SegReaderNew(i, 0,
143089           sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
143090           sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
143091           sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
143092           sqlite3_column_blob(pStmt, 4),         /* segdir.root */
143093           sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
143094           &pCsr->apSegment[i]
143095       );
143096       pCsr->nSegment++;
143097     }
143098     rc2 = sqlite3_reset(pStmt);
143099     if( rc==SQLITE_OK ) rc = rc2;
143100   }
143101 
143102   return rc;
143103 }
143104 
143105 typedef struct IncrmergeWriter IncrmergeWriter;
143106 typedef struct NodeWriter NodeWriter;
143107 typedef struct Blob Blob;
143108 typedef struct NodeReader NodeReader;
143109 
143110 /*
143111 ** An instance of the following structure is used as a dynamic buffer
143112 ** to build up nodes or other blobs of data in.
143113 **
143114 ** The function blobGrowBuffer() is used to extend the allocation.
143115 */
143116 struct Blob {
143117   char *a;                        /* Pointer to allocation */
143118   int n;                          /* Number of valid bytes of data in a[] */
143119   int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
143120 };
143121 
143122 /*
143123 ** This structure is used to build up buffers containing segment b-tree
143124 ** nodes (blocks).
143125 */
143126 struct NodeWriter {
143127   sqlite3_int64 iBlock;           /* Current block id */
143128   Blob key;                       /* Last key written to the current block */
143129   Blob block;                     /* Current block image */
143130 };
143131 
143132 /*
143133 ** An object of this type contains the state required to create or append
143134 ** to an appendable b-tree segment.
143135 */
143136 struct IncrmergeWriter {
143137   int nLeafEst;                   /* Space allocated for leaf blocks */
143138   int nWork;                      /* Number of leaf pages flushed */
143139   sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
143140   int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
143141   sqlite3_int64 iStart;           /* Block number of first allocated block */
143142   sqlite3_int64 iEnd;             /* Block number of last allocated block */
143143   sqlite3_int64 nLeafData;        /* Bytes of leaf page data so far */
143144   u8 bNoLeafData;                 /* If true, store 0 for segment size */
143145   NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
143146 };
143147 
143148 /*
143149 ** An object of the following type is used to read data from a single
143150 ** FTS segment node. See the following functions:
143151 **
143152 **     nodeReaderInit()
143153 **     nodeReaderNext()
143154 **     nodeReaderRelease()
143155 */
143156 struct NodeReader {
143157   const char *aNode;
143158   int nNode;
143159   int iOff;                       /* Current offset within aNode[] */
143160 
143161   /* Output variables. Containing the current node entry. */
143162   sqlite3_int64 iChild;           /* Pointer to child node */
143163   Blob term;                      /* Current term */
143164   const char *aDoclist;           /* Pointer to doclist */
143165   int nDoclist;                   /* Size of doclist in bytes */
143166 };
143167 
143168 /*
143169 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
143170 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
143171 ** bytes in size, extend (realloc) it to be so.
143172 **
143173 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
143174 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
143175 ** to reflect the new size of the pBlob->a[] buffer.
143176 */
143177 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
143178   if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
143179     int nAlloc = nMin;
143180     char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
143181     if( a ){
143182       pBlob->nAlloc = nAlloc;
143183       pBlob->a = a;
143184     }else{
143185       *pRc = SQLITE_NOMEM;
143186     }
143187   }
143188 }
143189 
143190 /*
143191 ** Attempt to advance the node-reader object passed as the first argument to
143192 ** the next entry on the node.
143193 **
143194 ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
143195 ** Otherwise return SQLITE_OK. If there is no next entry on the node
143196 ** (e.g. because the current entry is the last) set NodeReader->aNode to
143197 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
143198 ** variables for the new entry.
143199 */
143200 static int nodeReaderNext(NodeReader *p){
143201   int bFirst = (p->term.n==0);    /* True for first term on the node */
143202   int nPrefix = 0;                /* Bytes to copy from previous term */
143203   int nSuffix = 0;                /* Bytes to append to the prefix */
143204   int rc = SQLITE_OK;             /* Return code */
143205 
143206   assert( p->aNode );
143207   if( p->iChild && bFirst==0 ) p->iChild++;
143208   if( p->iOff>=p->nNode ){
143209     /* EOF */
143210     p->aNode = 0;
143211   }else{
143212     if( bFirst==0 ){
143213       p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
143214     }
143215     p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
143216 
143217     blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
143218     if( rc==SQLITE_OK ){
143219       memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
143220       p->term.n = nPrefix+nSuffix;
143221       p->iOff += nSuffix;
143222       if( p->iChild==0 ){
143223         p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
143224         p->aDoclist = &p->aNode[p->iOff];
143225         p->iOff += p->nDoclist;
143226       }
143227     }
143228   }
143229 
143230   assert( p->iOff<=p->nNode );
143231 
143232   return rc;
143233 }
143234 
143235 /*
143236 ** Release all dynamic resources held by node-reader object *p.
143237 */
143238 static void nodeReaderRelease(NodeReader *p){
143239   sqlite3_free(p->term.a);
143240 }
143241 
143242 /*
143243 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
143244 **
143245 ** If successful, SQLITE_OK is returned and the NodeReader object set to
143246 ** point to the first entry on the node (if any). Otherwise, an SQLite
143247 ** error code is returned.
143248 */
143249 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
143250   memset(p, 0, sizeof(NodeReader));
143251   p->aNode = aNode;
143252   p->nNode = nNode;
143253 
143254   /* Figure out if this is a leaf or an internal node. */
143255   if( p->aNode[0] ){
143256     /* An internal node. */
143257     p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
143258   }else{
143259     p->iOff = 1;
143260   }
143261 
143262   return nodeReaderNext(p);
143263 }
143264 
143265 /*
143266 ** This function is called while writing an FTS segment each time a leaf o
143267 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
143268 ** to be greater than the largest key on the node just written, but smaller
143269 ** than or equal to the first key that will be written to the next leaf
143270 ** node.
143271 **
143272 ** The block id of the leaf node just written to disk may be found in
143273 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
143274 */
143275 static int fts3IncrmergePush(
143276   Fts3Table *p,                   /* Fts3 table handle */
143277   IncrmergeWriter *pWriter,       /* Writer object */
143278   const char *zTerm,              /* Term to write to internal node */
143279   int nTerm                       /* Bytes at zTerm */
143280 ){
143281   sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
143282   int iLayer;
143283 
143284   assert( nTerm>0 );
143285   for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
143286     sqlite3_int64 iNextPtr = 0;
143287     NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
143288     int rc = SQLITE_OK;
143289     int nPrefix;
143290     int nSuffix;
143291     int nSpace;
143292 
143293     /* Figure out how much space the key will consume if it is written to
143294     ** the current node of layer iLayer. Due to the prefix compression,
143295     ** the space required changes depending on which node the key is to
143296     ** be added to.  */
143297     nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
143298     nSuffix = nTerm - nPrefix;
143299     nSpace  = sqlite3Fts3VarintLen(nPrefix);
143300     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
143301 
143302     if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
143303       /* If the current node of layer iLayer contains zero keys, or if adding
143304       ** the key to it will not cause it to grow to larger than nNodeSize
143305       ** bytes in size, write the key here.  */
143306 
143307       Blob *pBlk = &pNode->block;
143308       if( pBlk->n==0 ){
143309         blobGrowBuffer(pBlk, p->nNodeSize, &rc);
143310         if( rc==SQLITE_OK ){
143311           pBlk->a[0] = (char)iLayer;
143312           pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
143313         }
143314       }
143315       blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
143316       blobGrowBuffer(&pNode->key, nTerm, &rc);
143317 
143318       if( rc==SQLITE_OK ){
143319         if( pNode->key.n ){
143320           pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
143321         }
143322         pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
143323         memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
143324         pBlk->n += nSuffix;
143325 
143326         memcpy(pNode->key.a, zTerm, nTerm);
143327         pNode->key.n = nTerm;
143328       }
143329     }else{
143330       /* Otherwise, flush the current node of layer iLayer to disk.
143331       ** Then allocate a new, empty sibling node. The key will be written
143332       ** into the parent of this node. */
143333       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
143334 
143335       assert( pNode->block.nAlloc>=p->nNodeSize );
143336       pNode->block.a[0] = (char)iLayer;
143337       pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
143338 
143339       iNextPtr = pNode->iBlock;
143340       pNode->iBlock++;
143341       pNode->key.n = 0;
143342     }
143343 
143344     if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
143345     iPtr = iNextPtr;
143346   }
143347 
143348   assert( 0 );
143349   return 0;
143350 }
143351 
143352 /*
143353 ** Append a term and (optionally) doclist to the FTS segment node currently
143354 ** stored in blob *pNode. The node need not contain any terms, but the
143355 ** header must be written before this function is called.
143356 **
143357 ** A node header is a single 0x00 byte for a leaf node, or a height varint
143358 ** followed by the left-hand-child varint for an internal node.
143359 **
143360 ** The term to be appended is passed via arguments zTerm/nTerm. For a
143361 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
143362 ** node, both aDoclist and nDoclist must be passed 0.
143363 **
143364 ** If the size of the value in blob pPrev is zero, then this is the first
143365 ** term written to the node. Otherwise, pPrev contains a copy of the
143366 ** previous term. Before this function returns, it is updated to contain a
143367 ** copy of zTerm/nTerm.
143368 **
143369 ** It is assumed that the buffer associated with pNode is already large
143370 ** enough to accommodate the new entry. The buffer associated with pPrev
143371 ** is extended by this function if requrired.
143372 **
143373 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
143374 ** returned. Otherwise, SQLITE_OK.
143375 */
143376 static int fts3AppendToNode(
143377   Blob *pNode,                    /* Current node image to append to */
143378   Blob *pPrev,                    /* Buffer containing previous term written */
143379   const char *zTerm,              /* New term to write */
143380   int nTerm,                      /* Size of zTerm in bytes */
143381   const char *aDoclist,           /* Doclist (or NULL) to write */
143382   int nDoclist                    /* Size of aDoclist in bytes */
143383 ){
143384   int rc = SQLITE_OK;             /* Return code */
143385   int bFirst = (pPrev->n==0);     /* True if this is the first term written */
143386   int nPrefix;                    /* Size of term prefix in bytes */
143387   int nSuffix;                    /* Size of term suffix in bytes */
143388 
143389   /* Node must have already been started. There must be a doclist for a
143390   ** leaf node, and there must not be a doclist for an internal node.  */
143391   assert( pNode->n>0 );
143392   assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
143393 
143394   blobGrowBuffer(pPrev, nTerm, &rc);
143395   if( rc!=SQLITE_OK ) return rc;
143396 
143397   nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
143398   nSuffix = nTerm - nPrefix;
143399   memcpy(pPrev->a, zTerm, nTerm);
143400   pPrev->n = nTerm;
143401 
143402   if( bFirst==0 ){
143403     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
143404   }
143405   pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
143406   memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
143407   pNode->n += nSuffix;
143408 
143409   if( aDoclist ){
143410     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
143411     memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
143412     pNode->n += nDoclist;
143413   }
143414 
143415   assert( pNode->n<=pNode->nAlloc );
143416 
143417   return SQLITE_OK;
143418 }
143419 
143420 /*
143421 ** Append the current term and doclist pointed to by cursor pCsr to the
143422 ** appendable b-tree segment opened for writing by pWriter.
143423 **
143424 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
143425 */
143426 static int fts3IncrmergeAppend(
143427   Fts3Table *p,                   /* Fts3 table handle */
143428   IncrmergeWriter *pWriter,       /* Writer object */
143429   Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
143430 ){
143431   const char *zTerm = pCsr->zTerm;
143432   int nTerm = pCsr->nTerm;
143433   const char *aDoclist = pCsr->aDoclist;
143434   int nDoclist = pCsr->nDoclist;
143435   int rc = SQLITE_OK;           /* Return code */
143436   int nSpace;                   /* Total space in bytes required on leaf */
143437   int nPrefix;                  /* Size of prefix shared with previous term */
143438   int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
143439   NodeWriter *pLeaf;            /* Object used to write leaf nodes */
143440 
143441   pLeaf = &pWriter->aNodeWriter[0];
143442   nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
143443   nSuffix = nTerm - nPrefix;
143444 
143445   nSpace  = sqlite3Fts3VarintLen(nPrefix);
143446   nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
143447   nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
143448 
143449   /* If the current block is not empty, and if adding this term/doclist
143450   ** to the current block would make it larger than Fts3Table.nNodeSize
143451   ** bytes, write this block out to the database. */
143452   if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
143453     rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
143454     pWriter->nWork++;
143455 
143456     /* Add the current term to the parent node. The term added to the
143457     ** parent must:
143458     **
143459     **   a) be greater than the largest term on the leaf node just written
143460     **      to the database (still available in pLeaf->key), and
143461     **
143462     **   b) be less than or equal to the term about to be added to the new
143463     **      leaf node (zTerm/nTerm).
143464     **
143465     ** In other words, it must be the prefix of zTerm 1 byte longer than
143466     ** the common prefix (if any) of zTerm and pWriter->zTerm.
143467     */
143468     if( rc==SQLITE_OK ){
143469       rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
143470     }
143471 
143472     /* Advance to the next output block */
143473     pLeaf->iBlock++;
143474     pLeaf->key.n = 0;
143475     pLeaf->block.n = 0;
143476 
143477     nSuffix = nTerm;
143478     nSpace  = 1;
143479     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
143480     nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
143481   }
143482 
143483   pWriter->nLeafData += nSpace;
143484   blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
143485   if( rc==SQLITE_OK ){
143486     if( pLeaf->block.n==0 ){
143487       pLeaf->block.n = 1;
143488       pLeaf->block.a[0] = '\0';
143489     }
143490     rc = fts3AppendToNode(
143491         &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
143492     );
143493   }
143494 
143495   return rc;
143496 }
143497 
143498 /*
143499 ** This function is called to release all dynamic resources held by the
143500 ** merge-writer object pWriter, and if no error has occurred, to flush
143501 ** all outstanding node buffers held by pWriter to disk.
143502 **
143503 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
143504 ** is made to write any data to disk. Instead, this function serves only
143505 ** to release outstanding resources.
143506 **
143507 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
143508 ** flushing buffers to disk, *pRc is set to an SQLite error code before
143509 ** returning.
143510 */
143511 static void fts3IncrmergeRelease(
143512   Fts3Table *p,                   /* FTS3 table handle */
143513   IncrmergeWriter *pWriter,       /* Merge-writer object */
143514   int *pRc                        /* IN/OUT: Error code */
143515 ){
143516   int i;                          /* Used to iterate through non-root layers */
143517   int iRoot;                      /* Index of root in pWriter->aNodeWriter */
143518   NodeWriter *pRoot;              /* NodeWriter for root node */
143519   int rc = *pRc;                  /* Error code */
143520 
143521   /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
143522   ** root node. If the segment fits entirely on a single leaf node, iRoot
143523   ** will be set to 0. If the root node is the parent of the leaves, iRoot
143524   ** will be 1. And so on.  */
143525   for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
143526     NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
143527     if( pNode->block.n>0 ) break;
143528     assert( *pRc || pNode->block.nAlloc==0 );
143529     assert( *pRc || pNode->key.nAlloc==0 );
143530     sqlite3_free(pNode->block.a);
143531     sqlite3_free(pNode->key.a);
143532   }
143533 
143534   /* Empty output segment. This is a no-op. */
143535   if( iRoot<0 ) return;
143536 
143537   /* The entire output segment fits on a single node. Normally, this means
143538   ** the node would be stored as a blob in the "root" column of the %_segdir
143539   ** table. However, this is not permitted in this case. The problem is that
143540   ** space has already been reserved in the %_segments table, and so the
143541   ** start_block and end_block fields of the %_segdir table must be populated.
143542   ** And, by design or by accident, released versions of FTS cannot handle
143543   ** segments that fit entirely on the root node with start_block!=0.
143544   **
143545   ** Instead, create a synthetic root node that contains nothing but a
143546   ** pointer to the single content node. So that the segment consists of a
143547   ** single leaf and a single interior (root) node.
143548   **
143549   ** Todo: Better might be to defer allocating space in the %_segments
143550   ** table until we are sure it is needed.
143551   */
143552   if( iRoot==0 ){
143553     Blob *pBlock = &pWriter->aNodeWriter[1].block;
143554     blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
143555     if( rc==SQLITE_OK ){
143556       pBlock->a[0] = 0x01;
143557       pBlock->n = 1 + sqlite3Fts3PutVarint(
143558           &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
143559       );
143560     }
143561     iRoot = 1;
143562   }
143563   pRoot = &pWriter->aNodeWriter[iRoot];
143564 
143565   /* Flush all currently outstanding nodes to disk. */
143566   for(i=0; i<iRoot; i++){
143567     NodeWriter *pNode = &pWriter->aNodeWriter[i];
143568     if( pNode->block.n>0 && rc==SQLITE_OK ){
143569       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
143570     }
143571     sqlite3_free(pNode->block.a);
143572     sqlite3_free(pNode->key.a);
143573   }
143574 
143575   /* Write the %_segdir record. */
143576   if( rc==SQLITE_OK ){
143577     rc = fts3WriteSegdir(p,
143578         pWriter->iAbsLevel+1,               /* level */
143579         pWriter->iIdx,                      /* idx */
143580         pWriter->iStart,                    /* start_block */
143581         pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
143582         pWriter->iEnd,                      /* end_block */
143583         (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0),   /* end_block */
143584         pRoot->block.a, pRoot->block.n      /* root */
143585     );
143586   }
143587   sqlite3_free(pRoot->block.a);
143588   sqlite3_free(pRoot->key.a);
143589 
143590   *pRc = rc;
143591 }
143592 
143593 /*
143594 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
143595 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
143596 ** the other, it is considered to be smaller than the other.
143597 **
143598 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
143599 ** if it is greater.
143600 */
143601 static int fts3TermCmp(
143602   const char *zLhs, int nLhs,     /* LHS of comparison */
143603   const char *zRhs, int nRhs      /* RHS of comparison */
143604 ){
143605   int nCmp = MIN(nLhs, nRhs);
143606   int res;
143607 
143608   res = memcmp(zLhs, zRhs, nCmp);
143609   if( res==0 ) res = nLhs - nRhs;
143610 
143611   return res;
143612 }
143613 
143614 
143615 /*
143616 ** Query to see if the entry in the %_segments table with blockid iEnd is
143617 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
143618 ** returning. Otherwise, set *pbRes to 0.
143619 **
143620 ** Or, if an error occurs while querying the database, return an SQLite
143621 ** error code. The final value of *pbRes is undefined in this case.
143622 **
143623 ** This is used to test if a segment is an "appendable" segment. If it
143624 ** is, then a NULL entry has been inserted into the %_segments table
143625 ** with blockid %_segdir.end_block.
143626 */
143627 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
143628   int bRes = 0;                   /* Result to set *pbRes to */
143629   sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
143630   int rc;                         /* Return code */
143631 
143632   rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
143633   if( rc==SQLITE_OK ){
143634     sqlite3_bind_int64(pCheck, 1, iEnd);
143635     if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
143636     rc = sqlite3_reset(pCheck);
143637   }
143638 
143639   *pbRes = bRes;
143640   return rc;
143641 }
143642 
143643 /*
143644 ** This function is called when initializing an incremental-merge operation.
143645 ** It checks if the existing segment with index value iIdx at absolute level
143646 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
143647 ** merge-writer object *pWriter is initialized to write to it.
143648 **
143649 ** An existing segment can be appended to by an incremental merge if:
143650 **
143651 **   * It was initially created as an appendable segment (with all required
143652 **     space pre-allocated), and
143653 **
143654 **   * The first key read from the input (arguments zKey and nKey) is
143655 **     greater than the largest key currently stored in the potential
143656 **     output segment.
143657 */
143658 static int fts3IncrmergeLoad(
143659   Fts3Table *p,                   /* Fts3 table handle */
143660   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
143661   int iIdx,                       /* Index of candidate output segment */
143662   const char *zKey,               /* First key to write */
143663   int nKey,                       /* Number of bytes in nKey */
143664   IncrmergeWriter *pWriter        /* Populate this object */
143665 ){
143666   int rc;                         /* Return code */
143667   sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
143668 
143669   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
143670   if( rc==SQLITE_OK ){
143671     sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
143672     sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
143673     sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
143674     const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
143675     int nRoot = 0;                /* Size of aRoot[] in bytes */
143676     int rc2;                      /* Return code from sqlite3_reset() */
143677     int bAppendable = 0;          /* Set to true if segment is appendable */
143678 
143679     /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
143680     sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
143681     sqlite3_bind_int(pSelect, 2, iIdx);
143682     if( sqlite3_step(pSelect)==SQLITE_ROW ){
143683       iStart = sqlite3_column_int64(pSelect, 1);
143684       iLeafEnd = sqlite3_column_int64(pSelect, 2);
143685       fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
143686       if( pWriter->nLeafData<0 ){
143687         pWriter->nLeafData = pWriter->nLeafData * -1;
143688       }
143689       pWriter->bNoLeafData = (pWriter->nLeafData==0);
143690       nRoot = sqlite3_column_bytes(pSelect, 4);
143691       aRoot = sqlite3_column_blob(pSelect, 4);
143692     }else{
143693       return sqlite3_reset(pSelect);
143694     }
143695 
143696     /* Check for the zero-length marker in the %_segments table */
143697     rc = fts3IsAppendable(p, iEnd, &bAppendable);
143698 
143699     /* Check that zKey/nKey is larger than the largest key the candidate */
143700     if( rc==SQLITE_OK && bAppendable ){
143701       char *aLeaf = 0;
143702       int nLeaf = 0;
143703 
143704       rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
143705       if( rc==SQLITE_OK ){
143706         NodeReader reader;
143707         for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
143708             rc==SQLITE_OK && reader.aNode;
143709             rc = nodeReaderNext(&reader)
143710         ){
143711           assert( reader.aNode );
143712         }
143713         if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
143714           bAppendable = 0;
143715         }
143716         nodeReaderRelease(&reader);
143717       }
143718       sqlite3_free(aLeaf);
143719     }
143720 
143721     if( rc==SQLITE_OK && bAppendable ){
143722       /* It is possible to append to this segment. Set up the IncrmergeWriter
143723       ** object to do so.  */
143724       int i;
143725       int nHeight = (int)aRoot[0];
143726       NodeWriter *pNode;
143727 
143728       pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
143729       pWriter->iStart = iStart;
143730       pWriter->iEnd = iEnd;
143731       pWriter->iAbsLevel = iAbsLevel;
143732       pWriter->iIdx = iIdx;
143733 
143734       for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
143735         pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
143736       }
143737 
143738       pNode = &pWriter->aNodeWriter[nHeight];
143739       pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
143740       blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
143741       if( rc==SQLITE_OK ){
143742         memcpy(pNode->block.a, aRoot, nRoot);
143743         pNode->block.n = nRoot;
143744       }
143745 
143746       for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
143747         NodeReader reader;
143748         pNode = &pWriter->aNodeWriter[i];
143749 
143750         rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
143751         while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
143752         blobGrowBuffer(&pNode->key, reader.term.n, &rc);
143753         if( rc==SQLITE_OK ){
143754           memcpy(pNode->key.a, reader.term.a, reader.term.n);
143755           pNode->key.n = reader.term.n;
143756           if( i>0 ){
143757             char *aBlock = 0;
143758             int nBlock = 0;
143759             pNode = &pWriter->aNodeWriter[i-1];
143760             pNode->iBlock = reader.iChild;
143761             rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
143762             blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
143763             if( rc==SQLITE_OK ){
143764               memcpy(pNode->block.a, aBlock, nBlock);
143765               pNode->block.n = nBlock;
143766             }
143767             sqlite3_free(aBlock);
143768           }
143769         }
143770         nodeReaderRelease(&reader);
143771       }
143772     }
143773 
143774     rc2 = sqlite3_reset(pSelect);
143775     if( rc==SQLITE_OK ) rc = rc2;
143776   }
143777 
143778   return rc;
143779 }
143780 
143781 /*
143782 ** Determine the largest segment index value that exists within absolute
143783 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
143784 ** one before returning SQLITE_OK. Or, if there are no segments at all
143785 ** within level iAbsLevel, set *piIdx to zero.
143786 **
143787 ** If an error occurs, return an SQLite error code. The final value of
143788 ** *piIdx is undefined in this case.
143789 */
143790 static int fts3IncrmergeOutputIdx(
143791   Fts3Table *p,                   /* FTS Table handle */
143792   sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
143793   int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
143794 ){
143795   int rc;
143796   sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
143797 
143798   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
143799   if( rc==SQLITE_OK ){
143800     sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
143801     sqlite3_step(pOutputIdx);
143802     *piIdx = sqlite3_column_int(pOutputIdx, 0);
143803     rc = sqlite3_reset(pOutputIdx);
143804   }
143805 
143806   return rc;
143807 }
143808 
143809 /*
143810 ** Allocate an appendable output segment on absolute level iAbsLevel+1
143811 ** with idx value iIdx.
143812 **
143813 ** In the %_segdir table, a segment is defined by the values in three
143814 ** columns:
143815 **
143816 **     start_block
143817 **     leaves_end_block
143818 **     end_block
143819 **
143820 ** When an appendable segment is allocated, it is estimated that the
143821 ** maximum number of leaf blocks that may be required is the sum of the
143822 ** number of leaf blocks consumed by the input segments, plus the number
143823 ** of input segments, multiplied by two. This value is stored in stack
143824 ** variable nLeafEst.
143825 **
143826 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
143827 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
143828 ** array of leaf nodes starts at the first block allocated. The array
143829 ** of interior nodes that are parents of the leaf nodes start at block
143830 ** (start_block + (1 + end_block - start_block) / 16). And so on.
143831 **
143832 ** In the actual code below, the value "16" is replaced with the
143833 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
143834 */
143835 static int fts3IncrmergeWriter(
143836   Fts3Table *p,                   /* Fts3 table handle */
143837   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
143838   int iIdx,                       /* Index of new output segment */
143839   Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
143840   IncrmergeWriter *pWriter        /* Populate this object */
143841 ){
143842   int rc;                         /* Return Code */
143843   int i;                          /* Iterator variable */
143844   int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
143845   sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
143846   sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
143847 
143848   /* Calculate nLeafEst. */
143849   rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
143850   if( rc==SQLITE_OK ){
143851     sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
143852     sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
143853     if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
143854       nLeafEst = sqlite3_column_int(pLeafEst, 0);
143855     }
143856     rc = sqlite3_reset(pLeafEst);
143857   }
143858   if( rc!=SQLITE_OK ) return rc;
143859 
143860   /* Calculate the first block to use in the output segment */
143861   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
143862   if( rc==SQLITE_OK ){
143863     if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
143864       pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
143865       pWriter->iEnd = pWriter->iStart - 1;
143866       pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
143867     }
143868     rc = sqlite3_reset(pFirstBlock);
143869   }
143870   if( rc!=SQLITE_OK ) return rc;
143871 
143872   /* Insert the marker in the %_segments table to make sure nobody tries
143873   ** to steal the space just allocated. This is also used to identify
143874   ** appendable segments.  */
143875   rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
143876   if( rc!=SQLITE_OK ) return rc;
143877 
143878   pWriter->iAbsLevel = iAbsLevel;
143879   pWriter->nLeafEst = nLeafEst;
143880   pWriter->iIdx = iIdx;
143881 
143882   /* Set up the array of NodeWriter objects */
143883   for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
143884     pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
143885   }
143886   return SQLITE_OK;
143887 }
143888 
143889 /*
143890 ** Remove an entry from the %_segdir table. This involves running the
143891 ** following two statements:
143892 **
143893 **   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
143894 **   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
143895 **
143896 ** The DELETE statement removes the specific %_segdir level. The UPDATE
143897 ** statement ensures that the remaining segments have contiguously allocated
143898 ** idx values.
143899 */
143900 static int fts3RemoveSegdirEntry(
143901   Fts3Table *p,                   /* FTS3 table handle */
143902   sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
143903   int iIdx                        /* Index of %_segdir entry to delete */
143904 ){
143905   int rc;                         /* Return code */
143906   sqlite3_stmt *pDelete = 0;      /* DELETE statement */
143907 
143908   rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
143909   if( rc==SQLITE_OK ){
143910     sqlite3_bind_int64(pDelete, 1, iAbsLevel);
143911     sqlite3_bind_int(pDelete, 2, iIdx);
143912     sqlite3_step(pDelete);
143913     rc = sqlite3_reset(pDelete);
143914   }
143915 
143916   return rc;
143917 }
143918 
143919 /*
143920 ** One or more segments have just been removed from absolute level iAbsLevel.
143921 ** Update the 'idx' values of the remaining segments in the level so that
143922 ** the idx values are a contiguous sequence starting from 0.
143923 */
143924 static int fts3RepackSegdirLevel(
143925   Fts3Table *p,                   /* FTS3 table handle */
143926   sqlite3_int64 iAbsLevel         /* Absolute level to repack */
143927 ){
143928   int rc;                         /* Return code */
143929   int *aIdx = 0;                  /* Array of remaining idx values */
143930   int nIdx = 0;                   /* Valid entries in aIdx[] */
143931   int nAlloc = 0;                 /* Allocated size of aIdx[] */
143932   int i;                          /* Iterator variable */
143933   sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
143934   sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
143935 
143936   rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
143937   if( rc==SQLITE_OK ){
143938     int rc2;
143939     sqlite3_bind_int64(pSelect, 1, iAbsLevel);
143940     while( SQLITE_ROW==sqlite3_step(pSelect) ){
143941       if( nIdx>=nAlloc ){
143942         int *aNew;
143943         nAlloc += 16;
143944         aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
143945         if( !aNew ){
143946           rc = SQLITE_NOMEM;
143947           break;
143948         }
143949         aIdx = aNew;
143950       }
143951       aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
143952     }
143953     rc2 = sqlite3_reset(pSelect);
143954     if( rc==SQLITE_OK ) rc = rc2;
143955   }
143956 
143957   if( rc==SQLITE_OK ){
143958     rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
143959   }
143960   if( rc==SQLITE_OK ){
143961     sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
143962   }
143963 
143964   assert( p->bIgnoreSavepoint==0 );
143965   p->bIgnoreSavepoint = 1;
143966   for(i=0; rc==SQLITE_OK && i<nIdx; i++){
143967     if( aIdx[i]!=i ){
143968       sqlite3_bind_int(pUpdate, 3, aIdx[i]);
143969       sqlite3_bind_int(pUpdate, 1, i);
143970       sqlite3_step(pUpdate);
143971       rc = sqlite3_reset(pUpdate);
143972     }
143973   }
143974   p->bIgnoreSavepoint = 0;
143975 
143976   sqlite3_free(aIdx);
143977   return rc;
143978 }
143979 
143980 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
143981   pNode->a[0] = (char)iHeight;
143982   if( iChild ){
143983     assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
143984     pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
143985   }else{
143986     assert( pNode->nAlloc>=1 );
143987     pNode->n = 1;
143988   }
143989 }
143990 
143991 /*
143992 ** The first two arguments are a pointer to and the size of a segment b-tree
143993 ** node. The node may be a leaf or an internal node.
143994 **
143995 ** This function creates a new node image in blob object *pNew by copying
143996 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
143997 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
143998 */
143999 static int fts3TruncateNode(
144000   const char *aNode,              /* Current node image */
144001   int nNode,                      /* Size of aNode in bytes */
144002   Blob *pNew,                     /* OUT: Write new node image here */
144003   const char *zTerm,              /* Omit all terms smaller than this */
144004   int nTerm,                      /* Size of zTerm in bytes */
144005   sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
144006 ){
144007   NodeReader reader;              /* Reader object */
144008   Blob prev = {0, 0, 0};          /* Previous term written to new node */
144009   int rc = SQLITE_OK;             /* Return code */
144010   int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
144011 
144012   /* Allocate required output space */
144013   blobGrowBuffer(pNew, nNode, &rc);
144014   if( rc!=SQLITE_OK ) return rc;
144015   pNew->n = 0;
144016 
144017   /* Populate new node buffer */
144018   for(rc = nodeReaderInit(&reader, aNode, nNode);
144019       rc==SQLITE_OK && reader.aNode;
144020       rc = nodeReaderNext(&reader)
144021   ){
144022     if( pNew->n==0 ){
144023       int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
144024       if( res<0 || (bLeaf==0 && res==0) ) continue;
144025       fts3StartNode(pNew, (int)aNode[0], reader.iChild);
144026       *piBlock = reader.iChild;
144027     }
144028     rc = fts3AppendToNode(
144029         pNew, &prev, reader.term.a, reader.term.n,
144030         reader.aDoclist, reader.nDoclist
144031     );
144032     if( rc!=SQLITE_OK ) break;
144033   }
144034   if( pNew->n==0 ){
144035     fts3StartNode(pNew, (int)aNode[0], reader.iChild);
144036     *piBlock = reader.iChild;
144037   }
144038   assert( pNew->n<=pNew->nAlloc );
144039 
144040   nodeReaderRelease(&reader);
144041   sqlite3_free(prev.a);
144042   return rc;
144043 }
144044 
144045 /*
144046 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
144047 ** level iAbsLevel. This may involve deleting entries from the %_segments
144048 ** table, and modifying existing entries in both the %_segments and %_segdir
144049 ** tables.
144050 **
144051 ** SQLITE_OK is returned if the segment is updated successfully. Or an
144052 ** SQLite error code otherwise.
144053 */
144054 static int fts3TruncateSegment(
144055   Fts3Table *p,                   /* FTS3 table handle */
144056   sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
144057   int iIdx,                       /* Index within level of segment to modify */
144058   const char *zTerm,              /* Remove terms smaller than this */
144059   int nTerm                      /* Number of bytes in buffer zTerm */
144060 ){
144061   int rc = SQLITE_OK;             /* Return code */
144062   Blob root = {0,0,0};            /* New root page image */
144063   Blob block = {0,0,0};           /* Buffer used for any other block */
144064   sqlite3_int64 iBlock = 0;       /* Block id */
144065   sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
144066   sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
144067   sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
144068 
144069   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
144070   if( rc==SQLITE_OK ){
144071     int rc2;                      /* sqlite3_reset() return code */
144072     sqlite3_bind_int64(pFetch, 1, iAbsLevel);
144073     sqlite3_bind_int(pFetch, 2, iIdx);
144074     if( SQLITE_ROW==sqlite3_step(pFetch) ){
144075       const char *aRoot = sqlite3_column_blob(pFetch, 4);
144076       int nRoot = sqlite3_column_bytes(pFetch, 4);
144077       iOldStart = sqlite3_column_int64(pFetch, 1);
144078       rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
144079     }
144080     rc2 = sqlite3_reset(pFetch);
144081     if( rc==SQLITE_OK ) rc = rc2;
144082   }
144083 
144084   while( rc==SQLITE_OK && iBlock ){
144085     char *aBlock = 0;
144086     int nBlock = 0;
144087     iNewStart = iBlock;
144088 
144089     rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
144090     if( rc==SQLITE_OK ){
144091       rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
144092     }
144093     if( rc==SQLITE_OK ){
144094       rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
144095     }
144096     sqlite3_free(aBlock);
144097   }
144098 
144099   /* Variable iNewStart now contains the first valid leaf node. */
144100   if( rc==SQLITE_OK && iNewStart ){
144101     sqlite3_stmt *pDel = 0;
144102     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
144103     if( rc==SQLITE_OK ){
144104       sqlite3_bind_int64(pDel, 1, iOldStart);
144105       sqlite3_bind_int64(pDel, 2, iNewStart-1);
144106       sqlite3_step(pDel);
144107       rc = sqlite3_reset(pDel);
144108     }
144109   }
144110 
144111   if( rc==SQLITE_OK ){
144112     sqlite3_stmt *pChomp = 0;
144113     rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
144114     if( rc==SQLITE_OK ){
144115       sqlite3_bind_int64(pChomp, 1, iNewStart);
144116       sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
144117       sqlite3_bind_int64(pChomp, 3, iAbsLevel);
144118       sqlite3_bind_int(pChomp, 4, iIdx);
144119       sqlite3_step(pChomp);
144120       rc = sqlite3_reset(pChomp);
144121     }
144122   }
144123 
144124   sqlite3_free(root.a);
144125   sqlite3_free(block.a);
144126   return rc;
144127 }
144128 
144129 /*
144130 ** This function is called after an incrmental-merge operation has run to
144131 ** merge (or partially merge) two or more segments from absolute level
144132 ** iAbsLevel.
144133 **
144134 ** Each input segment is either removed from the db completely (if all of
144135 ** its data was copied to the output segment by the incrmerge operation)
144136 ** or modified in place so that it no longer contains those entries that
144137 ** have been duplicated in the output segment.
144138 */
144139 static int fts3IncrmergeChomp(
144140   Fts3Table *p,                   /* FTS table handle */
144141   sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
144142   Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
144143   int *pnRem                      /* Number of segments not deleted */
144144 ){
144145   int i;
144146   int nRem = 0;
144147   int rc = SQLITE_OK;
144148 
144149   for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
144150     Fts3SegReader *pSeg = 0;
144151     int j;
144152 
144153     /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
144154     ** somewhere in the pCsr->apSegment[] array.  */
144155     for(j=0; ALWAYS(j<pCsr->nSegment); j++){
144156       pSeg = pCsr->apSegment[j];
144157       if( pSeg->iIdx==i ) break;
144158     }
144159     assert( j<pCsr->nSegment && pSeg->iIdx==i );
144160 
144161     if( pSeg->aNode==0 ){
144162       /* Seg-reader is at EOF. Remove the entire input segment. */
144163       rc = fts3DeleteSegment(p, pSeg);
144164       if( rc==SQLITE_OK ){
144165         rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
144166       }
144167       *pnRem = 0;
144168     }else{
144169       /* The incremental merge did not copy all the data from this
144170       ** segment to the upper level. The segment is modified in place
144171       ** so that it contains no keys smaller than zTerm/nTerm. */
144172       const char *zTerm = pSeg->zTerm;
144173       int nTerm = pSeg->nTerm;
144174       rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
144175       nRem++;
144176     }
144177   }
144178 
144179   if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
144180     rc = fts3RepackSegdirLevel(p, iAbsLevel);
144181   }
144182 
144183   *pnRem = nRem;
144184   return rc;
144185 }
144186 
144187 /*
144188 ** Store an incr-merge hint in the database.
144189 */
144190 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
144191   sqlite3_stmt *pReplace = 0;
144192   int rc;                         /* Return code */
144193 
144194   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
144195   if( rc==SQLITE_OK ){
144196     sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
144197     sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
144198     sqlite3_step(pReplace);
144199     rc = sqlite3_reset(pReplace);
144200   }
144201 
144202   return rc;
144203 }
144204 
144205 /*
144206 ** Load an incr-merge hint from the database. The incr-merge hint, if one
144207 ** exists, is stored in the rowid==1 row of the %_stat table.
144208 **
144209 ** If successful, populate blob *pHint with the value read from the %_stat
144210 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
144211 ** SQLite error code.
144212 */
144213 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
144214   sqlite3_stmt *pSelect = 0;
144215   int rc;
144216 
144217   pHint->n = 0;
144218   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
144219   if( rc==SQLITE_OK ){
144220     int rc2;
144221     sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
144222     if( SQLITE_ROW==sqlite3_step(pSelect) ){
144223       const char *aHint = sqlite3_column_blob(pSelect, 0);
144224       int nHint = sqlite3_column_bytes(pSelect, 0);
144225       if( aHint ){
144226         blobGrowBuffer(pHint, nHint, &rc);
144227         if( rc==SQLITE_OK ){
144228           memcpy(pHint->a, aHint, nHint);
144229           pHint->n = nHint;
144230         }
144231       }
144232     }
144233     rc2 = sqlite3_reset(pSelect);
144234     if( rc==SQLITE_OK ) rc = rc2;
144235   }
144236 
144237   return rc;
144238 }
144239 
144240 /*
144241 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
144242 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
144243 ** consists of two varints, the absolute level number of the input segments
144244 ** and the number of input segments.
144245 **
144246 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
144247 ** set *pRc to an SQLite error code before returning.
144248 */
144249 static void fts3IncrmergeHintPush(
144250   Blob *pHint,                    /* Hint blob to append to */
144251   i64 iAbsLevel,                  /* First varint to store in hint */
144252   int nInput,                     /* Second varint to store in hint */
144253   int *pRc                        /* IN/OUT: Error code */
144254 ){
144255   blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
144256   if( *pRc==SQLITE_OK ){
144257     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
144258     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
144259   }
144260 }
144261 
144262 /*
144263 ** Read the last entry (most recently pushed) from the hint blob *pHint
144264 ** and then remove the entry. Write the two values read to *piAbsLevel and
144265 ** *pnInput before returning.
144266 **
144267 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
144268 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
144269 */
144270 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
144271   const int nHint = pHint->n;
144272   int i;
144273 
144274   i = pHint->n-2;
144275   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
144276   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
144277 
144278   pHint->n = i;
144279   i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
144280   i += fts3GetVarint32(&pHint->a[i], pnInput);
144281   if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
144282 
144283   return SQLITE_OK;
144284 }
144285 
144286 
144287 /*
144288 ** Attempt an incremental merge that writes nMerge leaf blocks.
144289 **
144290 ** Incremental merges happen nMin segments at a time. The segments
144291 ** to be merged are the nMin oldest segments (the ones with the smallest
144292 ** values for the _segdir.idx field) in the highest level that contains
144293 ** at least nMin segments. Multiple merges might occur in an attempt to
144294 ** write the quota of nMerge leaf blocks.
144295 */
144296 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
144297   int rc;                         /* Return code */
144298   int nRem = nMerge;              /* Number of leaf pages yet to  be written */
144299   Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
144300   Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
144301   IncrmergeWriter *pWriter;       /* Writer object */
144302   int nSeg = 0;                   /* Number of input segments */
144303   sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
144304   Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
144305   int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
144306 
144307   /* Allocate space for the cursor, filter and writer objects */
144308   const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
144309   pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
144310   if( !pWriter ) return SQLITE_NOMEM;
144311   pFilter = (Fts3SegFilter *)&pWriter[1];
144312   pCsr = (Fts3MultiSegReader *)&pFilter[1];
144313 
144314   rc = fts3IncrmergeHintLoad(p, &hint);
144315   while( rc==SQLITE_OK && nRem>0 ){
144316     const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
144317     sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
144318     int bUseHint = 0;             /* True if attempting to append */
144319     int iIdx = 0;                 /* Largest idx in level (iAbsLevel+1) */
144320 
144321     /* Search the %_segdir table for the absolute level with the smallest
144322     ** relative level number that contains at least nMin segments, if any.
144323     ** If one is found, set iAbsLevel to the absolute level number and
144324     ** nSeg to nMin. If no level with at least nMin segments can be found,
144325     ** set nSeg to -1.
144326     */
144327     rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
144328     sqlite3_bind_int(pFindLevel, 1, nMin);
144329     if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
144330       iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
144331       nSeg = nMin;
144332     }else{
144333       nSeg = -1;
144334     }
144335     rc = sqlite3_reset(pFindLevel);
144336 
144337     /* If the hint read from the %_stat table is not empty, check if the
144338     ** last entry in it specifies a relative level smaller than or equal
144339     ** to the level identified by the block above (if any). If so, this
144340     ** iteration of the loop will work on merging at the hinted level.
144341     */
144342     if( rc==SQLITE_OK && hint.n ){
144343       int nHint = hint.n;
144344       sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
144345       int nHintSeg = 0;                     /* Hint number of segments */
144346 
144347       rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
144348       if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
144349         iAbsLevel = iHintAbsLevel;
144350         nSeg = nHintSeg;
144351         bUseHint = 1;
144352         bDirtyHint = 1;
144353       }else{
144354         /* This undoes the effect of the HintPop() above - so that no entry
144355         ** is removed from the hint blob.  */
144356         hint.n = nHint;
144357       }
144358     }
144359 
144360     /* If nSeg is less that zero, then there is no level with at least
144361     ** nMin segments and no hint in the %_stat table. No work to do.
144362     ** Exit early in this case.  */
144363     if( nSeg<0 ) break;
144364 
144365     /* Open a cursor to iterate through the contents of the oldest nSeg
144366     ** indexes of absolute level iAbsLevel. If this cursor is opened using
144367     ** the 'hint' parameters, it is possible that there are less than nSeg
144368     ** segments available in level iAbsLevel. In this case, no work is
144369     ** done on iAbsLevel - fall through to the next iteration of the loop
144370     ** to start work on some other level.  */
144371     memset(pWriter, 0, nAlloc);
144372     pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
144373 
144374     if( rc==SQLITE_OK ){
144375       rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
144376       assert( bUseHint==1 || bUseHint==0 );
144377       if( iIdx==0 || (bUseHint && iIdx==1) ){
144378         int bIgnore = 0;
144379         rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
144380         if( bIgnore ){
144381           pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
144382         }
144383       }
144384     }
144385 
144386     if( rc==SQLITE_OK ){
144387       rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
144388     }
144389     if( SQLITE_OK==rc && pCsr->nSegment==nSeg
144390      && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
144391      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
144392     ){
144393       if( bUseHint && iIdx>0 ){
144394         const char *zKey = pCsr->zTerm;
144395         int nKey = pCsr->nTerm;
144396         rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
144397       }else{
144398         rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
144399       }
144400 
144401       if( rc==SQLITE_OK && pWriter->nLeafEst ){
144402         fts3LogMerge(nSeg, iAbsLevel);
144403         do {
144404           rc = fts3IncrmergeAppend(p, pWriter, pCsr);
144405           if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
144406           if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
144407         }while( rc==SQLITE_ROW );
144408 
144409         /* Update or delete the input segments */
144410         if( rc==SQLITE_OK ){
144411           nRem -= (1 + pWriter->nWork);
144412           rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
144413           if( nSeg!=0 ){
144414             bDirtyHint = 1;
144415             fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
144416           }
144417         }
144418       }
144419 
144420       if( nSeg!=0 ){
144421         pWriter->nLeafData = pWriter->nLeafData * -1;
144422       }
144423       fts3IncrmergeRelease(p, pWriter, &rc);
144424       if( nSeg==0 && pWriter->bNoLeafData==0 ){
144425         fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
144426       }
144427     }
144428 
144429     sqlite3Fts3SegReaderFinish(pCsr);
144430   }
144431 
144432   /* Write the hint values into the %_stat table for the next incr-merger */
144433   if( bDirtyHint && rc==SQLITE_OK ){
144434     rc = fts3IncrmergeHintStore(p, &hint);
144435   }
144436 
144437   sqlite3_free(pWriter);
144438   sqlite3_free(hint.a);
144439   return rc;
144440 }
144441 
144442 /*
144443 ** Convert the text beginning at *pz into an integer and return
144444 ** its value.  Advance *pz to point to the first character past
144445 ** the integer.
144446 */
144447 static int fts3Getint(const char **pz){
144448   const char *z = *pz;
144449   int i = 0;
144450   while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
144451   *pz = z;
144452   return i;
144453 }
144454 
144455 /*
144456 ** Process statements of the form:
144457 **
144458 **    INSERT INTO table(table) VALUES('merge=A,B');
144459 **
144460 ** A and B are integers that decode to be the number of leaf pages
144461 ** written for the merge, and the minimum number of segments on a level
144462 ** before it will be selected for a merge, respectively.
144463 */
144464 static int fts3DoIncrmerge(
144465   Fts3Table *p,                   /* FTS3 table handle */
144466   const char *zParam              /* Nul-terminated string containing "A,B" */
144467 ){
144468   int rc;
144469   int nMin = (FTS3_MERGE_COUNT / 2);
144470   int nMerge = 0;
144471   const char *z = zParam;
144472 
144473   /* Read the first integer value */
144474   nMerge = fts3Getint(&z);
144475 
144476   /* If the first integer value is followed by a ',',  read the second
144477   ** integer value. */
144478   if( z[0]==',' && z[1]!='\0' ){
144479     z++;
144480     nMin = fts3Getint(&z);
144481   }
144482 
144483   if( z[0]!='\0' || nMin<2 ){
144484     rc = SQLITE_ERROR;
144485   }else{
144486     rc = SQLITE_OK;
144487     if( !p->bHasStat ){
144488       assert( p->bFts4==0 );
144489       sqlite3Fts3CreateStatTable(&rc, p);
144490     }
144491     if( rc==SQLITE_OK ){
144492       rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
144493     }
144494     sqlite3Fts3SegmentsClose(p);
144495   }
144496   return rc;
144497 }
144498 
144499 /*
144500 ** Process statements of the form:
144501 **
144502 **    INSERT INTO table(table) VALUES('automerge=X');
144503 **
144504 ** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
144505 ** turn it on.  The setting is persistent.
144506 */
144507 static int fts3DoAutoincrmerge(
144508   Fts3Table *p,                   /* FTS3 table handle */
144509   const char *zParam              /* Nul-terminated string containing boolean */
144510 ){
144511   int rc = SQLITE_OK;
144512   sqlite3_stmt *pStmt = 0;
144513   p->nAutoincrmerge = fts3Getint(&zParam);
144514   if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
144515     p->nAutoincrmerge = 8;
144516   }
144517   if( !p->bHasStat ){
144518     assert( p->bFts4==0 );
144519     sqlite3Fts3CreateStatTable(&rc, p);
144520     if( rc ) return rc;
144521   }
144522   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
144523   if( rc ) return rc;
144524   sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
144525   sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
144526   sqlite3_step(pStmt);
144527   rc = sqlite3_reset(pStmt);
144528   return rc;
144529 }
144530 
144531 /*
144532 ** Return a 64-bit checksum for the FTS index entry specified by the
144533 ** arguments to this function.
144534 */
144535 static u64 fts3ChecksumEntry(
144536   const char *zTerm,              /* Pointer to buffer containing term */
144537   int nTerm,                      /* Size of zTerm in bytes */
144538   int iLangid,                    /* Language id for current row */
144539   int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
144540   i64 iDocid,                     /* Docid for current row. */
144541   int iCol,                       /* Column number */
144542   int iPos                        /* Position */
144543 ){
144544   int i;
144545   u64 ret = (u64)iDocid;
144546 
144547   ret += (ret<<3) + iLangid;
144548   ret += (ret<<3) + iIndex;
144549   ret += (ret<<3) + iCol;
144550   ret += (ret<<3) + iPos;
144551   for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
144552 
144553   return ret;
144554 }
144555 
144556 /*
144557 ** Return a checksum of all entries in the FTS index that correspond to
144558 ** language id iLangid. The checksum is calculated by XORing the checksums
144559 ** of each individual entry (see fts3ChecksumEntry()) together.
144560 **
144561 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
144562 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
144563 ** return value is undefined in this case.
144564 */
144565 static u64 fts3ChecksumIndex(
144566   Fts3Table *p,                   /* FTS3 table handle */
144567   int iLangid,                    /* Language id to return cksum for */
144568   int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
144569   int *pRc                        /* OUT: Return code */
144570 ){
144571   Fts3SegFilter filter;
144572   Fts3MultiSegReader csr;
144573   int rc;
144574   u64 cksum = 0;
144575 
144576   assert( *pRc==SQLITE_OK );
144577 
144578   memset(&filter, 0, sizeof(filter));
144579   memset(&csr, 0, sizeof(csr));
144580   filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
144581   filter.flags |= FTS3_SEGMENT_SCAN;
144582 
144583   rc = sqlite3Fts3SegReaderCursor(
144584       p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
144585   );
144586   if( rc==SQLITE_OK ){
144587     rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
144588   }
144589 
144590   if( rc==SQLITE_OK ){
144591     while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
144592       char *pCsr = csr.aDoclist;
144593       char *pEnd = &pCsr[csr.nDoclist];
144594 
144595       i64 iDocid = 0;
144596       i64 iCol = 0;
144597       i64 iPos = 0;
144598 
144599       pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
144600       while( pCsr<pEnd ){
144601         i64 iVal = 0;
144602         pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
144603         if( pCsr<pEnd ){
144604           if( iVal==0 || iVal==1 ){
144605             iCol = 0;
144606             iPos = 0;
144607             if( iVal ){
144608               pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
144609             }else{
144610               pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
144611               iDocid += iVal;
144612             }
144613           }else{
144614             iPos += (iVal - 2);
144615             cksum = cksum ^ fts3ChecksumEntry(
144616                 csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
144617                 (int)iCol, (int)iPos
144618             );
144619           }
144620         }
144621       }
144622     }
144623   }
144624   sqlite3Fts3SegReaderFinish(&csr);
144625 
144626   *pRc = rc;
144627   return cksum;
144628 }
144629 
144630 /*
144631 ** Check if the contents of the FTS index match the current contents of the
144632 ** content table. If no error occurs and the contents do match, set *pbOk
144633 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
144634 ** to false before returning.
144635 **
144636 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
144637 ** code. The final value of *pbOk is undefined in this case.
144638 */
144639 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
144640   int rc = SQLITE_OK;             /* Return code */
144641   u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
144642   u64 cksum2 = 0;                 /* Checksum based on %_content contents */
144643   sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
144644 
144645   /* This block calculates the checksum according to the FTS index. */
144646   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
144647   if( rc==SQLITE_OK ){
144648     int rc2;
144649     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
144650     while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
144651       int iLangid = sqlite3_column_int(pAllLangid, 0);
144652       int i;
144653       for(i=0; i<p->nIndex; i++){
144654         cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
144655       }
144656     }
144657     rc2 = sqlite3_reset(pAllLangid);
144658     if( rc==SQLITE_OK ) rc = rc2;
144659   }
144660 
144661   /* This block calculates the checksum according to the %_content table */
144662   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
144663   if( rc==SQLITE_OK ){
144664     sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
144665     sqlite3_stmt *pStmt = 0;
144666     char *zSql;
144667 
144668     zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
144669     if( !zSql ){
144670       rc = SQLITE_NOMEM;
144671     }else{
144672       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
144673       sqlite3_free(zSql);
144674     }
144675 
144676     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
144677       i64 iDocid = sqlite3_column_int64(pStmt, 0);
144678       int iLang = langidFromSelect(p, pStmt);
144679       int iCol;
144680 
144681       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
144682         if( p->abNotindexed[iCol]==0 ){
144683           const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
144684           int nText = sqlite3_column_bytes(pStmt, iCol+1);
144685           sqlite3_tokenizer_cursor *pT = 0;
144686 
144687           rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
144688           while( rc==SQLITE_OK ){
144689             char const *zToken;       /* Buffer containing token */
144690             int nToken = 0;           /* Number of bytes in token */
144691             int iDum1 = 0, iDum2 = 0; /* Dummy variables */
144692             int iPos = 0;             /* Position of token in zText */
144693 
144694             rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
144695             if( rc==SQLITE_OK ){
144696               int i;
144697               cksum2 = cksum2 ^ fts3ChecksumEntry(
144698                   zToken, nToken, iLang, 0, iDocid, iCol, iPos
144699               );
144700               for(i=1; i<p->nIndex; i++){
144701                 if( p->aIndex[i].nPrefix<=nToken ){
144702                   cksum2 = cksum2 ^ fts3ChecksumEntry(
144703                       zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
144704                   );
144705                 }
144706               }
144707             }
144708           }
144709           if( pT ) pModule->xClose(pT);
144710           if( rc==SQLITE_DONE ) rc = SQLITE_OK;
144711         }
144712       }
144713     }
144714 
144715     sqlite3_finalize(pStmt);
144716   }
144717 
144718   *pbOk = (cksum1==cksum2);
144719   return rc;
144720 }
144721 
144722 /*
144723 ** Run the integrity-check. If no error occurs and the current contents of
144724 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
144725 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
144726 **
144727 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
144728 ** error code.
144729 **
144730 ** The integrity-check works as follows. For each token and indexed token
144731 ** prefix in the document set, a 64-bit checksum is calculated (by code
144732 ** in fts3ChecksumEntry()) based on the following:
144733 **
144734 **     + The index number (0 for the main index, 1 for the first prefix
144735 **       index etc.),
144736 **     + The token (or token prefix) text itself,
144737 **     + The language-id of the row it appears in,
144738 **     + The docid of the row it appears in,
144739 **     + The column it appears in, and
144740 **     + The tokens position within that column.
144741 **
144742 ** The checksums for all entries in the index are XORed together to create
144743 ** a single checksum for the entire index.
144744 **
144745 ** The integrity-check code calculates the same checksum in two ways:
144746 **
144747 **     1. By scanning the contents of the FTS index, and
144748 **     2. By scanning and tokenizing the content table.
144749 **
144750 ** If the two checksums are identical, the integrity-check is deemed to have
144751 ** passed.
144752 */
144753 static int fts3DoIntegrityCheck(
144754   Fts3Table *p                    /* FTS3 table handle */
144755 ){
144756   int rc;
144757   int bOk = 0;
144758   rc = fts3IntegrityCheck(p, &bOk);
144759   if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
144760   return rc;
144761 }
144762 
144763 /*
144764 ** Handle a 'special' INSERT of the form:
144765 **
144766 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
144767 **
144768 ** Argument pVal contains the result of <expr>. Currently the only
144769 ** meaningful value to insert is the text 'optimize'.
144770 */
144771 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
144772   int rc;                         /* Return Code */
144773   const char *zVal = (const char *)sqlite3_value_text(pVal);
144774   int nVal = sqlite3_value_bytes(pVal);
144775 
144776   if( !zVal ){
144777     return SQLITE_NOMEM;
144778   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
144779     rc = fts3DoOptimize(p, 0);
144780   }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
144781     rc = fts3DoRebuild(p);
144782   }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
144783     rc = fts3DoIntegrityCheck(p);
144784   }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
144785     rc = fts3DoIncrmerge(p, &zVal[6]);
144786   }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
144787     rc = fts3DoAutoincrmerge(p, &zVal[10]);
144788 #ifdef SQLITE_TEST
144789   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
144790     p->nNodeSize = atoi(&zVal[9]);
144791     rc = SQLITE_OK;
144792   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
144793     p->nMaxPendingData = atoi(&zVal[11]);
144794     rc = SQLITE_OK;
144795   }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
144796     p->bNoIncrDoclist = atoi(&zVal[21]);
144797     rc = SQLITE_OK;
144798 #endif
144799   }else{
144800     rc = SQLITE_ERROR;
144801   }
144802 
144803   return rc;
144804 }
144805 
144806 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
144807 /*
144808 ** Delete all cached deferred doclists. Deferred doclists are cached
144809 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
144810 */
144811 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
144812   Fts3DeferredToken *pDef;
144813   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
144814     fts3PendingListDelete(pDef->pList);
144815     pDef->pList = 0;
144816   }
144817 }
144818 
144819 /*
144820 ** Free all entries in the pCsr->pDeffered list. Entries are added to
144821 ** this list using sqlite3Fts3DeferToken().
144822 */
144823 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
144824   Fts3DeferredToken *pDef;
144825   Fts3DeferredToken *pNext;
144826   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
144827     pNext = pDef->pNext;
144828     fts3PendingListDelete(pDef->pList);
144829     sqlite3_free(pDef);
144830   }
144831   pCsr->pDeferred = 0;
144832 }
144833 
144834 /*
144835 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
144836 ** based on the row that pCsr currently points to.
144837 **
144838 ** A deferred-doclist is like any other doclist with position information
144839 ** included, except that it only contains entries for a single row of the
144840 ** table, not for all rows.
144841 */
144842 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
144843   int rc = SQLITE_OK;             /* Return code */
144844   if( pCsr->pDeferred ){
144845     int i;                        /* Used to iterate through table columns */
144846     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
144847     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
144848 
144849     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
144850     sqlite3_tokenizer *pT = p->pTokenizer;
144851     sqlite3_tokenizer_module const *pModule = pT->pModule;
144852 
144853     assert( pCsr->isRequireSeek==0 );
144854     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
144855 
144856     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
144857       if( p->abNotindexed[i]==0 ){
144858         const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
144859         sqlite3_tokenizer_cursor *pTC = 0;
144860 
144861         rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
144862         while( rc==SQLITE_OK ){
144863           char const *zToken;       /* Buffer containing token */
144864           int nToken = 0;           /* Number of bytes in token */
144865           int iDum1 = 0, iDum2 = 0; /* Dummy variables */
144866           int iPos = 0;             /* Position of token in zText */
144867 
144868           rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
144869           for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
144870             Fts3PhraseToken *pPT = pDef->pToken;
144871             if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
144872                 && (pPT->bFirst==0 || iPos==0)
144873                 && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
144874                 && (0==memcmp(zToken, pPT->z, pPT->n))
144875               ){
144876               fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
144877             }
144878           }
144879         }
144880         if( pTC ) pModule->xClose(pTC);
144881         if( rc==SQLITE_DONE ) rc = SQLITE_OK;
144882       }
144883     }
144884 
144885     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
144886       if( pDef->pList ){
144887         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
144888       }
144889     }
144890   }
144891 
144892   return rc;
144893 }
144894 
144895 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
144896   Fts3DeferredToken *p,
144897   char **ppData,
144898   int *pnData
144899 ){
144900   char *pRet;
144901   int nSkip;
144902   sqlite3_int64 dummy;
144903 
144904   *ppData = 0;
144905   *pnData = 0;
144906 
144907   if( p->pList==0 ){
144908     return SQLITE_OK;
144909   }
144910 
144911   pRet = (char *)sqlite3_malloc(p->pList->nData);
144912   if( !pRet ) return SQLITE_NOMEM;
144913 
144914   nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
144915   *pnData = p->pList->nData - nSkip;
144916   *ppData = pRet;
144917 
144918   memcpy(pRet, &p->pList->aData[nSkip], *pnData);
144919   return SQLITE_OK;
144920 }
144921 
144922 /*
144923 ** Add an entry for token pToken to the pCsr->pDeferred list.
144924 */
144925 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
144926   Fts3Cursor *pCsr,               /* Fts3 table cursor */
144927   Fts3PhraseToken *pToken,        /* Token to defer */
144928   int iCol                        /* Column that token must appear in (or -1) */
144929 ){
144930   Fts3DeferredToken *pDeferred;
144931   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
144932   if( !pDeferred ){
144933     return SQLITE_NOMEM;
144934   }
144935   memset(pDeferred, 0, sizeof(*pDeferred));
144936   pDeferred->pToken = pToken;
144937   pDeferred->pNext = pCsr->pDeferred;
144938   pDeferred->iCol = iCol;
144939   pCsr->pDeferred = pDeferred;
144940 
144941   assert( pToken->pDeferred==0 );
144942   pToken->pDeferred = pDeferred;
144943 
144944   return SQLITE_OK;
144945 }
144946 #endif
144947 
144948 /*
144949 ** SQLite value pRowid contains the rowid of a row that may or may not be
144950 ** present in the FTS3 table. If it is, delete it and adjust the contents
144951 ** of subsiduary data structures accordingly.
144952 */
144953 static int fts3DeleteByRowid(
144954   Fts3Table *p,
144955   sqlite3_value *pRowid,
144956   int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
144957   u32 *aSzDel
144958 ){
144959   int rc = SQLITE_OK;             /* Return code */
144960   int bFound = 0;                 /* True if *pRowid really is in the table */
144961 
144962   fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
144963   if( bFound && rc==SQLITE_OK ){
144964     int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
144965     rc = fts3IsEmpty(p, pRowid, &isEmpty);
144966     if( rc==SQLITE_OK ){
144967       if( isEmpty ){
144968         /* Deleting this row means the whole table is empty. In this case
144969         ** delete the contents of all three tables and throw away any
144970         ** data in the pendingTerms hash table.  */
144971         rc = fts3DeleteAll(p, 1);
144972         *pnChng = 0;
144973         memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
144974       }else{
144975         *pnChng = *pnChng - 1;
144976         if( p->zContentTbl==0 ){
144977           fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
144978         }
144979         if( p->bHasDocsize ){
144980           fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
144981         }
144982       }
144983     }
144984   }
144985 
144986   return rc;
144987 }
144988 
144989 /*
144990 ** This function does the work for the xUpdate method of FTS3 virtual
144991 ** tables. The schema of the virtual table being:
144992 **
144993 **     CREATE TABLE <table name>(
144994 **       <user columns>,
144995 **       <table name> HIDDEN,
144996 **       docid HIDDEN,
144997 **       <langid> HIDDEN
144998 **     );
144999 **
145000 **
145001 */
145002 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
145003   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
145004   int nArg,                       /* Size of argument array */
145005   sqlite3_value **apVal,          /* Array of arguments */
145006   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
145007 ){
145008   Fts3Table *p = (Fts3Table *)pVtab;
145009   int rc = SQLITE_OK;             /* Return Code */
145010   int isRemove = 0;               /* True for an UPDATE or DELETE */
145011   u32 *aSzIns = 0;                /* Sizes of inserted documents */
145012   u32 *aSzDel = 0;                /* Sizes of deleted documents */
145013   int nChng = 0;                  /* Net change in number of documents */
145014   int bInsertDone = 0;
145015 
145016   /* At this point it must be known if the %_stat table exists or not.
145017   ** So bHasStat may not be 2.  */
145018   assert( p->bHasStat==0 || p->bHasStat==1 );
145019 
145020   assert( p->pSegments==0 );
145021   assert(
145022       nArg==1                     /* DELETE operations */
145023    || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
145024   );
145025 
145026   /* Check for a "special" INSERT operation. One of the form:
145027   **
145028   **   INSERT INTO xyz(xyz) VALUES('command');
145029   */
145030   if( nArg>1
145031    && sqlite3_value_type(apVal[0])==SQLITE_NULL
145032    && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
145033   ){
145034     rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
145035     goto update_out;
145036   }
145037 
145038   if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
145039     rc = SQLITE_CONSTRAINT;
145040     goto update_out;
145041   }
145042 
145043   /* Allocate space to hold the change in document sizes */
145044   aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
145045   if( aSzDel==0 ){
145046     rc = SQLITE_NOMEM;
145047     goto update_out;
145048   }
145049   aSzIns = &aSzDel[p->nColumn+1];
145050   memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
145051 
145052   rc = fts3Writelock(p);
145053   if( rc!=SQLITE_OK ) goto update_out;
145054 
145055   /* If this is an INSERT operation, or an UPDATE that modifies the rowid
145056   ** value, then this operation requires constraint handling.
145057   **
145058   ** If the on-conflict mode is REPLACE, this means that the existing row
145059   ** should be deleted from the database before inserting the new row. Or,
145060   ** if the on-conflict mode is other than REPLACE, then this method must
145061   ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
145062   ** modify the database file.
145063   */
145064   if( nArg>1 && p->zContentTbl==0 ){
145065     /* Find the value object that holds the new rowid value. */
145066     sqlite3_value *pNewRowid = apVal[3+p->nColumn];
145067     if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
145068       pNewRowid = apVal[1];
145069     }
145070 
145071     if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
145072         sqlite3_value_type(apVal[0])==SQLITE_NULL
145073      || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
145074     )){
145075       /* The new rowid is not NULL (in this case the rowid will be
145076       ** automatically assigned and there is no chance of a conflict), and
145077       ** the statement is either an INSERT or an UPDATE that modifies the
145078       ** rowid column. So if the conflict mode is REPLACE, then delete any
145079       ** existing row with rowid=pNewRowid.
145080       **
145081       ** Or, if the conflict mode is not REPLACE, insert the new record into
145082       ** the %_content table. If we hit the duplicate rowid constraint (or any
145083       ** other error) while doing so, return immediately.
145084       **
145085       ** This branch may also run if pNewRowid contains a value that cannot
145086       ** be losslessly converted to an integer. In this case, the eventual
145087       ** call to fts3InsertData() (either just below or further on in this
145088       ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
145089       ** invoked, it will delete zero rows (since no row will have
145090       ** docid=$pNewRowid if $pNewRowid is not an integer value).
145091       */
145092       if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
145093         rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
145094       }else{
145095         rc = fts3InsertData(p, apVal, pRowid);
145096         bInsertDone = 1;
145097       }
145098     }
145099   }
145100   if( rc!=SQLITE_OK ){
145101     goto update_out;
145102   }
145103 
145104   /* If this is a DELETE or UPDATE operation, remove the old record. */
145105   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
145106     assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
145107     rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
145108     isRemove = 1;
145109   }
145110 
145111   /* If this is an INSERT or UPDATE operation, insert the new record. */
145112   if( nArg>1 && rc==SQLITE_OK ){
145113     int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
145114     if( bInsertDone==0 ){
145115       rc = fts3InsertData(p, apVal, pRowid);
145116       if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
145117         rc = FTS_CORRUPT_VTAB;
145118       }
145119     }
145120     if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
145121       rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
145122     }
145123     if( rc==SQLITE_OK ){
145124       assert( p->iPrevDocid==*pRowid );
145125       rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
145126     }
145127     if( p->bHasDocsize ){
145128       fts3InsertDocsize(&rc, p, aSzIns);
145129     }
145130     nChng++;
145131   }
145132 
145133   if( p->bFts4 ){
145134     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
145135   }
145136 
145137  update_out:
145138   sqlite3_free(aSzDel);
145139   sqlite3Fts3SegmentsClose(p);
145140   return rc;
145141 }
145142 
145143 /*
145144 ** Flush any data in the pending-terms hash table to disk. If successful,
145145 ** merge all segments in the database (including the new segment, if
145146 ** there was any data to flush) into a single segment.
145147 */
145148 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
145149   int rc;
145150   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
145151   if( rc==SQLITE_OK ){
145152     rc = fts3DoOptimize(p, 1);
145153     if( rc==SQLITE_OK || rc==SQLITE_DONE ){
145154       int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
145155       if( rc2!=SQLITE_OK ) rc = rc2;
145156     }else{
145157       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
145158       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
145159     }
145160   }
145161   sqlite3Fts3SegmentsClose(p);
145162   return rc;
145163 }
145164 
145165 #endif
145166 
145167 /************** End of fts3_write.c ******************************************/
145168 /************** Begin file fts3_snippet.c ************************************/
145169 /*
145170 ** 2009 Oct 23
145171 **
145172 ** The author disclaims copyright to this source code.  In place of
145173 ** a legal notice, here is a blessing:
145174 **
145175 **    May you do good and not evil.
145176 **    May you find forgiveness for yourself and forgive others.
145177 **    May you share freely, never taking more than you give.
145178 **
145179 ******************************************************************************
145180 */
145181 
145182 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
145183 
145184 /* #include <string.h> */
145185 /* #include <assert.h> */
145186 
145187 /*
145188 ** Characters that may appear in the second argument to matchinfo().
145189 */
145190 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
145191 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
145192 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
145193 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
145194 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
145195 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
145196 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
145197 
145198 /*
145199 ** The default value for the second argument to matchinfo().
145200 */
145201 #define FTS3_MATCHINFO_DEFAULT   "pcx"
145202 
145203 
145204 /*
145205 ** Used as an fts3ExprIterate() context when loading phrase doclists to
145206 ** Fts3Expr.aDoclist[]/nDoclist.
145207 */
145208 typedef struct LoadDoclistCtx LoadDoclistCtx;
145209 struct LoadDoclistCtx {
145210   Fts3Cursor *pCsr;               /* FTS3 Cursor */
145211   int nPhrase;                    /* Number of phrases seen so far */
145212   int nToken;                     /* Number of tokens seen so far */
145213 };
145214 
145215 /*
145216 ** The following types are used as part of the implementation of the
145217 ** fts3BestSnippet() routine.
145218 */
145219 typedef struct SnippetIter SnippetIter;
145220 typedef struct SnippetPhrase SnippetPhrase;
145221 typedef struct SnippetFragment SnippetFragment;
145222 
145223 struct SnippetIter {
145224   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
145225   int iCol;                       /* Extract snippet from this column */
145226   int nSnippet;                   /* Requested snippet length (in tokens) */
145227   int nPhrase;                    /* Number of phrases in query */
145228   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
145229   int iCurrent;                   /* First token of current snippet */
145230 };
145231 
145232 struct SnippetPhrase {
145233   int nToken;                     /* Number of tokens in phrase */
145234   char *pList;                    /* Pointer to start of phrase position list */
145235   int iHead;                      /* Next value in position list */
145236   char *pHead;                    /* Position list data following iHead */
145237   int iTail;                      /* Next value in trailing position list */
145238   char *pTail;                    /* Position list data following iTail */
145239 };
145240 
145241 struct SnippetFragment {
145242   int iCol;                       /* Column snippet is extracted from */
145243   int iPos;                       /* Index of first token in snippet */
145244   u64 covered;                    /* Mask of query phrases covered */
145245   u64 hlmask;                     /* Mask of snippet terms to highlight */
145246 };
145247 
145248 /*
145249 ** This type is used as an fts3ExprIterate() context object while
145250 ** accumulating the data returned by the matchinfo() function.
145251 */
145252 typedef struct MatchInfo MatchInfo;
145253 struct MatchInfo {
145254   Fts3Cursor *pCursor;            /* FTS3 Cursor */
145255   int nCol;                       /* Number of columns in table */
145256   int nPhrase;                    /* Number of matchable phrases in query */
145257   sqlite3_int64 nDoc;             /* Number of docs in database */
145258   u32 *aMatchinfo;                /* Pre-allocated buffer */
145259 };
145260 
145261 
145262 
145263 /*
145264 ** The snippet() and offsets() functions both return text values. An instance
145265 ** of the following structure is used to accumulate those values while the
145266 ** functions are running. See fts3StringAppend() for details.
145267 */
145268 typedef struct StrBuffer StrBuffer;
145269 struct StrBuffer {
145270   char *z;                        /* Pointer to buffer containing string */
145271   int n;                          /* Length of z in bytes (excl. nul-term) */
145272   int nAlloc;                     /* Allocated size of buffer z in bytes */
145273 };
145274 
145275 
145276 /*
145277 ** This function is used to help iterate through a position-list. A position
145278 ** list is a list of unique integers, sorted from smallest to largest. Each
145279 ** element of the list is represented by an FTS3 varint that takes the value
145280 ** of the difference between the current element and the previous one plus
145281 ** two. For example, to store the position-list:
145282 **
145283 **     4 9 113
145284 **
145285 ** the three varints:
145286 **
145287 **     6 7 106
145288 **
145289 ** are encoded.
145290 **
145291 ** When this function is called, *pp points to the start of an element of
145292 ** the list. *piPos contains the value of the previous entry in the list.
145293 ** After it returns, *piPos contains the value of the next element of the
145294 ** list and *pp is advanced to the following varint.
145295 */
145296 static void fts3GetDeltaPosition(char **pp, int *piPos){
145297   int iVal;
145298   *pp += fts3GetVarint32(*pp, &iVal);
145299   *piPos += (iVal-2);
145300 }
145301 
145302 /*
145303 ** Helper function for fts3ExprIterate() (see below).
145304 */
145305 static int fts3ExprIterate2(
145306   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
145307   int *piPhrase,                  /* Pointer to phrase counter */
145308   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
145309   void *pCtx                      /* Second argument to pass to callback */
145310 ){
145311   int rc;                         /* Return code */
145312   int eType = pExpr->eType;       /* Type of expression node pExpr */
145313 
145314   if( eType!=FTSQUERY_PHRASE ){
145315     assert( pExpr->pLeft && pExpr->pRight );
145316     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
145317     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
145318       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
145319     }
145320   }else{
145321     rc = x(pExpr, *piPhrase, pCtx);
145322     (*piPhrase)++;
145323   }
145324   return rc;
145325 }
145326 
145327 /*
145328 ** Iterate through all phrase nodes in an FTS3 query, except those that
145329 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
145330 ** For each phrase node found, the supplied callback function is invoked.
145331 **
145332 ** If the callback function returns anything other than SQLITE_OK,
145333 ** the iteration is abandoned and the error code returned immediately.
145334 ** Otherwise, SQLITE_OK is returned after a callback has been made for
145335 ** all eligible phrase nodes.
145336 */
145337 static int fts3ExprIterate(
145338   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
145339   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
145340   void *pCtx                      /* Second argument to pass to callback */
145341 ){
145342   int iPhrase = 0;                /* Variable used as the phrase counter */
145343   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
145344 }
145345 
145346 /*
145347 ** This is an fts3ExprIterate() callback used while loading the doclists
145348 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
145349 ** fts3ExprLoadDoclists().
145350 */
145351 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
145352   int rc = SQLITE_OK;
145353   Fts3Phrase *pPhrase = pExpr->pPhrase;
145354   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
145355 
145356   UNUSED_PARAMETER(iPhrase);
145357 
145358   p->nPhrase++;
145359   p->nToken += pPhrase->nToken;
145360 
145361   return rc;
145362 }
145363 
145364 /*
145365 ** Load the doclists for each phrase in the query associated with FTS3 cursor
145366 ** pCsr.
145367 **
145368 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
145369 ** phrases in the expression (all phrases except those directly or
145370 ** indirectly descended from the right-hand-side of a NOT operator). If
145371 ** pnToken is not NULL, then it is set to the number of tokens in all
145372 ** matchable phrases of the expression.
145373 */
145374 static int fts3ExprLoadDoclists(
145375   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
145376   int *pnPhrase,                  /* OUT: Number of phrases in query */
145377   int *pnToken                    /* OUT: Number of tokens in query */
145378 ){
145379   int rc;                         /* Return Code */
145380   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
145381   sCtx.pCsr = pCsr;
145382   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
145383   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
145384   if( pnToken ) *pnToken = sCtx.nToken;
145385   return rc;
145386 }
145387 
145388 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
145389   (*(int *)ctx)++;
145390   UNUSED_PARAMETER(pExpr);
145391   UNUSED_PARAMETER(iPhrase);
145392   return SQLITE_OK;
145393 }
145394 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
145395   int nPhrase = 0;
145396   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
145397   return nPhrase;
145398 }
145399 
145400 /*
145401 ** Advance the position list iterator specified by the first two
145402 ** arguments so that it points to the first element with a value greater
145403 ** than or equal to parameter iNext.
145404 */
145405 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
145406   char *pIter = *ppIter;
145407   if( pIter ){
145408     int iIter = *piIter;
145409 
145410     while( iIter<iNext ){
145411       if( 0==(*pIter & 0xFE) ){
145412         iIter = -1;
145413         pIter = 0;
145414         break;
145415       }
145416       fts3GetDeltaPosition(&pIter, &iIter);
145417     }
145418 
145419     *piIter = iIter;
145420     *ppIter = pIter;
145421   }
145422 }
145423 
145424 /*
145425 ** Advance the snippet iterator to the next candidate snippet.
145426 */
145427 static int fts3SnippetNextCandidate(SnippetIter *pIter){
145428   int i;                          /* Loop counter */
145429 
145430   if( pIter->iCurrent<0 ){
145431     /* The SnippetIter object has just been initialized. The first snippet
145432     ** candidate always starts at offset 0 (even if this candidate has a
145433     ** score of 0.0).
145434     */
145435     pIter->iCurrent = 0;
145436 
145437     /* Advance the 'head' iterator of each phrase to the first offset that
145438     ** is greater than or equal to (iNext+nSnippet).
145439     */
145440     for(i=0; i<pIter->nPhrase; i++){
145441       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
145442       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
145443     }
145444   }else{
145445     int iStart;
145446     int iEnd = 0x7FFFFFFF;
145447 
145448     for(i=0; i<pIter->nPhrase; i++){
145449       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
145450       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
145451         iEnd = pPhrase->iHead;
145452       }
145453     }
145454     if( iEnd==0x7FFFFFFF ){
145455       return 1;
145456     }
145457 
145458     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
145459     for(i=0; i<pIter->nPhrase; i++){
145460       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
145461       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
145462       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
145463     }
145464   }
145465 
145466   return 0;
145467 }
145468 
145469 /*
145470 ** Retrieve information about the current candidate snippet of snippet
145471 ** iterator pIter.
145472 */
145473 static void fts3SnippetDetails(
145474   SnippetIter *pIter,             /* Snippet iterator */
145475   u64 mCovered,                   /* Bitmask of phrases already covered */
145476   int *piToken,                   /* OUT: First token of proposed snippet */
145477   int *piScore,                   /* OUT: "Score" for this snippet */
145478   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
145479   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
145480 ){
145481   int iStart = pIter->iCurrent;   /* First token of snippet */
145482   int iScore = 0;                 /* Score of this snippet */
145483   int i;                          /* Loop counter */
145484   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
145485   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
145486 
145487   for(i=0; i<pIter->nPhrase; i++){
145488     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
145489     if( pPhrase->pTail ){
145490       char *pCsr = pPhrase->pTail;
145491       int iCsr = pPhrase->iTail;
145492 
145493       while( iCsr<(iStart+pIter->nSnippet) ){
145494         int j;
145495         u64 mPhrase = (u64)1 << i;
145496         u64 mPos = (u64)1 << (iCsr - iStart);
145497         assert( iCsr>=iStart );
145498         if( (mCover|mCovered)&mPhrase ){
145499           iScore++;
145500         }else{
145501           iScore += 1000;
145502         }
145503         mCover |= mPhrase;
145504 
145505         for(j=0; j<pPhrase->nToken; j++){
145506           mHighlight |= (mPos>>j);
145507         }
145508 
145509         if( 0==(*pCsr & 0x0FE) ) break;
145510         fts3GetDeltaPosition(&pCsr, &iCsr);
145511       }
145512     }
145513   }
145514 
145515   /* Set the output variables before returning. */
145516   *piToken = iStart;
145517   *piScore = iScore;
145518   *pmCover = mCover;
145519   *pmHighlight = mHighlight;
145520 }
145521 
145522 /*
145523 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
145524 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
145525 */
145526 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
145527   SnippetIter *p = (SnippetIter *)ctx;
145528   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
145529   char *pCsr;
145530   int rc;
145531 
145532   pPhrase->nToken = pExpr->pPhrase->nToken;
145533   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
145534   assert( rc==SQLITE_OK || pCsr==0 );
145535   if( pCsr ){
145536     int iFirst = 0;
145537     pPhrase->pList = pCsr;
145538     fts3GetDeltaPosition(&pCsr, &iFirst);
145539     assert( iFirst>=0 );
145540     pPhrase->pHead = pCsr;
145541     pPhrase->pTail = pCsr;
145542     pPhrase->iHead = iFirst;
145543     pPhrase->iTail = iFirst;
145544   }else{
145545     assert( rc!=SQLITE_OK || (
145546        pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
145547     ));
145548   }
145549 
145550   return rc;
145551 }
145552 
145553 /*
145554 ** Select the fragment of text consisting of nFragment contiguous tokens
145555 ** from column iCol that represent the "best" snippet. The best snippet
145556 ** is the snippet with the highest score, where scores are calculated
145557 ** by adding:
145558 **
145559 **   (a) +1 point for each occurrence of a matchable phrase in the snippet.
145560 **
145561 **   (b) +1000 points for the first occurrence of each matchable phrase in
145562 **       the snippet for which the corresponding mCovered bit is not set.
145563 **
145564 ** The selected snippet parameters are stored in structure *pFragment before
145565 ** returning. The score of the selected snippet is stored in *piScore
145566 ** before returning.
145567 */
145568 static int fts3BestSnippet(
145569   int nSnippet,                   /* Desired snippet length */
145570   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
145571   int iCol,                       /* Index of column to create snippet from */
145572   u64 mCovered,                   /* Mask of phrases already covered */
145573   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
145574   SnippetFragment *pFragment,     /* OUT: Best snippet found */
145575   int *piScore                    /* OUT: Score of snippet pFragment */
145576 ){
145577   int rc;                         /* Return Code */
145578   int nList;                      /* Number of phrases in expression */
145579   SnippetIter sIter;              /* Iterates through snippet candidates */
145580   int nByte;                      /* Number of bytes of space to allocate */
145581   int iBestScore = -1;            /* Best snippet score found so far */
145582   int i;                          /* Loop counter */
145583 
145584   memset(&sIter, 0, sizeof(sIter));
145585 
145586   /* Iterate through the phrases in the expression to count them. The same
145587   ** callback makes sure the doclists are loaded for each phrase.
145588   */
145589   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
145590   if( rc!=SQLITE_OK ){
145591     return rc;
145592   }
145593 
145594   /* Now that it is known how many phrases there are, allocate and zero
145595   ** the required space using malloc().
145596   */
145597   nByte = sizeof(SnippetPhrase) * nList;
145598   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
145599   if( !sIter.aPhrase ){
145600     return SQLITE_NOMEM;
145601   }
145602   memset(sIter.aPhrase, 0, nByte);
145603 
145604   /* Initialize the contents of the SnippetIter object. Then iterate through
145605   ** the set of phrases in the expression to populate the aPhrase[] array.
145606   */
145607   sIter.pCsr = pCsr;
145608   sIter.iCol = iCol;
145609   sIter.nSnippet = nSnippet;
145610   sIter.nPhrase = nList;
145611   sIter.iCurrent = -1;
145612   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
145613 
145614   /* Set the *pmSeen output variable. */
145615   for(i=0; i<nList; i++){
145616     if( sIter.aPhrase[i].pHead ){
145617       *pmSeen |= (u64)1 << i;
145618     }
145619   }
145620 
145621   /* Loop through all candidate snippets. Store the best snippet in
145622   ** *pFragment. Store its associated 'score' in iBestScore.
145623   */
145624   pFragment->iCol = iCol;
145625   while( !fts3SnippetNextCandidate(&sIter) ){
145626     int iPos;
145627     int iScore;
145628     u64 mCover;
145629     u64 mHighlight;
145630     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
145631     assert( iScore>=0 );
145632     if( iScore>iBestScore ){
145633       pFragment->iPos = iPos;
145634       pFragment->hlmask = mHighlight;
145635       pFragment->covered = mCover;
145636       iBestScore = iScore;
145637     }
145638   }
145639 
145640   sqlite3_free(sIter.aPhrase);
145641   *piScore = iBestScore;
145642   return SQLITE_OK;
145643 }
145644 
145645 
145646 /*
145647 ** Append a string to the string-buffer passed as the first argument.
145648 **
145649 ** If nAppend is negative, then the length of the string zAppend is
145650 ** determined using strlen().
145651 */
145652 static int fts3StringAppend(
145653   StrBuffer *pStr,                /* Buffer to append to */
145654   const char *zAppend,            /* Pointer to data to append to buffer */
145655   int nAppend                     /* Size of zAppend in bytes (or -1) */
145656 ){
145657   if( nAppend<0 ){
145658     nAppend = (int)strlen(zAppend);
145659   }
145660 
145661   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
145662   ** to grow the buffer until so that it is big enough to accomadate the
145663   ** appended data.
145664   */
145665   if( pStr->n+nAppend+1>=pStr->nAlloc ){
145666     int nAlloc = pStr->nAlloc+nAppend+100;
145667     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
145668     if( !zNew ){
145669       return SQLITE_NOMEM;
145670     }
145671     pStr->z = zNew;
145672     pStr->nAlloc = nAlloc;
145673   }
145674   assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
145675 
145676   /* Append the data to the string buffer. */
145677   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
145678   pStr->n += nAppend;
145679   pStr->z[pStr->n] = '\0';
145680 
145681   return SQLITE_OK;
145682 }
145683 
145684 /*
145685 ** The fts3BestSnippet() function often selects snippets that end with a
145686 ** query term. That is, the final term of the snippet is always a term
145687 ** that requires highlighting. For example, if 'X' is a highlighted term
145688 ** and '.' is a non-highlighted term, BestSnippet() may select:
145689 **
145690 **     ........X.....X
145691 **
145692 ** This function "shifts" the beginning of the snippet forward in the
145693 ** document so that there are approximately the same number of
145694 ** non-highlighted terms to the right of the final highlighted term as there
145695 ** are to the left of the first highlighted term. For example, to this:
145696 **
145697 **     ....X.....X....
145698 **
145699 ** This is done as part of extracting the snippet text, not when selecting
145700 ** the snippet. Snippet selection is done based on doclists only, so there
145701 ** is no way for fts3BestSnippet() to know whether or not the document
145702 ** actually contains terms that follow the final highlighted term.
145703 */
145704 static int fts3SnippetShift(
145705   Fts3Table *pTab,                /* FTS3 table snippet comes from */
145706   int iLangid,                    /* Language id to use in tokenizing */
145707   int nSnippet,                   /* Number of tokens desired for snippet */
145708   const char *zDoc,               /* Document text to extract snippet from */
145709   int nDoc,                       /* Size of buffer zDoc in bytes */
145710   int *piPos,                     /* IN/OUT: First token of snippet */
145711   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
145712 ){
145713   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
145714 
145715   if( hlmask ){
145716     int nLeft;                    /* Tokens to the left of first highlight */
145717     int nRight;                   /* Tokens to the right of last highlight */
145718     int nDesired;                 /* Ideal number of tokens to shift forward */
145719 
145720     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
145721     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
145722     nDesired = (nLeft-nRight)/2;
145723 
145724     /* Ideally, the start of the snippet should be pushed forward in the
145725     ** document nDesired tokens. This block checks if there are actually
145726     ** nDesired tokens to the right of the snippet. If so, *piPos and
145727     ** *pHlMask are updated to shift the snippet nDesired tokens to the
145728     ** right. Otherwise, the snippet is shifted by the number of tokens
145729     ** available.
145730     */
145731     if( nDesired>0 ){
145732       int nShift;                 /* Number of tokens to shift snippet by */
145733       int iCurrent = 0;           /* Token counter */
145734       int rc;                     /* Return Code */
145735       sqlite3_tokenizer_module *pMod;
145736       sqlite3_tokenizer_cursor *pC;
145737       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
145738 
145739       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
145740       ** or more tokens in zDoc/nDoc.
145741       */
145742       rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
145743       if( rc!=SQLITE_OK ){
145744         return rc;
145745       }
145746       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
145747         const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
145748         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
145749       }
145750       pMod->xClose(pC);
145751       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
145752 
145753       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
145754       assert( nShift<=nDesired );
145755       if( nShift>0 ){
145756         *piPos += nShift;
145757         *pHlmask = hlmask >> nShift;
145758       }
145759     }
145760   }
145761   return SQLITE_OK;
145762 }
145763 
145764 /*
145765 ** Extract the snippet text for fragment pFragment from cursor pCsr and
145766 ** append it to string buffer pOut.
145767 */
145768 static int fts3SnippetText(
145769   Fts3Cursor *pCsr,               /* FTS3 Cursor */
145770   SnippetFragment *pFragment,     /* Snippet to extract */
145771   int iFragment,                  /* Fragment number */
145772   int isLast,                     /* True for final fragment in snippet */
145773   int nSnippet,                   /* Number of tokens in extracted snippet */
145774   const char *zOpen,              /* String inserted before highlighted term */
145775   const char *zClose,             /* String inserted after highlighted term */
145776   const char *zEllipsis,          /* String inserted between snippets */
145777   StrBuffer *pOut                 /* Write output here */
145778 ){
145779   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
145780   int rc;                         /* Return code */
145781   const char *zDoc;               /* Document text to extract snippet from */
145782   int nDoc;                       /* Size of zDoc in bytes */
145783   int iCurrent = 0;               /* Current token number of document */
145784   int iEnd = 0;                   /* Byte offset of end of current token */
145785   int isShiftDone = 0;            /* True after snippet is shifted */
145786   int iPos = pFragment->iPos;     /* First token of snippet */
145787   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
145788   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
145789   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
145790   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
145791 
145792   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
145793   if( zDoc==0 ){
145794     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
145795       return SQLITE_NOMEM;
145796     }
145797     return SQLITE_OK;
145798   }
145799   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
145800 
145801   /* Open a token cursor on the document. */
145802   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
145803   rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
145804   if( rc!=SQLITE_OK ){
145805     return rc;
145806   }
145807 
145808   while( rc==SQLITE_OK ){
145809     const char *ZDUMMY;           /* Dummy argument used with tokenizer */
145810     int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
145811     int iBegin = 0;               /* Offset in zDoc of start of token */
145812     int iFin = 0;                 /* Offset in zDoc of end of token */
145813     int isHighlight = 0;          /* True for highlighted terms */
145814 
145815     /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
145816     ** in the FTS code the variable that the third argument to xNext points to
145817     ** is initialized to zero before the first (*but not necessarily
145818     ** subsequent*) call to xNext(). This is done for a particular application
145819     ** that needs to know whether or not the tokenizer is being used for
145820     ** snippet generation or for some other purpose.
145821     **
145822     ** Extreme care is required when writing code to depend on this
145823     ** initialization. It is not a documented part of the tokenizer interface.
145824     ** If a tokenizer is used directly by any code outside of FTS, this
145825     ** convention might not be respected.  */
145826     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
145827     if( rc!=SQLITE_OK ){
145828       if( rc==SQLITE_DONE ){
145829         /* Special case - the last token of the snippet is also the last token
145830         ** of the column. Append any punctuation that occurred between the end
145831         ** of the previous token and the end of the document to the output.
145832         ** Then break out of the loop. */
145833         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
145834       }
145835       break;
145836     }
145837     if( iCurrent<iPos ){ continue; }
145838 
145839     if( !isShiftDone ){
145840       int n = nDoc - iBegin;
145841       rc = fts3SnippetShift(
145842           pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
145843       );
145844       isShiftDone = 1;
145845 
145846       /* Now that the shift has been done, check if the initial "..." are
145847       ** required. They are required if (a) this is not the first fragment,
145848       ** or (b) this fragment does not begin at position 0 of its column.
145849       */
145850       if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
145851         rc = fts3StringAppend(pOut, zEllipsis, -1);
145852       }
145853       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
145854     }
145855 
145856     if( iCurrent>=(iPos+nSnippet) ){
145857       if( isLast ){
145858         rc = fts3StringAppend(pOut, zEllipsis, -1);
145859       }
145860       break;
145861     }
145862 
145863     /* Set isHighlight to true if this term should be highlighted. */
145864     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
145865 
145866     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
145867     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
145868     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
145869     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
145870 
145871     iEnd = iFin;
145872   }
145873 
145874   pMod->xClose(pC);
145875   return rc;
145876 }
145877 
145878 
145879 /*
145880 ** This function is used to count the entries in a column-list (a
145881 ** delta-encoded list of term offsets within a single column of a single
145882 ** row). When this function is called, *ppCollist should point to the
145883 ** beginning of the first varint in the column-list (the varint that
145884 ** contains the position of the first matching term in the column data).
145885 ** Before returning, *ppCollist is set to point to the first byte after
145886 ** the last varint in the column-list (either the 0x00 signifying the end
145887 ** of the position-list, or the 0x01 that precedes the column number of
145888 ** the next column in the position-list).
145889 **
145890 ** The number of elements in the column-list is returned.
145891 */
145892 static int fts3ColumnlistCount(char **ppCollist){
145893   char *pEnd = *ppCollist;
145894   char c = 0;
145895   int nEntry = 0;
145896 
145897   /* A column-list is terminated by either a 0x01 or 0x00. */
145898   while( 0xFE & (*pEnd | c) ){
145899     c = *pEnd++ & 0x80;
145900     if( !c ) nEntry++;
145901   }
145902 
145903   *ppCollist = pEnd;
145904   return nEntry;
145905 }
145906 
145907 /*
145908 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
145909 ** for a single query.
145910 **
145911 ** fts3ExprIterate() callback to load the 'global' elements of a
145912 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
145913 ** of the matchinfo array that are constant for all rows returned by the
145914 ** current query.
145915 **
145916 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
145917 ** function populates Matchinfo.aMatchinfo[] as follows:
145918 **
145919 **   for(iCol=0; iCol<nCol; iCol++){
145920 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
145921 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
145922 **   }
145923 **
145924 ** where X is the number of matches for phrase iPhrase is column iCol of all
145925 ** rows of the table. Y is the number of rows for which column iCol contains
145926 ** at least one instance of phrase iPhrase.
145927 **
145928 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
145929 ** Y values are set to nDoc, where nDoc is the number of documents in the
145930 ** file system. This is done because the full-text index doclist is required
145931 ** to calculate these values properly, and the full-text index doclist is
145932 ** not available for deferred tokens.
145933 */
145934 static int fts3ExprGlobalHitsCb(
145935   Fts3Expr *pExpr,                /* Phrase expression node */
145936   int iPhrase,                    /* Phrase number (numbered from zero) */
145937   void *pCtx                      /* Pointer to MatchInfo structure */
145938 ){
145939   MatchInfo *p = (MatchInfo *)pCtx;
145940   return sqlite3Fts3EvalPhraseStats(
145941       p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
145942   );
145943 }
145944 
145945 /*
145946 ** fts3ExprIterate() callback used to collect the "local" part of the
145947 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
145948 ** array that are different for each row returned by the query.
145949 */
145950 static int fts3ExprLocalHitsCb(
145951   Fts3Expr *pExpr,                /* Phrase expression node */
145952   int iPhrase,                    /* Phrase number */
145953   void *pCtx                      /* Pointer to MatchInfo structure */
145954 ){
145955   int rc = SQLITE_OK;
145956   MatchInfo *p = (MatchInfo *)pCtx;
145957   int iStart = iPhrase * p->nCol * 3;
145958   int i;
145959 
145960   for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
145961     char *pCsr;
145962     rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
145963     if( pCsr ){
145964       p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
145965     }else{
145966       p->aMatchinfo[iStart+i*3] = 0;
145967     }
145968   }
145969 
145970   return rc;
145971 }
145972 
145973 static int fts3MatchinfoCheck(
145974   Fts3Table *pTab,
145975   char cArg,
145976   char **pzErr
145977 ){
145978   if( (cArg==FTS3_MATCHINFO_NPHRASE)
145979    || (cArg==FTS3_MATCHINFO_NCOL)
145980    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
145981    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
145982    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
145983    || (cArg==FTS3_MATCHINFO_LCS)
145984    || (cArg==FTS3_MATCHINFO_HITS)
145985   ){
145986     return SQLITE_OK;
145987   }
145988   *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
145989   return SQLITE_ERROR;
145990 }
145991 
145992 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
145993   int nVal;                       /* Number of integers output by cArg */
145994 
145995   switch( cArg ){
145996     case FTS3_MATCHINFO_NDOC:
145997     case FTS3_MATCHINFO_NPHRASE:
145998     case FTS3_MATCHINFO_NCOL:
145999       nVal = 1;
146000       break;
146001 
146002     case FTS3_MATCHINFO_AVGLENGTH:
146003     case FTS3_MATCHINFO_LENGTH:
146004     case FTS3_MATCHINFO_LCS:
146005       nVal = pInfo->nCol;
146006       break;
146007 
146008     default:
146009       assert( cArg==FTS3_MATCHINFO_HITS );
146010       nVal = pInfo->nCol * pInfo->nPhrase * 3;
146011       break;
146012   }
146013 
146014   return nVal;
146015 }
146016 
146017 static int fts3MatchinfoSelectDoctotal(
146018   Fts3Table *pTab,
146019   sqlite3_stmt **ppStmt,
146020   sqlite3_int64 *pnDoc,
146021   const char **paLen
146022 ){
146023   sqlite3_stmt *pStmt;
146024   const char *a;
146025   sqlite3_int64 nDoc;
146026 
146027   if( !*ppStmt ){
146028     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
146029     if( rc!=SQLITE_OK ) return rc;
146030   }
146031   pStmt = *ppStmt;
146032   assert( sqlite3_data_count(pStmt)==1 );
146033 
146034   a = sqlite3_column_blob(pStmt, 0);
146035   a += sqlite3Fts3GetVarint(a, &nDoc);
146036   if( nDoc==0 ) return FTS_CORRUPT_VTAB;
146037   *pnDoc = (u32)nDoc;
146038 
146039   if( paLen ) *paLen = a;
146040   return SQLITE_OK;
146041 }
146042 
146043 /*
146044 ** An instance of the following structure is used to store state while
146045 ** iterating through a multi-column position-list corresponding to the
146046 ** hits for a single phrase on a single row in order to calculate the
146047 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
146048 */
146049 typedef struct LcsIterator LcsIterator;
146050 struct LcsIterator {
146051   Fts3Expr *pExpr;                /* Pointer to phrase expression */
146052   int iPosOffset;                 /* Tokens count up to end of this phrase */
146053   char *pRead;                    /* Cursor used to iterate through aDoclist */
146054   int iPos;                       /* Current position */
146055 };
146056 
146057 /*
146058 ** If LcsIterator.iCol is set to the following value, the iterator has
146059 ** finished iterating through all offsets for all columns.
146060 */
146061 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
146062 
146063 static int fts3MatchinfoLcsCb(
146064   Fts3Expr *pExpr,                /* Phrase expression node */
146065   int iPhrase,                    /* Phrase number (numbered from zero) */
146066   void *pCtx                      /* Pointer to MatchInfo structure */
146067 ){
146068   LcsIterator *aIter = (LcsIterator *)pCtx;
146069   aIter[iPhrase].pExpr = pExpr;
146070   return SQLITE_OK;
146071 }
146072 
146073 /*
146074 ** Advance the iterator passed as an argument to the next position. Return
146075 ** 1 if the iterator is at EOF or if it now points to the start of the
146076 ** position list for the next column.
146077 */
146078 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
146079   char *pRead = pIter->pRead;
146080   sqlite3_int64 iRead;
146081   int rc = 0;
146082 
146083   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
146084   if( iRead==0 || iRead==1 ){
146085     pRead = 0;
146086     rc = 1;
146087   }else{
146088     pIter->iPos += (int)(iRead-2);
146089   }
146090 
146091   pIter->pRead = pRead;
146092   return rc;
146093 }
146094 
146095 /*
146096 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
146097 **
146098 ** If the call is successful, the longest-common-substring lengths for each
146099 ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
146100 ** array before returning. SQLITE_OK is returned in this case.
146101 **
146102 ** Otherwise, if an error occurs, an SQLite error code is returned and the
146103 ** data written to the first nCol elements of pInfo->aMatchinfo[] is
146104 ** undefined.
146105 */
146106 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
146107   LcsIterator *aIter;
146108   int i;
146109   int iCol;
146110   int nToken = 0;
146111 
146112   /* Allocate and populate the array of LcsIterator objects. The array
146113   ** contains one element for each matchable phrase in the query.
146114   **/
146115   aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
146116   if( !aIter ) return SQLITE_NOMEM;
146117   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
146118   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
146119 
146120   for(i=0; i<pInfo->nPhrase; i++){
146121     LcsIterator *pIter = &aIter[i];
146122     nToken -= pIter->pExpr->pPhrase->nToken;
146123     pIter->iPosOffset = nToken;
146124   }
146125 
146126   for(iCol=0; iCol<pInfo->nCol; iCol++){
146127     int nLcs = 0;                 /* LCS value for this column */
146128     int nLive = 0;                /* Number of iterators in aIter not at EOF */
146129 
146130     for(i=0; i<pInfo->nPhrase; i++){
146131       int rc;
146132       LcsIterator *pIt = &aIter[i];
146133       rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
146134       if( rc!=SQLITE_OK ) return rc;
146135       if( pIt->pRead ){
146136         pIt->iPos = pIt->iPosOffset;
146137         fts3LcsIteratorAdvance(&aIter[i]);
146138         nLive++;
146139       }
146140     }
146141 
146142     while( nLive>0 ){
146143       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
146144       int nThisLcs = 0;           /* LCS for the current iterator positions */
146145 
146146       for(i=0; i<pInfo->nPhrase; i++){
146147         LcsIterator *pIter = &aIter[i];
146148         if( pIter->pRead==0 ){
146149           /* This iterator is already at EOF for this column. */
146150           nThisLcs = 0;
146151         }else{
146152           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
146153             pAdv = pIter;
146154           }
146155           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
146156             nThisLcs++;
146157           }else{
146158             nThisLcs = 1;
146159           }
146160           if( nThisLcs>nLcs ) nLcs = nThisLcs;
146161         }
146162       }
146163       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
146164     }
146165 
146166     pInfo->aMatchinfo[iCol] = nLcs;
146167   }
146168 
146169   sqlite3_free(aIter);
146170   return SQLITE_OK;
146171 }
146172 
146173 /*
146174 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
146175 ** be returned by the matchinfo() function. Argument zArg contains the
146176 ** format string passed as the second argument to matchinfo (or the
146177 ** default value "pcx" if no second argument was specified). The format
146178 ** string has already been validated and the pInfo->aMatchinfo[] array
146179 ** is guaranteed to be large enough for the output.
146180 **
146181 ** If bGlobal is true, then populate all fields of the matchinfo() output.
146182 ** If it is false, then assume that those fields that do not change between
146183 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
146184 ** have already been populated.
146185 **
146186 ** Return SQLITE_OK if successful, or an SQLite error code if an error
146187 ** occurs. If a value other than SQLITE_OK is returned, the state the
146188 ** pInfo->aMatchinfo[] buffer is left in is undefined.
146189 */
146190 static int fts3MatchinfoValues(
146191   Fts3Cursor *pCsr,               /* FTS3 cursor object */
146192   int bGlobal,                    /* True to grab the global stats */
146193   MatchInfo *pInfo,               /* Matchinfo context object */
146194   const char *zArg                /* Matchinfo format string */
146195 ){
146196   int rc = SQLITE_OK;
146197   int i;
146198   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
146199   sqlite3_stmt *pSelect = 0;
146200 
146201   for(i=0; rc==SQLITE_OK && zArg[i]; i++){
146202 
146203     switch( zArg[i] ){
146204       case FTS3_MATCHINFO_NPHRASE:
146205         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
146206         break;
146207 
146208       case FTS3_MATCHINFO_NCOL:
146209         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
146210         break;
146211 
146212       case FTS3_MATCHINFO_NDOC:
146213         if( bGlobal ){
146214           sqlite3_int64 nDoc = 0;
146215           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
146216           pInfo->aMatchinfo[0] = (u32)nDoc;
146217         }
146218         break;
146219 
146220       case FTS3_MATCHINFO_AVGLENGTH:
146221         if( bGlobal ){
146222           sqlite3_int64 nDoc;     /* Number of rows in table */
146223           const char *a;          /* Aggregate column length array */
146224 
146225           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
146226           if( rc==SQLITE_OK ){
146227             int iCol;
146228             for(iCol=0; iCol<pInfo->nCol; iCol++){
146229               u32 iVal;
146230               sqlite3_int64 nToken;
146231               a += sqlite3Fts3GetVarint(a, &nToken);
146232               iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
146233               pInfo->aMatchinfo[iCol] = iVal;
146234             }
146235           }
146236         }
146237         break;
146238 
146239       case FTS3_MATCHINFO_LENGTH: {
146240         sqlite3_stmt *pSelectDocsize = 0;
146241         rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
146242         if( rc==SQLITE_OK ){
146243           int iCol;
146244           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
146245           for(iCol=0; iCol<pInfo->nCol; iCol++){
146246             sqlite3_int64 nToken;
146247             a += sqlite3Fts3GetVarint(a, &nToken);
146248             pInfo->aMatchinfo[iCol] = (u32)nToken;
146249           }
146250         }
146251         sqlite3_reset(pSelectDocsize);
146252         break;
146253       }
146254 
146255       case FTS3_MATCHINFO_LCS:
146256         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
146257         if( rc==SQLITE_OK ){
146258           rc = fts3MatchinfoLcs(pCsr, pInfo);
146259         }
146260         break;
146261 
146262       default: {
146263         Fts3Expr *pExpr;
146264         assert( zArg[i]==FTS3_MATCHINFO_HITS );
146265         pExpr = pCsr->pExpr;
146266         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
146267         if( rc!=SQLITE_OK ) break;
146268         if( bGlobal ){
146269           if( pCsr->pDeferred ){
146270             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
146271             if( rc!=SQLITE_OK ) break;
146272           }
146273           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
146274           if( rc!=SQLITE_OK ) break;
146275         }
146276         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
146277         break;
146278       }
146279     }
146280 
146281     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
146282   }
146283 
146284   sqlite3_reset(pSelect);
146285   return rc;
146286 }
146287 
146288 
146289 /*
146290 ** Populate pCsr->aMatchinfo[] with data for the current row. The
146291 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
146292 */
146293 static int fts3GetMatchinfo(
146294   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
146295   const char *zArg                /* Second argument to matchinfo() function */
146296 ){
146297   MatchInfo sInfo;
146298   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
146299   int rc = SQLITE_OK;
146300   int bGlobal = 0;                /* Collect 'global' stats as well as local */
146301 
146302   memset(&sInfo, 0, sizeof(MatchInfo));
146303   sInfo.pCursor = pCsr;
146304   sInfo.nCol = pTab->nColumn;
146305 
146306   /* If there is cached matchinfo() data, but the format string for the
146307   ** cache does not match the format string for this request, discard
146308   ** the cached data. */
146309   if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
146310     assert( pCsr->aMatchinfo );
146311     sqlite3_free(pCsr->aMatchinfo);
146312     pCsr->zMatchinfo = 0;
146313     pCsr->aMatchinfo = 0;
146314   }
146315 
146316   /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
146317   ** matchinfo function has been called for this query. In this case
146318   ** allocate the array used to accumulate the matchinfo data and
146319   ** initialize those elements that are constant for every row.
146320   */
146321   if( pCsr->aMatchinfo==0 ){
146322     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
146323     int nArg;                     /* Bytes in zArg */
146324     int i;                        /* Used to iterate through zArg */
146325 
146326     /* Determine the number of phrases in the query */
146327     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
146328     sInfo.nPhrase = pCsr->nPhrase;
146329 
146330     /* Determine the number of integers in the buffer returned by this call. */
146331     for(i=0; zArg[i]; i++){
146332       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
146333     }
146334 
146335     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
146336     nArg = (int)strlen(zArg);
146337     pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
146338     if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
146339 
146340     pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
146341     pCsr->nMatchinfo = nMatchinfo;
146342     memcpy(pCsr->zMatchinfo, zArg, nArg+1);
146343     memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
146344     pCsr->isMatchinfoNeeded = 1;
146345     bGlobal = 1;
146346   }
146347 
146348   sInfo.aMatchinfo = pCsr->aMatchinfo;
146349   sInfo.nPhrase = pCsr->nPhrase;
146350   if( pCsr->isMatchinfoNeeded ){
146351     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
146352     pCsr->isMatchinfoNeeded = 0;
146353   }
146354 
146355   return rc;
146356 }
146357 
146358 /*
146359 ** Implementation of snippet() function.
146360 */
146361 SQLITE_PRIVATE void sqlite3Fts3Snippet(
146362   sqlite3_context *pCtx,          /* SQLite function call context */
146363   Fts3Cursor *pCsr,               /* Cursor object */
146364   const char *zStart,             /* Snippet start text - "<b>" */
146365   const char *zEnd,               /* Snippet end text - "</b>" */
146366   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
146367   int iCol,                       /* Extract snippet from this column */
146368   int nToken                      /* Approximate number of tokens in snippet */
146369 ){
146370   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
146371   int rc = SQLITE_OK;
146372   int i;
146373   StrBuffer res = {0, 0, 0};
146374 
146375   /* The returned text includes up to four fragments of text extracted from
146376   ** the data in the current row. The first iteration of the for(...) loop
146377   ** below attempts to locate a single fragment of text nToken tokens in
146378   ** size that contains at least one instance of all phrases in the query
146379   ** expression that appear in the current row. If such a fragment of text
146380   ** cannot be found, the second iteration of the loop attempts to locate
146381   ** a pair of fragments, and so on.
146382   */
146383   int nSnippet = 0;               /* Number of fragments in this snippet */
146384   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
146385   int nFToken = -1;               /* Number of tokens in each fragment */
146386 
146387   if( !pCsr->pExpr ){
146388     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
146389     return;
146390   }
146391 
146392   for(nSnippet=1; 1; nSnippet++){
146393 
146394     int iSnip;                    /* Loop counter 0..nSnippet-1 */
146395     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
146396     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
146397 
146398     if( nToken>=0 ){
146399       nFToken = (nToken+nSnippet-1) / nSnippet;
146400     }else{
146401       nFToken = -1 * nToken;
146402     }
146403 
146404     for(iSnip=0; iSnip<nSnippet; iSnip++){
146405       int iBestScore = -1;        /* Best score of columns checked so far */
146406       int iRead;                  /* Used to iterate through columns */
146407       SnippetFragment *pFragment = &aSnippet[iSnip];
146408 
146409       memset(pFragment, 0, sizeof(*pFragment));
146410 
146411       /* Loop through all columns of the table being considered for snippets.
146412       ** If the iCol argument to this function was negative, this means all
146413       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
146414       */
146415       for(iRead=0; iRead<pTab->nColumn; iRead++){
146416         SnippetFragment sF = {0, 0, 0, 0};
146417         int iS;
146418         if( iCol>=0 && iRead!=iCol ) continue;
146419 
146420         /* Find the best snippet of nFToken tokens in column iRead. */
146421         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
146422         if( rc!=SQLITE_OK ){
146423           goto snippet_out;
146424         }
146425         if( iS>iBestScore ){
146426           *pFragment = sF;
146427           iBestScore = iS;
146428         }
146429       }
146430 
146431       mCovered |= pFragment->covered;
146432     }
146433 
146434     /* If all query phrases seen by fts3BestSnippet() are present in at least
146435     ** one of the nSnippet snippet fragments, break out of the loop.
146436     */
146437     assert( (mCovered&mSeen)==mCovered );
146438     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
146439   }
146440 
146441   assert( nFToken>0 );
146442 
146443   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
146444     rc = fts3SnippetText(pCsr, &aSnippet[i],
146445         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
146446     );
146447   }
146448 
146449  snippet_out:
146450   sqlite3Fts3SegmentsClose(pTab);
146451   if( rc!=SQLITE_OK ){
146452     sqlite3_result_error_code(pCtx, rc);
146453     sqlite3_free(res.z);
146454   }else{
146455     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
146456   }
146457 }
146458 
146459 
146460 typedef struct TermOffset TermOffset;
146461 typedef struct TermOffsetCtx TermOffsetCtx;
146462 
146463 struct TermOffset {
146464   char *pList;                    /* Position-list */
146465   int iPos;                       /* Position just read from pList */
146466   int iOff;                       /* Offset of this term from read positions */
146467 };
146468 
146469 struct TermOffsetCtx {
146470   Fts3Cursor *pCsr;
146471   int iCol;                       /* Column of table to populate aTerm for */
146472   int iTerm;
146473   sqlite3_int64 iDocid;
146474   TermOffset *aTerm;
146475 };
146476 
146477 /*
146478 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
146479 */
146480 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
146481   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
146482   int nTerm;                      /* Number of tokens in phrase */
146483   int iTerm;                      /* For looping through nTerm phrase terms */
146484   char *pList;                    /* Pointer to position list for phrase */
146485   int iPos = 0;                   /* First position in position-list */
146486   int rc;
146487 
146488   UNUSED_PARAMETER(iPhrase);
146489   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
146490   nTerm = pExpr->pPhrase->nToken;
146491   if( pList ){
146492     fts3GetDeltaPosition(&pList, &iPos);
146493     assert( iPos>=0 );
146494   }
146495 
146496   for(iTerm=0; iTerm<nTerm; iTerm++){
146497     TermOffset *pT = &p->aTerm[p->iTerm++];
146498     pT->iOff = nTerm-iTerm-1;
146499     pT->pList = pList;
146500     pT->iPos = iPos;
146501   }
146502 
146503   return rc;
146504 }
146505 
146506 /*
146507 ** Implementation of offsets() function.
146508 */
146509 SQLITE_PRIVATE void sqlite3Fts3Offsets(
146510   sqlite3_context *pCtx,          /* SQLite function call context */
146511   Fts3Cursor *pCsr                /* Cursor object */
146512 ){
146513   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
146514   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
146515   int rc;                         /* Return Code */
146516   int nToken;                     /* Number of tokens in query */
146517   int iCol;                       /* Column currently being processed */
146518   StrBuffer res = {0, 0, 0};      /* Result string */
146519   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
146520 
146521   if( !pCsr->pExpr ){
146522     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
146523     return;
146524   }
146525 
146526   memset(&sCtx, 0, sizeof(sCtx));
146527   assert( pCsr->isRequireSeek==0 );
146528 
146529   /* Count the number of terms in the query */
146530   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
146531   if( rc!=SQLITE_OK ) goto offsets_out;
146532 
146533   /* Allocate the array of TermOffset iterators. */
146534   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
146535   if( 0==sCtx.aTerm ){
146536     rc = SQLITE_NOMEM;
146537     goto offsets_out;
146538   }
146539   sCtx.iDocid = pCsr->iPrevId;
146540   sCtx.pCsr = pCsr;
146541 
146542   /* Loop through the table columns, appending offset information to
146543   ** string-buffer res for each column.
146544   */
146545   for(iCol=0; iCol<pTab->nColumn; iCol++){
146546     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
146547     const char *ZDUMMY;           /* Dummy argument used with xNext() */
146548     int NDUMMY = 0;               /* Dummy argument used with xNext() */
146549     int iStart = 0;
146550     int iEnd = 0;
146551     int iCurrent = 0;
146552     const char *zDoc;
146553     int nDoc;
146554 
146555     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
146556     ** no way that this operation can fail, so the return code from
146557     ** fts3ExprIterate() can be discarded.
146558     */
146559     sCtx.iCol = iCol;
146560     sCtx.iTerm = 0;
146561     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
146562 
146563     /* Retreive the text stored in column iCol. If an SQL NULL is stored
146564     ** in column iCol, jump immediately to the next iteration of the loop.
146565     ** If an OOM occurs while retrieving the data (this can happen if SQLite
146566     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
146567     ** to the caller.
146568     */
146569     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
146570     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
146571     if( zDoc==0 ){
146572       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
146573         continue;
146574       }
146575       rc = SQLITE_NOMEM;
146576       goto offsets_out;
146577     }
146578 
146579     /* Initialize a tokenizer iterator to iterate through column iCol. */
146580     rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
146581         zDoc, nDoc, &pC
146582     );
146583     if( rc!=SQLITE_OK ) goto offsets_out;
146584 
146585     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
146586     while( rc==SQLITE_OK ){
146587       int i;                      /* Used to loop through terms */
146588       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
146589       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
146590 
146591       for(i=0; i<nToken; i++){
146592         TermOffset *pT = &sCtx.aTerm[i];
146593         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
146594           iMinPos = pT->iPos-pT->iOff;
146595           pTerm = pT;
146596         }
146597       }
146598 
146599       if( !pTerm ){
146600         /* All offsets for this column have been gathered. */
146601         rc = SQLITE_DONE;
146602       }else{
146603         assert( iCurrent<=iMinPos );
146604         if( 0==(0xFE&*pTerm->pList) ){
146605           pTerm->pList = 0;
146606         }else{
146607           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
146608         }
146609         while( rc==SQLITE_OK && iCurrent<iMinPos ){
146610           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
146611         }
146612         if( rc==SQLITE_OK ){
146613           char aBuffer[64];
146614           sqlite3_snprintf(sizeof(aBuffer), aBuffer,
146615               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
146616           );
146617           rc = fts3StringAppend(&res, aBuffer, -1);
146618         }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
146619           rc = FTS_CORRUPT_VTAB;
146620         }
146621       }
146622     }
146623     if( rc==SQLITE_DONE ){
146624       rc = SQLITE_OK;
146625     }
146626 
146627     pMod->xClose(pC);
146628     if( rc!=SQLITE_OK ) goto offsets_out;
146629   }
146630 
146631  offsets_out:
146632   sqlite3_free(sCtx.aTerm);
146633   assert( rc!=SQLITE_DONE );
146634   sqlite3Fts3SegmentsClose(pTab);
146635   if( rc!=SQLITE_OK ){
146636     sqlite3_result_error_code(pCtx,  rc);
146637     sqlite3_free(res.z);
146638   }else{
146639     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
146640   }
146641   return;
146642 }
146643 
146644 /*
146645 ** Implementation of matchinfo() function.
146646 */
146647 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
146648   sqlite3_context *pContext,      /* Function call context */
146649   Fts3Cursor *pCsr,               /* FTS3 table cursor */
146650   const char *zArg                /* Second arg to matchinfo() function */
146651 ){
146652   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
146653   int rc;
146654   int i;
146655   const char *zFormat;
146656 
146657   if( zArg ){
146658     for(i=0; zArg[i]; i++){
146659       char *zErr = 0;
146660       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
146661         sqlite3_result_error(pContext, zErr, -1);
146662         sqlite3_free(zErr);
146663         return;
146664       }
146665     }
146666     zFormat = zArg;
146667   }else{
146668     zFormat = FTS3_MATCHINFO_DEFAULT;
146669   }
146670 
146671   if( !pCsr->pExpr ){
146672     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
146673     return;
146674   }
146675 
146676   /* Retrieve matchinfo() data. */
146677   rc = fts3GetMatchinfo(pCsr, zFormat);
146678   sqlite3Fts3SegmentsClose(pTab);
146679 
146680   if( rc!=SQLITE_OK ){
146681     sqlite3_result_error_code(pContext, rc);
146682   }else{
146683     int n = pCsr->nMatchinfo * sizeof(u32);
146684     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
146685   }
146686 }
146687 
146688 #endif
146689 
146690 /************** End of fts3_snippet.c ****************************************/
146691 /************** Begin file fts3_unicode.c ************************************/
146692 /*
146693 ** 2012 May 24
146694 **
146695 ** The author disclaims copyright to this source code.  In place of
146696 ** a legal notice, here is a blessing:
146697 **
146698 **    May you do good and not evil.
146699 **    May you find forgiveness for yourself and forgive others.
146700 **    May you share freely, never taking more than you give.
146701 **
146702 ******************************************************************************
146703 **
146704 ** Implementation of the "unicode" full-text-search tokenizer.
146705 */
146706 
146707 #ifndef SQLITE_DISABLE_FTS3_UNICODE
146708 
146709 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
146710 
146711 /* #include <assert.h> */
146712 /* #include <stdlib.h> */
146713 /* #include <stdio.h> */
146714 /* #include <string.h> */
146715 
146716 
146717 /*
146718 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
146719 ** from the sqlite3 source file utf.c. If this file is compiled as part
146720 ** of the amalgamation, they are not required.
146721 */
146722 #ifndef SQLITE_AMALGAMATION
146723 
146724 static const unsigned char sqlite3Utf8Trans1[] = {
146725   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
146726   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
146727   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
146728   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
146729   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
146730   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
146731   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
146732   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
146733 };
146734 
146735 #define READ_UTF8(zIn, zTerm, c)                           \
146736   c = *(zIn++);                                            \
146737   if( c>=0xc0 ){                                           \
146738     c = sqlite3Utf8Trans1[c-0xc0];                         \
146739     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
146740       c = (c<<6) + (0x3f & *(zIn++));                      \
146741     }                                                      \
146742     if( c<0x80                                             \
146743         || (c&0xFFFFF800)==0xD800                          \
146744         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
146745   }
146746 
146747 #define WRITE_UTF8(zOut, c) {                          \
146748   if( c<0x00080 ){                                     \
146749     *zOut++ = (u8)(c&0xFF);                            \
146750   }                                                    \
146751   else if( c<0x00800 ){                                \
146752     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
146753     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
146754   }                                                    \
146755   else if( c<0x10000 ){                                \
146756     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
146757     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
146758     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
146759   }else{                                               \
146760     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
146761     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
146762     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
146763     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
146764   }                                                    \
146765 }
146766 
146767 #endif /* ifndef SQLITE_AMALGAMATION */
146768 
146769 typedef struct unicode_tokenizer unicode_tokenizer;
146770 typedef struct unicode_cursor unicode_cursor;
146771 
146772 struct unicode_tokenizer {
146773   sqlite3_tokenizer base;
146774   int bRemoveDiacritic;
146775   int nException;
146776   int *aiException;
146777 };
146778 
146779 struct unicode_cursor {
146780   sqlite3_tokenizer_cursor base;
146781   const unsigned char *aInput;    /* Input text being tokenized */
146782   int nInput;                     /* Size of aInput[] in bytes */
146783   int iOff;                       /* Current offset within aInput[] */
146784   int iToken;                     /* Index of next token to be returned */
146785   char *zToken;                   /* storage for current token */
146786   int nAlloc;                     /* space allocated at zToken */
146787 };
146788 
146789 
146790 /*
146791 ** Destroy a tokenizer allocated by unicodeCreate().
146792 */
146793 static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
146794   if( pTokenizer ){
146795     unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
146796     sqlite3_free(p->aiException);
146797     sqlite3_free(p);
146798   }
146799   return SQLITE_OK;
146800 }
146801 
146802 /*
146803 ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
146804 ** statement has specified that the tokenizer for this table shall consider
146805 ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
146806 ** token characters (if bAlnum==1).
146807 **
146808 ** For each codepoint in the zIn/nIn string, this function checks if the
146809 ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
146810 ** If so, no action is taken. Otherwise, the codepoint is added to the
146811 ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
146812 ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
146813 ** codepoints in the aiException[] array.
146814 **
146815 ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
146816 ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
146817 ** It is not possible to change the behavior of the tokenizer with respect
146818 ** to these codepoints.
146819 */
146820 static int unicodeAddExceptions(
146821   unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
146822   int bAlnum,                     /* Replace Isalnum() return value with this */
146823   const char *zIn,                /* Array of characters to make exceptions */
146824   int nIn                         /* Length of z in bytes */
146825 ){
146826   const unsigned char *z = (const unsigned char *)zIn;
146827   const unsigned char *zTerm = &z[nIn];
146828   int iCode;
146829   int nEntry = 0;
146830 
146831   assert( bAlnum==0 || bAlnum==1 );
146832 
146833   while( z<zTerm ){
146834     READ_UTF8(z, zTerm, iCode);
146835     assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
146836     if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
146837      && sqlite3FtsUnicodeIsdiacritic(iCode)==0
146838     ){
146839       nEntry++;
146840     }
146841   }
146842 
146843   if( nEntry ){
146844     int *aNew;                    /* New aiException[] array */
146845     int nNew;                     /* Number of valid entries in array aNew[] */
146846 
146847     aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
146848     if( aNew==0 ) return SQLITE_NOMEM;
146849     nNew = p->nException;
146850 
146851     z = (const unsigned char *)zIn;
146852     while( z<zTerm ){
146853       READ_UTF8(z, zTerm, iCode);
146854       if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
146855        && sqlite3FtsUnicodeIsdiacritic(iCode)==0
146856       ){
146857         int i, j;
146858         for(i=0; i<nNew && aNew[i]<iCode; i++);
146859         for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
146860         aNew[i] = iCode;
146861         nNew++;
146862       }
146863     }
146864     p->aiException = aNew;
146865     p->nException = nNew;
146866   }
146867 
146868   return SQLITE_OK;
146869 }
146870 
146871 /*
146872 ** Return true if the p->aiException[] array contains the value iCode.
146873 */
146874 static int unicodeIsException(unicode_tokenizer *p, int iCode){
146875   if( p->nException>0 ){
146876     int *a = p->aiException;
146877     int iLo = 0;
146878     int iHi = p->nException-1;
146879 
146880     while( iHi>=iLo ){
146881       int iTest = (iHi + iLo) / 2;
146882       if( iCode==a[iTest] ){
146883         return 1;
146884       }else if( iCode>a[iTest] ){
146885         iLo = iTest+1;
146886       }else{
146887         iHi = iTest-1;
146888       }
146889     }
146890   }
146891 
146892   return 0;
146893 }
146894 
146895 /*
146896 ** Return true if, for the purposes of tokenization, codepoint iCode is
146897 ** considered a token character (not a separator).
146898 */
146899 static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
146900   assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
146901   return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
146902 }
146903 
146904 /*
146905 ** Create a new tokenizer instance.
146906 */
146907 static int unicodeCreate(
146908   int nArg,                       /* Size of array argv[] */
146909   const char * const *azArg,      /* Tokenizer creation arguments */
146910   sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
146911 ){
146912   unicode_tokenizer *pNew;        /* New tokenizer object */
146913   int i;
146914   int rc = SQLITE_OK;
146915 
146916   pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
146917   if( pNew==NULL ) return SQLITE_NOMEM;
146918   memset(pNew, 0, sizeof(unicode_tokenizer));
146919   pNew->bRemoveDiacritic = 1;
146920 
146921   for(i=0; rc==SQLITE_OK && i<nArg; i++){
146922     const char *z = azArg[i];
146923     int n = (int)strlen(z);
146924 
146925     if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
146926       pNew->bRemoveDiacritic = 1;
146927     }
146928     else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
146929       pNew->bRemoveDiacritic = 0;
146930     }
146931     else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
146932       rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
146933     }
146934     else if( n>=11 && memcmp("separators=", z, 11)==0 ){
146935       rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
146936     }
146937     else{
146938       /* Unrecognized argument */
146939       rc  = SQLITE_ERROR;
146940     }
146941   }
146942 
146943   if( rc!=SQLITE_OK ){
146944     unicodeDestroy((sqlite3_tokenizer *)pNew);
146945     pNew = 0;
146946   }
146947   *pp = (sqlite3_tokenizer *)pNew;
146948   return rc;
146949 }
146950 
146951 /*
146952 ** Prepare to begin tokenizing a particular string.  The input
146953 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
146954 ** used to incrementally tokenize this string is returned in
146955 ** *ppCursor.
146956 */
146957 static int unicodeOpen(
146958   sqlite3_tokenizer *p,           /* The tokenizer */
146959   const char *aInput,             /* Input string */
146960   int nInput,                     /* Size of string aInput in bytes */
146961   sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
146962 ){
146963   unicode_cursor *pCsr;
146964 
146965   pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
146966   if( pCsr==0 ){
146967     return SQLITE_NOMEM;
146968   }
146969   memset(pCsr, 0, sizeof(unicode_cursor));
146970 
146971   pCsr->aInput = (const unsigned char *)aInput;
146972   if( aInput==0 ){
146973     pCsr->nInput = 0;
146974   }else if( nInput<0 ){
146975     pCsr->nInput = (int)strlen(aInput);
146976   }else{
146977     pCsr->nInput = nInput;
146978   }
146979 
146980   *pp = &pCsr->base;
146981   UNUSED_PARAMETER(p);
146982   return SQLITE_OK;
146983 }
146984 
146985 /*
146986 ** Close a tokenization cursor previously opened by a call to
146987 ** simpleOpen() above.
146988 */
146989 static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
146990   unicode_cursor *pCsr = (unicode_cursor *) pCursor;
146991   sqlite3_free(pCsr->zToken);
146992   sqlite3_free(pCsr);
146993   return SQLITE_OK;
146994 }
146995 
146996 /*
146997 ** Extract the next token from a tokenization cursor.  The cursor must
146998 ** have been opened by a prior call to simpleOpen().
146999 */
147000 static int unicodeNext(
147001   sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
147002   const char **paToken,           /* OUT: Token text */
147003   int *pnToken,                   /* OUT: Number of bytes at *paToken */
147004   int *piStart,                   /* OUT: Starting offset of token */
147005   int *piEnd,                     /* OUT: Ending offset of token */
147006   int *piPos                      /* OUT: Position integer of token */
147007 ){
147008   unicode_cursor *pCsr = (unicode_cursor *)pC;
147009   unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
147010   int iCode = 0;
147011   char *zOut;
147012   const unsigned char *z = &pCsr->aInput[pCsr->iOff];
147013   const unsigned char *zStart = z;
147014   const unsigned char *zEnd;
147015   const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
147016 
147017   /* Scan past any delimiter characters before the start of the next token.
147018   ** Return SQLITE_DONE early if this takes us all the way to the end of
147019   ** the input.  */
147020   while( z<zTerm ){
147021     READ_UTF8(z, zTerm, iCode);
147022     if( unicodeIsAlnum(p, iCode) ) break;
147023     zStart = z;
147024   }
147025   if( zStart>=zTerm ) return SQLITE_DONE;
147026 
147027   zOut = pCsr->zToken;
147028   do {
147029     int iOut;
147030 
147031     /* Grow the output buffer if required. */
147032     if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
147033       char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
147034       if( !zNew ) return SQLITE_NOMEM;
147035       zOut = &zNew[zOut - pCsr->zToken];
147036       pCsr->zToken = zNew;
147037       pCsr->nAlloc += 64;
147038     }
147039 
147040     /* Write the folded case of the last character read to the output */
147041     zEnd = z;
147042     iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
147043     if( iOut ){
147044       WRITE_UTF8(zOut, iOut);
147045     }
147046 
147047     /* If the cursor is not at EOF, read the next character */
147048     if( z>=zTerm ) break;
147049     READ_UTF8(z, zTerm, iCode);
147050   }while( unicodeIsAlnum(p, iCode)
147051        || sqlite3FtsUnicodeIsdiacritic(iCode)
147052   );
147053 
147054   /* Set the output variables and return. */
147055   pCsr->iOff = (int)(z - pCsr->aInput);
147056   *paToken = pCsr->zToken;
147057   *pnToken = (int)(zOut - pCsr->zToken);
147058   *piStart = (int)(zStart - pCsr->aInput);
147059   *piEnd = (int)(zEnd - pCsr->aInput);
147060   *piPos = pCsr->iToken++;
147061   return SQLITE_OK;
147062 }
147063 
147064 /*
147065 ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
147066 ** structure for the unicode tokenizer.
147067 */
147068 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
147069   static const sqlite3_tokenizer_module module = {
147070     0,
147071     unicodeCreate,
147072     unicodeDestroy,
147073     unicodeOpen,
147074     unicodeClose,
147075     unicodeNext,
147076     0,
147077   };
147078   *ppModule = &module;
147079 }
147080 
147081 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
147082 #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
147083 
147084 /************** End of fts3_unicode.c ****************************************/
147085 /************** Begin file fts3_unicode2.c ***********************************/
147086 /*
147087 ** 2012 May 25
147088 **
147089 ** The author disclaims copyright to this source code.  In place of
147090 ** a legal notice, here is a blessing:
147091 **
147092 **    May you do good and not evil.
147093 **    May you find forgiveness for yourself and forgive others.
147094 **    May you share freely, never taking more than you give.
147095 **
147096 ******************************************************************************
147097 */
147098 
147099 /*
147100 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
147101 */
147102 
147103 #ifndef SQLITE_DISABLE_FTS3_UNICODE
147104 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
147105 
147106 /* #include <assert.h> */
147107 
147108 /*
147109 ** Return true if the argument corresponds to a unicode codepoint
147110 ** classified as either a letter or a number. Otherwise false.
147111 **
147112 ** The results are undefined if the value passed to this function
147113 ** is less than zero.
147114 */
147115 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
147116   /* Each unsigned integer in the following array corresponds to a contiguous
147117   ** range of unicode codepoints that are not either letters or numbers (i.e.
147118   ** codepoints for which this function should return 0).
147119   **
147120   ** The most significant 22 bits in each 32-bit value contain the first
147121   ** codepoint in the range. The least significant 10 bits are used to store
147122   ** the size of the range (always at least 1). In other words, the value
147123   ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
147124   ** C. It is not possible to represent a range larger than 1023 codepoints
147125   ** using this format.
147126   */
147127   static const unsigned int aEntry[] = {
147128     0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
147129     0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
147130     0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
147131     0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
147132     0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
147133     0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
147134     0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
147135     0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
147136     0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
147137     0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
147138     0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
147139     0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
147140     0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
147141     0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
147142     0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
147143     0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
147144     0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
147145     0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
147146     0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
147147     0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
147148     0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
147149     0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
147150     0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
147151     0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
147152     0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
147153     0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
147154     0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
147155     0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
147156     0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
147157     0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
147158     0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
147159     0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
147160     0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
147161     0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
147162     0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
147163     0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
147164     0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
147165     0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
147166     0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
147167     0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
147168     0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
147169     0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
147170     0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
147171     0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
147172     0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
147173     0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
147174     0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
147175     0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
147176     0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
147177     0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
147178     0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
147179     0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
147180     0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
147181     0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
147182     0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
147183     0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
147184     0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
147185     0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
147186     0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
147187     0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
147188     0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
147189     0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
147190     0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
147191     0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
147192     0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
147193     0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
147194     0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
147195     0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
147196     0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
147197     0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
147198     0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
147199     0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
147200     0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
147201     0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
147202     0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
147203     0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
147204     0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
147205     0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
147206     0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
147207     0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
147208     0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
147209     0x380400F0,
147210   };
147211   static const unsigned int aAscii[4] = {
147212     0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
147213   };
147214 
147215   if( c<128 ){
147216     return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
147217   }else if( c<(1<<22) ){
147218     unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
147219     int iRes = 0;
147220     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
147221     int iLo = 0;
147222     while( iHi>=iLo ){
147223       int iTest = (iHi + iLo) / 2;
147224       if( key >= aEntry[iTest] ){
147225         iRes = iTest;
147226         iLo = iTest+1;
147227       }else{
147228         iHi = iTest-1;
147229       }
147230     }
147231     assert( aEntry[0]<key );
147232     assert( key>=aEntry[iRes] );
147233     return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
147234   }
147235   return 1;
147236 }
147237 
147238 
147239 /*
147240 ** If the argument is a codepoint corresponding to a lowercase letter
147241 ** in the ASCII range with a diacritic added, return the codepoint
147242 ** of the ASCII letter only. For example, if passed 235 - "LATIN
147243 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
147244 ** E"). The resuls of passing a codepoint that corresponds to an
147245 ** uppercase letter are undefined.
147246 */
147247 static int remove_diacritic(int c){
147248   unsigned short aDia[] = {
147249         0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
147250      2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
147251      2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
147252      2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
147253      3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928,
147254      3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234,
147255      4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504,
147256      6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529,
147257     61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
147258     61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
147259     62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
147260     62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
147261     62924, 63050, 63082, 63274, 63390,
147262   };
147263   char aChar[] = {
147264     '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',
147265     'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',
147266     's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',
147267     'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',
147268     'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0',
147269     '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',
147270     'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',
147271     'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',
147272     'e',  'i',  'o',  'u',  'y',
147273   };
147274 
147275   unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
147276   int iRes = 0;
147277   int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
147278   int iLo = 0;
147279   while( iHi>=iLo ){
147280     int iTest = (iHi + iLo) / 2;
147281     if( key >= aDia[iTest] ){
147282       iRes = iTest;
147283       iLo = iTest+1;
147284     }else{
147285       iHi = iTest-1;
147286     }
147287   }
147288   assert( key>=aDia[iRes] );
147289   return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
147290 }
147291 
147292 
147293 /*
147294 ** Return true if the argument interpreted as a unicode codepoint
147295 ** is a diacritical modifier character.
147296 */
147297 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
147298   unsigned int mask0 = 0x08029FDF;
147299   unsigned int mask1 = 0x000361F8;
147300   if( c<768 || c>817 ) return 0;
147301   return (c < 768+32) ?
147302       (mask0 & (1 << (c-768))) :
147303       (mask1 & (1 << (c-768-32)));
147304 }
147305 
147306 
147307 /*
147308 ** Interpret the argument as a unicode codepoint. If the codepoint
147309 ** is an upper case character that has a lower case equivalent,
147310 ** return the codepoint corresponding to the lower case version.
147311 ** Otherwise, return a copy of the argument.
147312 **
147313 ** The results are undefined if the value passed to this function
147314 ** is less than zero.
147315 */
147316 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
147317   /* Each entry in the following array defines a rule for folding a range
147318   ** of codepoints to lower case. The rule applies to a range of nRange
147319   ** codepoints starting at codepoint iCode.
147320   **
147321   ** If the least significant bit in flags is clear, then the rule applies
147322   ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
147323   ** need to be folded). Or, if it is set, then the rule only applies to
147324   ** every second codepoint in the range, starting with codepoint C.
147325   **
147326   ** The 7 most significant bits in flags are an index into the aiOff[]
147327   ** array. If a specific codepoint C does require folding, then its lower
147328   ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
147329   **
147330   ** The contents of this array are generated by parsing the CaseFolding.txt
147331   ** file distributed as part of the "Unicode Character Database". See
147332   ** http://www.unicode.org for details.
147333   */
147334   static const struct TableEntry {
147335     unsigned short iCode;
147336     unsigned char flags;
147337     unsigned char nRange;
147338   } aEntry[] = {
147339     {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
147340     {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
147341     {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
147342     {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
147343     {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
147344     {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
147345     {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
147346     {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
147347     {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
147348     {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
147349     {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
147350     {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
147351     {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
147352     {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
147353     {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
147354     {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
147355     {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
147356     {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
147357     {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
147358     {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
147359     {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
147360     {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
147361     {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
147362     {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
147363     {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
147364     {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
147365     {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
147366     {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
147367     {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
147368     {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
147369     {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
147370     {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
147371     {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
147372     {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
147373     {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
147374     {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
147375     {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
147376     {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
147377     {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
147378     {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
147379     {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
147380     {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
147381     {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
147382     {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
147383     {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
147384     {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
147385     {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
147386     {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
147387     {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
147388     {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
147389     {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
147390     {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
147391     {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
147392     {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
147393     {65313, 14, 26},
147394   };
147395   static const unsigned short aiOff[] = {
147396    1,     2,     8,     15,    16,    26,    28,    32,
147397    37,    38,    40,    48,    63,    64,    69,    71,
147398    79,    80,    116,   202,   203,   205,   206,   207,
147399    209,   210,   211,   213,   214,   217,   218,   219,
147400    775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
147401    54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
147402    57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
147403    65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
147404    65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
147405    65514, 65521, 65527, 65528, 65529,
147406   };
147407 
147408   int ret = c;
147409 
147410   assert( c>=0 );
147411   assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
147412 
147413   if( c<128 ){
147414     if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
147415   }else if( c<65536 ){
147416     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
147417     int iLo = 0;
147418     int iRes = -1;
147419 
147420     while( iHi>=iLo ){
147421       int iTest = (iHi + iLo) / 2;
147422       int cmp = (c - aEntry[iTest].iCode);
147423       if( cmp>=0 ){
147424         iRes = iTest;
147425         iLo = iTest+1;
147426       }else{
147427         iHi = iTest-1;
147428       }
147429     }
147430     assert( iRes<0 || c>=aEntry[iRes].iCode );
147431 
147432     if( iRes>=0 ){
147433       const struct TableEntry *p = &aEntry[iRes];
147434       if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
147435         ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
147436         assert( ret>0 );
147437       }
147438     }
147439 
147440     if( bRemoveDiacritic ) ret = remove_diacritic(ret);
147441   }
147442 
147443   else if( c>=66560 && c<66600 ){
147444     ret = c + 40;
147445   }
147446 
147447   return ret;
147448 }
147449 #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
147450 #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
147451 
147452 /************** End of fts3_unicode2.c ***************************************/
147453 /************** Begin file rtree.c *******************************************/
147454 /*
147455 ** 2001 September 15
147456 **
147457 ** The author disclaims copyright to this source code.  In place of
147458 ** a legal notice, here is a blessing:
147459 **
147460 **    May you do good and not evil.
147461 **    May you find forgiveness for yourself and forgive others.
147462 **    May you share freely, never taking more than you give.
147463 **
147464 *************************************************************************
147465 ** This file contains code for implementations of the r-tree and r*-tree
147466 ** algorithms packaged as an SQLite virtual table module.
147467 */
147468 
147469 /*
147470 ** Database Format of R-Tree Tables
147471 ** --------------------------------
147472 **
147473 ** The data structure for a single virtual r-tree table is stored in three
147474 ** native SQLite tables declared as follows. In each case, the '%' character
147475 ** in the table name is replaced with the user-supplied name of the r-tree
147476 ** table.
147477 **
147478 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
147479 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
147480 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
147481 **
147482 ** The data for each node of the r-tree structure is stored in the %_node
147483 ** table. For each node that is not the root node of the r-tree, there is
147484 ** an entry in the %_parent table associating the node with its parent.
147485 ** And for each row of data in the table, there is an entry in the %_rowid
147486 ** table that maps from the entries rowid to the id of the node that it
147487 ** is stored on.
147488 **
147489 ** The root node of an r-tree always exists, even if the r-tree table is
147490 ** empty. The nodeno of the root node is always 1. All other nodes in the
147491 ** table must be the same size as the root node. The content of each node
147492 ** is formatted as follows:
147493 **
147494 **   1. If the node is the root node (node 1), then the first 2 bytes
147495 **      of the node contain the tree depth as a big-endian integer.
147496 **      For non-root nodes, the first 2 bytes are left unused.
147497 **
147498 **   2. The next 2 bytes contain the number of entries currently
147499 **      stored in the node.
147500 **
147501 **   3. The remainder of the node contains the node entries. Each entry
147502 **      consists of a single 8-byte integer followed by an even number
147503 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
147504 **      of a record. For internal nodes it is the node number of a
147505 **      child page.
147506 */
147507 
147508 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
147509 
147510 #ifndef SQLITE_CORE
147511   SQLITE_EXTENSION_INIT1
147512 #else
147513 #endif
147514 
147515 /* #include <string.h> */
147516 /* #include <assert.h> */
147517 /* #include <stdio.h> */
147518 
147519 #ifndef SQLITE_AMALGAMATION
147520 #include "sqlite3rtree.h"
147521 typedef sqlite3_int64 i64;
147522 typedef unsigned char u8;
147523 typedef unsigned short u16;
147524 typedef unsigned int u32;
147525 #endif
147526 
147527 /*  The following macro is used to suppress compiler warnings.
147528 */
147529 #ifndef UNUSED_PARAMETER
147530 # define UNUSED_PARAMETER(x) (void)(x)
147531 #endif
147532 
147533 typedef struct Rtree Rtree;
147534 typedef struct RtreeCursor RtreeCursor;
147535 typedef struct RtreeNode RtreeNode;
147536 typedef struct RtreeCell RtreeCell;
147537 typedef struct RtreeConstraint RtreeConstraint;
147538 typedef struct RtreeMatchArg RtreeMatchArg;
147539 typedef struct RtreeGeomCallback RtreeGeomCallback;
147540 typedef union RtreeCoord RtreeCoord;
147541 typedef struct RtreeSearchPoint RtreeSearchPoint;
147542 
147543 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
147544 #define RTREE_MAX_DIMENSIONS 5
147545 
147546 /* Size of hash table Rtree.aHash. This hash table is not expected to
147547 ** ever contain very many entries, so a fixed number of buckets is
147548 ** used.
147549 */
147550 #define HASHSIZE 97
147551 
147552 /* The xBestIndex method of this virtual table requires an estimate of
147553 ** the number of rows in the virtual table to calculate the costs of
147554 ** various strategies. If possible, this estimate is loaded from the
147555 ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
147556 ** Otherwise, if no sqlite_stat1 entry is available, use
147557 ** RTREE_DEFAULT_ROWEST.
147558 */
147559 #define RTREE_DEFAULT_ROWEST 1048576
147560 #define RTREE_MIN_ROWEST         100
147561 
147562 /*
147563 ** An rtree virtual-table object.
147564 */
147565 struct Rtree {
147566   sqlite3_vtab base;          /* Base class.  Must be first */
147567   sqlite3 *db;                /* Host database connection */
147568   int iNodeSize;              /* Size in bytes of each node in the node table */
147569   u8 nDim;                    /* Number of dimensions */
147570   u8 eCoordType;              /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
147571   u8 nBytesPerCell;           /* Bytes consumed per cell */
147572   int iDepth;                 /* Current depth of the r-tree structure */
147573   char *zDb;                  /* Name of database containing r-tree table */
147574   char *zName;                /* Name of r-tree table */
147575   int nBusy;                  /* Current number of users of this structure */
147576   i64 nRowEst;                /* Estimated number of rows in this table */
147577 
147578   /* List of nodes removed during a CondenseTree operation. List is
147579   ** linked together via the pointer normally used for hash chains -
147580   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
147581   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
147582   */
147583   RtreeNode *pDeleted;
147584   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
147585 
147586   /* Statements to read/write/delete a record from xxx_node */
147587   sqlite3_stmt *pReadNode;
147588   sqlite3_stmt *pWriteNode;
147589   sqlite3_stmt *pDeleteNode;
147590 
147591   /* Statements to read/write/delete a record from xxx_rowid */
147592   sqlite3_stmt *pReadRowid;
147593   sqlite3_stmt *pWriteRowid;
147594   sqlite3_stmt *pDeleteRowid;
147595 
147596   /* Statements to read/write/delete a record from xxx_parent */
147597   sqlite3_stmt *pReadParent;
147598   sqlite3_stmt *pWriteParent;
147599   sqlite3_stmt *pDeleteParent;
147600 
147601   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
147602 };
147603 
147604 /* Possible values for Rtree.eCoordType: */
147605 #define RTREE_COORD_REAL32 0
147606 #define RTREE_COORD_INT32  1
147607 
147608 /*
147609 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
147610 ** only deal with integer coordinates.  No floating point operations
147611 ** will be done.
147612 */
147613 #ifdef SQLITE_RTREE_INT_ONLY
147614   typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
147615   typedef int RtreeValue;                  /* Low accuracy coordinate */
147616 # define RTREE_ZERO 0
147617 #else
147618   typedef double RtreeDValue;              /* High accuracy coordinate */
147619   typedef float RtreeValue;                /* Low accuracy coordinate */
147620 # define RTREE_ZERO 0.0
147621 #endif
147622 
147623 /*
147624 ** When doing a search of an r-tree, instances of the following structure
147625 ** record intermediate results from the tree walk.
147626 **
147627 ** The id is always a node-id.  For iLevel>=1 the id is the node-id of
147628 ** the node that the RtreeSearchPoint represents.  When iLevel==0, however,
147629 ** the id is of the parent node and the cell that RtreeSearchPoint
147630 ** represents is the iCell-th entry in the parent node.
147631 */
147632 struct RtreeSearchPoint {
147633   RtreeDValue rScore;    /* The score for this node.  Smallest goes first. */
147634   sqlite3_int64 id;      /* Node ID */
147635   u8 iLevel;             /* 0=entries.  1=leaf node.  2+ for higher */
147636   u8 eWithin;            /* PARTLY_WITHIN or FULLY_WITHIN */
147637   u8 iCell;              /* Cell index within the node */
147638 };
147639 
147640 /*
147641 ** The minimum number of cells allowed for a node is a third of the
147642 ** maximum. In Gutman's notation:
147643 **
147644 **     m = M/3
147645 **
147646 ** If an R*-tree "Reinsert" operation is required, the same number of
147647 ** cells are removed from the overfull node and reinserted into the tree.
147648 */
147649 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
147650 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
147651 #define RTREE_MAXCELLS 51
147652 
147653 /*
147654 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
147655 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
147656 ** Therefore all non-root nodes must contain at least 3 entries. Since
147657 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
147658 ** 40 or less.
147659 */
147660 #define RTREE_MAX_DEPTH 40
147661 
147662 
147663 /*
147664 ** Number of entries in the cursor RtreeNode cache.  The first entry is
147665 ** used to cache the RtreeNode for RtreeCursor.sPoint.  The remaining
147666 ** entries cache the RtreeNode for the first elements of the priority queue.
147667 */
147668 #define RTREE_CACHE_SZ  5
147669 
147670 /*
147671 ** An rtree cursor object.
147672 */
147673 struct RtreeCursor {
147674   sqlite3_vtab_cursor base;         /* Base class.  Must be first */
147675   u8 atEOF;                         /* True if at end of search */
147676   u8 bPoint;                        /* True if sPoint is valid */
147677   int iStrategy;                    /* Copy of idxNum search parameter */
147678   int nConstraint;                  /* Number of entries in aConstraint */
147679   RtreeConstraint *aConstraint;     /* Search constraints. */
147680   int nPointAlloc;                  /* Number of slots allocated for aPoint[] */
147681   int nPoint;                       /* Number of slots used in aPoint[] */
147682   int mxLevel;                      /* iLevel value for root of the tree */
147683   RtreeSearchPoint *aPoint;         /* Priority queue for search points */
147684   RtreeSearchPoint sPoint;          /* Cached next search point */
147685   RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
147686   u32 anQueue[RTREE_MAX_DEPTH+1];   /* Number of queued entries by iLevel */
147687 };
147688 
147689 /* Return the Rtree of a RtreeCursor */
147690 #define RTREE_OF_CURSOR(X)   ((Rtree*)((X)->base.pVtab))
147691 
147692 /*
147693 ** A coordinate can be either a floating point number or a integer.  All
147694 ** coordinates within a single R-Tree are always of the same time.
147695 */
147696 union RtreeCoord {
147697   RtreeValue f;      /* Floating point value */
147698   int i;             /* Integer value */
147699   u32 u;             /* Unsigned for byte-order conversions */
147700 };
147701 
147702 /*
147703 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
147704 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
147705 ** variable pRtree points to the Rtree structure associated with the
147706 ** RtreeCoord.
147707 */
147708 #ifdef SQLITE_RTREE_INT_ONLY
147709 # define DCOORD(coord) ((RtreeDValue)coord.i)
147710 #else
147711 # define DCOORD(coord) (                           \
147712     (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
147713       ((double)coord.f) :                           \
147714       ((double)coord.i)                             \
147715   )
147716 #endif
147717 
147718 /*
147719 ** A search constraint.
147720 */
147721 struct RtreeConstraint {
147722   int iCoord;                     /* Index of constrained coordinate */
147723   int op;                         /* Constraining operation */
147724   union {
147725     RtreeDValue rValue;             /* Constraint value. */
147726     int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
147727     int (*xQueryFunc)(sqlite3_rtree_query_info*);
147728   } u;
147729   sqlite3_rtree_query_info *pInfo;  /* xGeom and xQueryFunc argument */
147730 };
147731 
147732 /* Possible values for RtreeConstraint.op */
147733 #define RTREE_EQ    0x41  /* A */
147734 #define RTREE_LE    0x42  /* B */
147735 #define RTREE_LT    0x43  /* C */
147736 #define RTREE_GE    0x44  /* D */
147737 #define RTREE_GT    0x45  /* E */
147738 #define RTREE_MATCH 0x46  /* F: Old-style sqlite3_rtree_geometry_callback() */
147739 #define RTREE_QUERY 0x47  /* G: New-style sqlite3_rtree_query_callback() */
147740 
147741 
147742 /*
147743 ** An rtree structure node.
147744 */
147745 struct RtreeNode {
147746   RtreeNode *pParent;         /* Parent node */
147747   i64 iNode;                  /* The node number */
147748   int nRef;                   /* Number of references to this node */
147749   int isDirty;                /* True if the node needs to be written to disk */
147750   u8 *zData;                  /* Content of the node, as should be on disk */
147751   RtreeNode *pNext;           /* Next node in this hash collision chain */
147752 };
147753 
147754 /* Return the number of cells in a node  */
147755 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
147756 
147757 /*
147758 ** A single cell from a node, deserialized
147759 */
147760 struct RtreeCell {
147761   i64 iRowid;                                 /* Node or entry ID */
147762   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];  /* Bounding box coordinates */
147763 };
147764 
147765 
147766 /*
147767 ** This object becomes the sqlite3_user_data() for the SQL functions
147768 ** that are created by sqlite3_rtree_geometry_callback() and
147769 ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
147770 ** operators in order to constrain a search.
147771 **
147772 ** xGeom and xQueryFunc are the callback functions.  Exactly one of
147773 ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
147774 ** SQL function was created using sqlite3_rtree_geometry_callback() or
147775 ** sqlite3_rtree_query_callback().
147776 **
147777 ** This object is deleted automatically by the destructor mechanism in
147778 ** sqlite3_create_function_v2().
147779 */
147780 struct RtreeGeomCallback {
147781   int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
147782   int (*xQueryFunc)(sqlite3_rtree_query_info*);
147783   void (*xDestructor)(void*);
147784   void *pContext;
147785 };
147786 
147787 
147788 /*
147789 ** Value for the first field of every RtreeMatchArg object. The MATCH
147790 ** operator tests that the first field of a blob operand matches this
147791 ** value to avoid operating on invalid blobs (which could cause a segfault).
147792 */
147793 #define RTREE_GEOMETRY_MAGIC 0x891245AB
147794 
147795 /*
147796 ** An instance of this structure (in the form of a BLOB) is returned by
147797 ** the SQL functions that sqlite3_rtree_geometry_callback() and
147798 ** sqlite3_rtree_query_callback() create, and is read as the right-hand
147799 ** operand to the MATCH operator of an R-Tree.
147800 */
147801 struct RtreeMatchArg {
147802   u32 magic;                  /* Always RTREE_GEOMETRY_MAGIC */
147803   RtreeGeomCallback cb;       /* Info about the callback functions */
147804   int nParam;                 /* Number of parameters to the SQL function */
147805   RtreeDValue aParam[1];      /* Values for parameters to the SQL function */
147806 };
147807 
147808 #ifndef MAX
147809 # define MAX(x,y) ((x) < (y) ? (y) : (x))
147810 #endif
147811 #ifndef MIN
147812 # define MIN(x,y) ((x) > (y) ? (y) : (x))
147813 #endif
147814 
147815 /*
147816 ** Functions to deserialize a 16 bit integer, 32 bit real number and
147817 ** 64 bit integer. The deserialized value is returned.
147818 */
147819 static int readInt16(u8 *p){
147820   return (p[0]<<8) + p[1];
147821 }
147822 static void readCoord(u8 *p, RtreeCoord *pCoord){
147823   u32 i = (
147824     (((u32)p[0]) << 24) +
147825     (((u32)p[1]) << 16) +
147826     (((u32)p[2]) <<  8) +
147827     (((u32)p[3]) <<  0)
147828   );
147829   *(u32 *)pCoord = i;
147830 }
147831 static i64 readInt64(u8 *p){
147832   return (
147833     (((i64)p[0]) << 56) +
147834     (((i64)p[1]) << 48) +
147835     (((i64)p[2]) << 40) +
147836     (((i64)p[3]) << 32) +
147837     (((i64)p[4]) << 24) +
147838     (((i64)p[5]) << 16) +
147839     (((i64)p[6]) <<  8) +
147840     (((i64)p[7]) <<  0)
147841   );
147842 }
147843 
147844 /*
147845 ** Functions to serialize a 16 bit integer, 32 bit real number and
147846 ** 64 bit integer. The value returned is the number of bytes written
147847 ** to the argument buffer (always 2, 4 and 8 respectively).
147848 */
147849 static int writeInt16(u8 *p, int i){
147850   p[0] = (i>> 8)&0xFF;
147851   p[1] = (i>> 0)&0xFF;
147852   return 2;
147853 }
147854 static int writeCoord(u8 *p, RtreeCoord *pCoord){
147855   u32 i;
147856   assert( sizeof(RtreeCoord)==4 );
147857   assert( sizeof(u32)==4 );
147858   i = *(u32 *)pCoord;
147859   p[0] = (i>>24)&0xFF;
147860   p[1] = (i>>16)&0xFF;
147861   p[2] = (i>> 8)&0xFF;
147862   p[3] = (i>> 0)&0xFF;
147863   return 4;
147864 }
147865 static int writeInt64(u8 *p, i64 i){
147866   p[0] = (i>>56)&0xFF;
147867   p[1] = (i>>48)&0xFF;
147868   p[2] = (i>>40)&0xFF;
147869   p[3] = (i>>32)&0xFF;
147870   p[4] = (i>>24)&0xFF;
147871   p[5] = (i>>16)&0xFF;
147872   p[6] = (i>> 8)&0xFF;
147873   p[7] = (i>> 0)&0xFF;
147874   return 8;
147875 }
147876 
147877 /*
147878 ** Increment the reference count of node p.
147879 */
147880 static void nodeReference(RtreeNode *p){
147881   if( p ){
147882     p->nRef++;
147883   }
147884 }
147885 
147886 /*
147887 ** Clear the content of node p (set all bytes to 0x00).
147888 */
147889 static void nodeZero(Rtree *pRtree, RtreeNode *p){
147890   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
147891   p->isDirty = 1;
147892 }
147893 
147894 /*
147895 ** Given a node number iNode, return the corresponding key to use
147896 ** in the Rtree.aHash table.
147897 */
147898 static int nodeHash(i64 iNode){
147899   return iNode % HASHSIZE;
147900 }
147901 
147902 /*
147903 ** Search the node hash table for node iNode. If found, return a pointer
147904 ** to it. Otherwise, return 0.
147905 */
147906 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
147907   RtreeNode *p;
147908   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
147909   return p;
147910 }
147911 
147912 /*
147913 ** Add node pNode to the node hash table.
147914 */
147915 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
147916   int iHash;
147917   assert( pNode->pNext==0 );
147918   iHash = nodeHash(pNode->iNode);
147919   pNode->pNext = pRtree->aHash[iHash];
147920   pRtree->aHash[iHash] = pNode;
147921 }
147922 
147923 /*
147924 ** Remove node pNode from the node hash table.
147925 */
147926 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
147927   RtreeNode **pp;
147928   if( pNode->iNode!=0 ){
147929     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
147930     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
147931     *pp = pNode->pNext;
147932     pNode->pNext = 0;
147933   }
147934 }
147935 
147936 /*
147937 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
147938 ** indicating that node has not yet been assigned a node number. It is
147939 ** assigned a node number when nodeWrite() is called to write the
147940 ** node contents out to the database.
147941 */
147942 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
147943   RtreeNode *pNode;
147944   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
147945   if( pNode ){
147946     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
147947     pNode->zData = (u8 *)&pNode[1];
147948     pNode->nRef = 1;
147949     pNode->pParent = pParent;
147950     pNode->isDirty = 1;
147951     nodeReference(pParent);
147952   }
147953   return pNode;
147954 }
147955 
147956 /*
147957 ** Obtain a reference to an r-tree node.
147958 */
147959 static int nodeAcquire(
147960   Rtree *pRtree,             /* R-tree structure */
147961   i64 iNode,                 /* Node number to load */
147962   RtreeNode *pParent,        /* Either the parent node or NULL */
147963   RtreeNode **ppNode         /* OUT: Acquired node */
147964 ){
147965   int rc;
147966   int rc2 = SQLITE_OK;
147967   RtreeNode *pNode;
147968 
147969   /* Check if the requested node is already in the hash table. If so,
147970   ** increase its reference count and return it.
147971   */
147972   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
147973     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
147974     if( pParent && !pNode->pParent ){
147975       nodeReference(pParent);
147976       pNode->pParent = pParent;
147977     }
147978     pNode->nRef++;
147979     *ppNode = pNode;
147980     return SQLITE_OK;
147981   }
147982 
147983   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
147984   rc = sqlite3_step(pRtree->pReadNode);
147985   if( rc==SQLITE_ROW ){
147986     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
147987     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
147988       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
147989       if( !pNode ){
147990         rc2 = SQLITE_NOMEM;
147991       }else{
147992         pNode->pParent = pParent;
147993         pNode->zData = (u8 *)&pNode[1];
147994         pNode->nRef = 1;
147995         pNode->iNode = iNode;
147996         pNode->isDirty = 0;
147997         pNode->pNext = 0;
147998         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
147999         nodeReference(pParent);
148000       }
148001     }
148002   }
148003   rc = sqlite3_reset(pRtree->pReadNode);
148004   if( rc==SQLITE_OK ) rc = rc2;
148005 
148006   /* If the root node was just loaded, set pRtree->iDepth to the height
148007   ** of the r-tree structure. A height of zero means all data is stored on
148008   ** the root node. A height of one means the children of the root node
148009   ** are the leaves, and so on. If the depth as specified on the root node
148010   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
148011   */
148012   if( pNode && iNode==1 ){
148013     pRtree->iDepth = readInt16(pNode->zData);
148014     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
148015       rc = SQLITE_CORRUPT_VTAB;
148016     }
148017   }
148018 
148019   /* If no error has occurred so far, check if the "number of entries"
148020   ** field on the node is too large. If so, set the return code to
148021   ** SQLITE_CORRUPT_VTAB.
148022   */
148023   if( pNode && rc==SQLITE_OK ){
148024     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
148025       rc = SQLITE_CORRUPT_VTAB;
148026     }
148027   }
148028 
148029   if( rc==SQLITE_OK ){
148030     if( pNode!=0 ){
148031       nodeHashInsert(pRtree, pNode);
148032     }else{
148033       rc = SQLITE_CORRUPT_VTAB;
148034     }
148035     *ppNode = pNode;
148036   }else{
148037     sqlite3_free(pNode);
148038     *ppNode = 0;
148039   }
148040 
148041   return rc;
148042 }
148043 
148044 /*
148045 ** Overwrite cell iCell of node pNode with the contents of pCell.
148046 */
148047 static void nodeOverwriteCell(
148048   Rtree *pRtree,             /* The overall R-Tree */
148049   RtreeNode *pNode,          /* The node into which the cell is to be written */
148050   RtreeCell *pCell,          /* The cell to write */
148051   int iCell                  /* Index into pNode into which pCell is written */
148052 ){
148053   int ii;
148054   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
148055   p += writeInt64(p, pCell->iRowid);
148056   for(ii=0; ii<(pRtree->nDim*2); ii++){
148057     p += writeCoord(p, &pCell->aCoord[ii]);
148058   }
148059   pNode->isDirty = 1;
148060 }
148061 
148062 /*
148063 ** Remove the cell with index iCell from node pNode.
148064 */
148065 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
148066   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
148067   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
148068   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
148069   memmove(pDst, pSrc, nByte);
148070   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
148071   pNode->isDirty = 1;
148072 }
148073 
148074 /*
148075 ** Insert the contents of cell pCell into node pNode. If the insert
148076 ** is successful, return SQLITE_OK.
148077 **
148078 ** If there is not enough free space in pNode, return SQLITE_FULL.
148079 */
148080 static int nodeInsertCell(
148081   Rtree *pRtree,                /* The overall R-Tree */
148082   RtreeNode *pNode,             /* Write new cell into this node */
148083   RtreeCell *pCell              /* The cell to be inserted */
148084 ){
148085   int nCell;                    /* Current number of cells in pNode */
148086   int nMaxCell;                 /* Maximum number of cells for pNode */
148087 
148088   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
148089   nCell = NCELL(pNode);
148090 
148091   assert( nCell<=nMaxCell );
148092   if( nCell<nMaxCell ){
148093     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
148094     writeInt16(&pNode->zData[2], nCell+1);
148095     pNode->isDirty = 1;
148096   }
148097 
148098   return (nCell==nMaxCell);
148099 }
148100 
148101 /*
148102 ** If the node is dirty, write it out to the database.
148103 */
148104 static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
148105   int rc = SQLITE_OK;
148106   if( pNode->isDirty ){
148107     sqlite3_stmt *p = pRtree->pWriteNode;
148108     if( pNode->iNode ){
148109       sqlite3_bind_int64(p, 1, pNode->iNode);
148110     }else{
148111       sqlite3_bind_null(p, 1);
148112     }
148113     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
148114     sqlite3_step(p);
148115     pNode->isDirty = 0;
148116     rc = sqlite3_reset(p);
148117     if( pNode->iNode==0 && rc==SQLITE_OK ){
148118       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
148119       nodeHashInsert(pRtree, pNode);
148120     }
148121   }
148122   return rc;
148123 }
148124 
148125 /*
148126 ** Release a reference to a node. If the node is dirty and the reference
148127 ** count drops to zero, the node data is written to the database.
148128 */
148129 static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
148130   int rc = SQLITE_OK;
148131   if( pNode ){
148132     assert( pNode->nRef>0 );
148133     pNode->nRef--;
148134     if( pNode->nRef==0 ){
148135       if( pNode->iNode==1 ){
148136         pRtree->iDepth = -1;
148137       }
148138       if( pNode->pParent ){
148139         rc = nodeRelease(pRtree, pNode->pParent);
148140       }
148141       if( rc==SQLITE_OK ){
148142         rc = nodeWrite(pRtree, pNode);
148143       }
148144       nodeHashDelete(pRtree, pNode);
148145       sqlite3_free(pNode);
148146     }
148147   }
148148   return rc;
148149 }
148150 
148151 /*
148152 ** Return the 64-bit integer value associated with cell iCell of
148153 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
148154 ** an internal node, then the 64-bit integer is a child page number.
148155 */
148156 static i64 nodeGetRowid(
148157   Rtree *pRtree,       /* The overall R-Tree */
148158   RtreeNode *pNode,    /* The node from which to extract the ID */
148159   int iCell            /* The cell index from which to extract the ID */
148160 ){
148161   assert( iCell<NCELL(pNode) );
148162   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
148163 }
148164 
148165 /*
148166 ** Return coordinate iCoord from cell iCell in node pNode.
148167 */
148168 static void nodeGetCoord(
148169   Rtree *pRtree,               /* The overall R-Tree */
148170   RtreeNode *pNode,            /* The node from which to extract a coordinate */
148171   int iCell,                   /* The index of the cell within the node */
148172   int iCoord,                  /* Which coordinate to extract */
148173   RtreeCoord *pCoord           /* OUT: Space to write result to */
148174 ){
148175   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
148176 }
148177 
148178 /*
148179 ** Deserialize cell iCell of node pNode. Populate the structure pointed
148180 ** to by pCell with the results.
148181 */
148182 static void nodeGetCell(
148183   Rtree *pRtree,               /* The overall R-Tree */
148184   RtreeNode *pNode,            /* The node containing the cell to be read */
148185   int iCell,                   /* Index of the cell within the node */
148186   RtreeCell *pCell             /* OUT: Write the cell contents here */
148187 ){
148188   u8 *pData;
148189   u8 *pEnd;
148190   RtreeCoord *pCoord;
148191   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
148192   pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
148193   pEnd = pData + pRtree->nDim*8;
148194   pCoord = pCell->aCoord;
148195   for(; pData<pEnd; pData+=4, pCoord++){
148196     readCoord(pData, pCoord);
148197   }
148198 }
148199 
148200 
148201 /* Forward declaration for the function that does the work of
148202 ** the virtual table module xCreate() and xConnect() methods.
148203 */
148204 static int rtreeInit(
148205   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
148206 );
148207 
148208 /*
148209 ** Rtree virtual table module xCreate method.
148210 */
148211 static int rtreeCreate(
148212   sqlite3 *db,
148213   void *pAux,
148214   int argc, const char *const*argv,
148215   sqlite3_vtab **ppVtab,
148216   char **pzErr
148217 ){
148218   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
148219 }
148220 
148221 /*
148222 ** Rtree virtual table module xConnect method.
148223 */
148224 static int rtreeConnect(
148225   sqlite3 *db,
148226   void *pAux,
148227   int argc, const char *const*argv,
148228   sqlite3_vtab **ppVtab,
148229   char **pzErr
148230 ){
148231   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
148232 }
148233 
148234 /*
148235 ** Increment the r-tree reference count.
148236 */
148237 static void rtreeReference(Rtree *pRtree){
148238   pRtree->nBusy++;
148239 }
148240 
148241 /*
148242 ** Decrement the r-tree reference count. When the reference count reaches
148243 ** zero the structure is deleted.
148244 */
148245 static void rtreeRelease(Rtree *pRtree){
148246   pRtree->nBusy--;
148247   if( pRtree->nBusy==0 ){
148248     sqlite3_finalize(pRtree->pReadNode);
148249     sqlite3_finalize(pRtree->pWriteNode);
148250     sqlite3_finalize(pRtree->pDeleteNode);
148251     sqlite3_finalize(pRtree->pReadRowid);
148252     sqlite3_finalize(pRtree->pWriteRowid);
148253     sqlite3_finalize(pRtree->pDeleteRowid);
148254     sqlite3_finalize(pRtree->pReadParent);
148255     sqlite3_finalize(pRtree->pWriteParent);
148256     sqlite3_finalize(pRtree->pDeleteParent);
148257     sqlite3_free(pRtree);
148258   }
148259 }
148260 
148261 /*
148262 ** Rtree virtual table module xDisconnect method.
148263 */
148264 static int rtreeDisconnect(sqlite3_vtab *pVtab){
148265   rtreeRelease((Rtree *)pVtab);
148266   return SQLITE_OK;
148267 }
148268 
148269 /*
148270 ** Rtree virtual table module xDestroy method.
148271 */
148272 static int rtreeDestroy(sqlite3_vtab *pVtab){
148273   Rtree *pRtree = (Rtree *)pVtab;
148274   int rc;
148275   char *zCreate = sqlite3_mprintf(
148276     "DROP TABLE '%q'.'%q_node';"
148277     "DROP TABLE '%q'.'%q_rowid';"
148278     "DROP TABLE '%q'.'%q_parent';",
148279     pRtree->zDb, pRtree->zName,
148280     pRtree->zDb, pRtree->zName,
148281     pRtree->zDb, pRtree->zName
148282   );
148283   if( !zCreate ){
148284     rc = SQLITE_NOMEM;
148285   }else{
148286     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
148287     sqlite3_free(zCreate);
148288   }
148289   if( rc==SQLITE_OK ){
148290     rtreeRelease(pRtree);
148291   }
148292 
148293   return rc;
148294 }
148295 
148296 /*
148297 ** Rtree virtual table module xOpen method.
148298 */
148299 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
148300   int rc = SQLITE_NOMEM;
148301   RtreeCursor *pCsr;
148302 
148303   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
148304   if( pCsr ){
148305     memset(pCsr, 0, sizeof(RtreeCursor));
148306     pCsr->base.pVtab = pVTab;
148307     rc = SQLITE_OK;
148308   }
148309   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
148310 
148311   return rc;
148312 }
148313 
148314 
148315 /*
148316 ** Free the RtreeCursor.aConstraint[] array and its contents.
148317 */
148318 static void freeCursorConstraints(RtreeCursor *pCsr){
148319   if( pCsr->aConstraint ){
148320     int i;                        /* Used to iterate through constraint array */
148321     for(i=0; i<pCsr->nConstraint; i++){
148322       sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
148323       if( pInfo ){
148324         if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
148325         sqlite3_free(pInfo);
148326       }
148327     }
148328     sqlite3_free(pCsr->aConstraint);
148329     pCsr->aConstraint = 0;
148330   }
148331 }
148332 
148333 /*
148334 ** Rtree virtual table module xClose method.
148335 */
148336 static int rtreeClose(sqlite3_vtab_cursor *cur){
148337   Rtree *pRtree = (Rtree *)(cur->pVtab);
148338   int ii;
148339   RtreeCursor *pCsr = (RtreeCursor *)cur;
148340   freeCursorConstraints(pCsr);
148341   sqlite3_free(pCsr->aPoint);
148342   for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
148343   sqlite3_free(pCsr);
148344   return SQLITE_OK;
148345 }
148346 
148347 /*
148348 ** Rtree virtual table module xEof method.
148349 **
148350 ** Return non-zero if the cursor does not currently point to a valid
148351 ** record (i.e if the scan has finished), or zero otherwise.
148352 */
148353 static int rtreeEof(sqlite3_vtab_cursor *cur){
148354   RtreeCursor *pCsr = (RtreeCursor *)cur;
148355   return pCsr->atEOF;
148356 }
148357 
148358 /*
148359 ** Convert raw bits from the on-disk RTree record into a coordinate value.
148360 ** The on-disk format is big-endian and needs to be converted for little-
148361 ** endian platforms.  The on-disk record stores integer coordinates if
148362 ** eInt is true and it stores 32-bit floating point records if eInt is
148363 ** false.  a[] is the four bytes of the on-disk record to be decoded.
148364 ** Store the results in "r".
148365 **
148366 ** There are three versions of this macro, one each for little-endian and
148367 ** big-endian processors and a third generic implementation.  The endian-
148368 ** specific implementations are much faster and are preferred if the
148369 ** processor endianness is known at compile-time.  The SQLITE_BYTEORDER
148370 ** macro is part of sqliteInt.h and hence the endian-specific
148371 ** implementation will only be used if this module is compiled as part
148372 ** of the amalgamation.
148373 */
148374 #if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
148375 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
148376     RtreeCoord c;    /* Coordinate decoded */                   \
148377     memcpy(&c.u,a,4);                                           \
148378     c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)|                   \
148379           ((c.u&0xff)<<24)|((c.u&0xff00)<<8);                   \
148380     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
148381 }
148382 #elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
148383 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
148384     RtreeCoord c;    /* Coordinate decoded */                   \
148385     memcpy(&c.u,a,4);                                           \
148386     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
148387 }
148388 #else
148389 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
148390     RtreeCoord c;    /* Coordinate decoded */                   \
148391     c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16)                     \
148392            +((u32)a[2]<<8) + a[3];                              \
148393     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
148394 }
148395 #endif
148396 
148397 /*
148398 ** Check the RTree node or entry given by pCellData and p against the MATCH
148399 ** constraint pConstraint.
148400 */
148401 static int rtreeCallbackConstraint(
148402   RtreeConstraint *pConstraint,  /* The constraint to test */
148403   int eInt,                      /* True if RTree holding integer coordinates */
148404   u8 *pCellData,                 /* Raw cell content */
148405   RtreeSearchPoint *pSearch,     /* Container of this cell */
148406   sqlite3_rtree_dbl *prScore,    /* OUT: score for the cell */
148407   int *peWithin                  /* OUT: visibility of the cell */
148408 ){
148409   int i;                                                /* Loop counter */
148410   sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
148411   int nCoord = pInfo->nCoord;                           /* No. of coordinates */
148412   int rc;                                             /* Callback return code */
148413   sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2];   /* Decoded coordinates */
148414 
148415   assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
148416   assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
148417 
148418   if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
148419     pInfo->iRowid = readInt64(pCellData);
148420   }
148421   pCellData += 8;
148422   for(i=0; i<nCoord; i++, pCellData += 4){
148423     RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
148424   }
148425   if( pConstraint->op==RTREE_MATCH ){
148426     rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
148427                               nCoord, aCoord, &i);
148428     if( i==0 ) *peWithin = NOT_WITHIN;
148429     *prScore = RTREE_ZERO;
148430   }else{
148431     pInfo->aCoord = aCoord;
148432     pInfo->iLevel = pSearch->iLevel - 1;
148433     pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
148434     pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
148435     rc = pConstraint->u.xQueryFunc(pInfo);
148436     if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
148437     if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
148438       *prScore = pInfo->rScore;
148439     }
148440   }
148441   return rc;
148442 }
148443 
148444 /*
148445 ** Check the internal RTree node given by pCellData against constraint p.
148446 ** If this constraint cannot be satisfied by any child within the node,
148447 ** set *peWithin to NOT_WITHIN.
148448 */
148449 static void rtreeNonleafConstraint(
148450   RtreeConstraint *p,        /* The constraint to test */
148451   int eInt,                  /* True if RTree holds integer coordinates */
148452   u8 *pCellData,             /* Raw cell content as appears on disk */
148453   int *peWithin              /* Adjust downward, as appropriate */
148454 ){
148455   sqlite3_rtree_dbl val;     /* Coordinate value convert to a double */
148456 
148457   /* p->iCoord might point to either a lower or upper bound coordinate
148458   ** in a coordinate pair.  But make pCellData point to the lower bound.
148459   */
148460   pCellData += 8 + 4*(p->iCoord&0xfe);
148461 
148462   assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
148463       || p->op==RTREE_GT || p->op==RTREE_EQ );
148464   switch( p->op ){
148465     case RTREE_LE:
148466     case RTREE_LT:
148467     case RTREE_EQ:
148468       RTREE_DECODE_COORD(eInt, pCellData, val);
148469       /* val now holds the lower bound of the coordinate pair */
148470       if( p->u.rValue>=val ) return;
148471       if( p->op!=RTREE_EQ ) break;  /* RTREE_LE and RTREE_LT end here */
148472       /* Fall through for the RTREE_EQ case */
148473 
148474     default: /* RTREE_GT or RTREE_GE,  or fallthrough of RTREE_EQ */
148475       pCellData += 4;
148476       RTREE_DECODE_COORD(eInt, pCellData, val);
148477       /* val now holds the upper bound of the coordinate pair */
148478       if( p->u.rValue<=val ) return;
148479   }
148480   *peWithin = NOT_WITHIN;
148481 }
148482 
148483 /*
148484 ** Check the leaf RTree cell given by pCellData against constraint p.
148485 ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
148486 ** If the constraint is satisfied, leave *peWithin unchanged.
148487 **
148488 ** The constraint is of the form:  xN op $val
148489 **
148490 ** The op is given by p->op.  The xN is p->iCoord-th coordinate in
148491 ** pCellData.  $val is given by p->u.rValue.
148492 */
148493 static void rtreeLeafConstraint(
148494   RtreeConstraint *p,        /* The constraint to test */
148495   int eInt,                  /* True if RTree holds integer coordinates */
148496   u8 *pCellData,             /* Raw cell content as appears on disk */
148497   int *peWithin              /* Adjust downward, as appropriate */
148498 ){
148499   RtreeDValue xN;      /* Coordinate value converted to a double */
148500 
148501   assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
148502       || p->op==RTREE_GT || p->op==RTREE_EQ );
148503   pCellData += 8 + p->iCoord*4;
148504   RTREE_DECODE_COORD(eInt, pCellData, xN);
148505   switch( p->op ){
148506     case RTREE_LE: if( xN <= p->u.rValue ) return;  break;
148507     case RTREE_LT: if( xN <  p->u.rValue ) return;  break;
148508     case RTREE_GE: if( xN >= p->u.rValue ) return;  break;
148509     case RTREE_GT: if( xN >  p->u.rValue ) return;  break;
148510     default:       if( xN == p->u.rValue ) return;  break;
148511   }
148512   *peWithin = NOT_WITHIN;
148513 }
148514 
148515 /*
148516 ** One of the cells in node pNode is guaranteed to have a 64-bit
148517 ** integer value equal to iRowid. Return the index of this cell.
148518 */
148519 static int nodeRowidIndex(
148520   Rtree *pRtree,
148521   RtreeNode *pNode,
148522   i64 iRowid,
148523   int *piIndex
148524 ){
148525   int ii;
148526   int nCell = NCELL(pNode);
148527   assert( nCell<200 );
148528   for(ii=0; ii<nCell; ii++){
148529     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
148530       *piIndex = ii;
148531       return SQLITE_OK;
148532     }
148533   }
148534   return SQLITE_CORRUPT_VTAB;
148535 }
148536 
148537 /*
148538 ** Return the index of the cell containing a pointer to node pNode
148539 ** in its parent. If pNode is the root node, return -1.
148540 */
148541 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
148542   RtreeNode *pParent = pNode->pParent;
148543   if( pParent ){
148544     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
148545   }
148546   *piIndex = -1;
148547   return SQLITE_OK;
148548 }
148549 
148550 /*
148551 ** Compare two search points.  Return negative, zero, or positive if the first
148552 ** is less than, equal to, or greater than the second.
148553 **
148554 ** The rScore is the primary key.  Smaller rScore values come first.
148555 ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
148556 ** iLevel values coming first.  In this way, if rScore is the same for all
148557 ** SearchPoints, then iLevel becomes the deciding factor and the result
148558 ** is a depth-first search, which is the desired default behavior.
148559 */
148560 static int rtreeSearchPointCompare(
148561   const RtreeSearchPoint *pA,
148562   const RtreeSearchPoint *pB
148563 ){
148564   if( pA->rScore<pB->rScore ) return -1;
148565   if( pA->rScore>pB->rScore ) return +1;
148566   if( pA->iLevel<pB->iLevel ) return -1;
148567   if( pA->iLevel>pB->iLevel ) return +1;
148568   return 0;
148569 }
148570 
148571 /*
148572 ** Interchange to search points in a cursor.
148573 */
148574 static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
148575   RtreeSearchPoint t = p->aPoint[i];
148576   assert( i<j );
148577   p->aPoint[i] = p->aPoint[j];
148578   p->aPoint[j] = t;
148579   i++; j++;
148580   if( i<RTREE_CACHE_SZ ){
148581     if( j>=RTREE_CACHE_SZ ){
148582       nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
148583       p->aNode[i] = 0;
148584     }else{
148585       RtreeNode *pTemp = p->aNode[i];
148586       p->aNode[i] = p->aNode[j];
148587       p->aNode[j] = pTemp;
148588     }
148589   }
148590 }
148591 
148592 /*
148593 ** Return the search point with the lowest current score.
148594 */
148595 static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
148596   return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
148597 }
148598 
148599 /*
148600 ** Get the RtreeNode for the search point with the lowest score.
148601 */
148602 static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
148603   sqlite3_int64 id;
148604   int ii = 1 - pCur->bPoint;
148605   assert( ii==0 || ii==1 );
148606   assert( pCur->bPoint || pCur->nPoint );
148607   if( pCur->aNode[ii]==0 ){
148608     assert( pRC!=0 );
148609     id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
148610     *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
148611   }
148612   return pCur->aNode[ii];
148613 }
148614 
148615 /*
148616 ** Push a new element onto the priority queue
148617 */
148618 static RtreeSearchPoint *rtreeEnqueue(
148619   RtreeCursor *pCur,    /* The cursor */
148620   RtreeDValue rScore,   /* Score for the new search point */
148621   u8 iLevel             /* Level for the new search point */
148622 ){
148623   int i, j;
148624   RtreeSearchPoint *pNew;
148625   if( pCur->nPoint>=pCur->nPointAlloc ){
148626     int nNew = pCur->nPointAlloc*2 + 8;
148627     pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
148628     if( pNew==0 ) return 0;
148629     pCur->aPoint = pNew;
148630     pCur->nPointAlloc = nNew;
148631   }
148632   i = pCur->nPoint++;
148633   pNew = pCur->aPoint + i;
148634   pNew->rScore = rScore;
148635   pNew->iLevel = iLevel;
148636   assert( iLevel>=0 && iLevel<=RTREE_MAX_DEPTH );
148637   while( i>0 ){
148638     RtreeSearchPoint *pParent;
148639     j = (i-1)/2;
148640     pParent = pCur->aPoint + j;
148641     if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
148642     rtreeSearchPointSwap(pCur, j, i);
148643     i = j;
148644     pNew = pParent;
148645   }
148646   return pNew;
148647 }
148648 
148649 /*
148650 ** Allocate a new RtreeSearchPoint and return a pointer to it.  Return
148651 ** NULL if malloc fails.
148652 */
148653 static RtreeSearchPoint *rtreeSearchPointNew(
148654   RtreeCursor *pCur,    /* The cursor */
148655   RtreeDValue rScore,   /* Score for the new search point */
148656   u8 iLevel             /* Level for the new search point */
148657 ){
148658   RtreeSearchPoint *pNew, *pFirst;
148659   pFirst = rtreeSearchPointFirst(pCur);
148660   pCur->anQueue[iLevel]++;
148661   if( pFirst==0
148662    || pFirst->rScore>rScore
148663    || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
148664   ){
148665     if( pCur->bPoint ){
148666       int ii;
148667       pNew = rtreeEnqueue(pCur, rScore, iLevel);
148668       if( pNew==0 ) return 0;
148669       ii = (int)(pNew - pCur->aPoint) + 1;
148670       if( ii<RTREE_CACHE_SZ ){
148671         assert( pCur->aNode[ii]==0 );
148672         pCur->aNode[ii] = pCur->aNode[0];
148673        }else{
148674         nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
148675       }
148676       pCur->aNode[0] = 0;
148677       *pNew = pCur->sPoint;
148678     }
148679     pCur->sPoint.rScore = rScore;
148680     pCur->sPoint.iLevel = iLevel;
148681     pCur->bPoint = 1;
148682     return &pCur->sPoint;
148683   }else{
148684     return rtreeEnqueue(pCur, rScore, iLevel);
148685   }
148686 }
148687 
148688 #if 0
148689 /* Tracing routines for the RtreeSearchPoint queue */
148690 static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
148691   if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
148692   printf(" %d.%05lld.%02d %g %d",
148693     p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
148694   );
148695   idx++;
148696   if( idx<RTREE_CACHE_SZ ){
148697     printf(" %p\n", pCur->aNode[idx]);
148698   }else{
148699     printf("\n");
148700   }
148701 }
148702 static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
148703   int ii;
148704   printf("=== %9s ", zPrefix);
148705   if( pCur->bPoint ){
148706     tracePoint(&pCur->sPoint, -1, pCur);
148707   }
148708   for(ii=0; ii<pCur->nPoint; ii++){
148709     if( ii>0 || pCur->bPoint ) printf("              ");
148710     tracePoint(&pCur->aPoint[ii], ii, pCur);
148711   }
148712 }
148713 # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
148714 #else
148715 # define RTREE_QUEUE_TRACE(A,B)   /* no-op */
148716 #endif
148717 
148718 /* Remove the search point with the lowest current score.
148719 */
148720 static void rtreeSearchPointPop(RtreeCursor *p){
148721   int i, j, k, n;
148722   i = 1 - p->bPoint;
148723   assert( i==0 || i==1 );
148724   if( p->aNode[i] ){
148725     nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
148726     p->aNode[i] = 0;
148727   }
148728   if( p->bPoint ){
148729     p->anQueue[p->sPoint.iLevel]--;
148730     p->bPoint = 0;
148731   }else if( p->nPoint ){
148732     p->anQueue[p->aPoint[0].iLevel]--;
148733     n = --p->nPoint;
148734     p->aPoint[0] = p->aPoint[n];
148735     if( n<RTREE_CACHE_SZ-1 ){
148736       p->aNode[1] = p->aNode[n+1];
148737       p->aNode[n+1] = 0;
148738     }
148739     i = 0;
148740     while( (j = i*2+1)<n ){
148741       k = j+1;
148742       if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
148743         if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
148744           rtreeSearchPointSwap(p, i, k);
148745           i = k;
148746         }else{
148747           break;
148748         }
148749       }else{
148750         if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
148751           rtreeSearchPointSwap(p, i, j);
148752           i = j;
148753         }else{
148754           break;
148755         }
148756       }
148757     }
148758   }
148759 }
148760 
148761 
148762 /*
148763 ** Continue the search on cursor pCur until the front of the queue
148764 ** contains an entry suitable for returning as a result-set row,
148765 ** or until the RtreeSearchPoint queue is empty, indicating that the
148766 ** query has completed.
148767 */
148768 static int rtreeStepToLeaf(RtreeCursor *pCur){
148769   RtreeSearchPoint *p;
148770   Rtree *pRtree = RTREE_OF_CURSOR(pCur);
148771   RtreeNode *pNode;
148772   int eWithin;
148773   int rc = SQLITE_OK;
148774   int nCell;
148775   int nConstraint = pCur->nConstraint;
148776   int ii;
148777   int eInt;
148778   RtreeSearchPoint x;
148779 
148780   eInt = pRtree->eCoordType==RTREE_COORD_INT32;
148781   while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
148782     pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
148783     if( rc ) return rc;
148784     nCell = NCELL(pNode);
148785     assert( nCell<200 );
148786     while( p->iCell<nCell ){
148787       sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
148788       u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
148789       eWithin = FULLY_WITHIN;
148790       for(ii=0; ii<nConstraint; ii++){
148791         RtreeConstraint *pConstraint = pCur->aConstraint + ii;
148792         if( pConstraint->op>=RTREE_MATCH ){
148793           rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
148794                                        &rScore, &eWithin);
148795           if( rc ) return rc;
148796         }else if( p->iLevel==1 ){
148797           rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
148798         }else{
148799           rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
148800         }
148801         if( eWithin==NOT_WITHIN ) break;
148802       }
148803       p->iCell++;
148804       if( eWithin==NOT_WITHIN ) continue;
148805       x.iLevel = p->iLevel - 1;
148806       if( x.iLevel ){
148807         x.id = readInt64(pCellData);
148808         x.iCell = 0;
148809       }else{
148810         x.id = p->id;
148811         x.iCell = p->iCell - 1;
148812       }
148813       if( p->iCell>=nCell ){
148814         RTREE_QUEUE_TRACE(pCur, "POP-S:");
148815         rtreeSearchPointPop(pCur);
148816       }
148817       if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
148818       p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
148819       if( p==0 ) return SQLITE_NOMEM;
148820       p->eWithin = eWithin;
148821       p->id = x.id;
148822       p->iCell = x.iCell;
148823       RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
148824       break;
148825     }
148826     if( p->iCell>=nCell ){
148827       RTREE_QUEUE_TRACE(pCur, "POP-Se:");
148828       rtreeSearchPointPop(pCur);
148829     }
148830   }
148831   pCur->atEOF = p==0;
148832   return SQLITE_OK;
148833 }
148834 
148835 /*
148836 ** Rtree virtual table module xNext method.
148837 */
148838 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
148839   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
148840   int rc = SQLITE_OK;
148841 
148842   /* Move to the next entry that matches the configured constraints. */
148843   RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
148844   rtreeSearchPointPop(pCsr);
148845   rc = rtreeStepToLeaf(pCsr);
148846   return rc;
148847 }
148848 
148849 /*
148850 ** Rtree virtual table module xRowid method.
148851 */
148852 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
148853   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
148854   RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
148855   int rc = SQLITE_OK;
148856   RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
148857   if( rc==SQLITE_OK && p ){
148858     *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
148859   }
148860   return rc;
148861 }
148862 
148863 /*
148864 ** Rtree virtual table module xColumn method.
148865 */
148866 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
148867   Rtree *pRtree = (Rtree *)cur->pVtab;
148868   RtreeCursor *pCsr = (RtreeCursor *)cur;
148869   RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
148870   RtreeCoord c;
148871   int rc = SQLITE_OK;
148872   RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
148873 
148874   if( rc ) return rc;
148875   if( p==0 ) return SQLITE_OK;
148876   if( i==0 ){
148877     sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
148878   }else{
148879     if( rc ) return rc;
148880     nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
148881 #ifndef SQLITE_RTREE_INT_ONLY
148882     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
148883       sqlite3_result_double(ctx, c.f);
148884     }else
148885 #endif
148886     {
148887       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
148888       sqlite3_result_int(ctx, c.i);
148889     }
148890   }
148891   return SQLITE_OK;
148892 }
148893 
148894 /*
148895 ** Use nodeAcquire() to obtain the leaf node containing the record with
148896 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
148897 ** return SQLITE_OK. If there is no such record in the table, set
148898 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
148899 ** to zero and return an SQLite error code.
148900 */
148901 static int findLeafNode(
148902   Rtree *pRtree,              /* RTree to search */
148903   i64 iRowid,                 /* The rowid searching for */
148904   RtreeNode **ppLeaf,         /* Write the node here */
148905   sqlite3_int64 *piNode       /* Write the node-id here */
148906 ){
148907   int rc;
148908   *ppLeaf = 0;
148909   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
148910   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
148911     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
148912     if( piNode ) *piNode = iNode;
148913     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
148914     sqlite3_reset(pRtree->pReadRowid);
148915   }else{
148916     rc = sqlite3_reset(pRtree->pReadRowid);
148917   }
148918   return rc;
148919 }
148920 
148921 /*
148922 ** This function is called to configure the RtreeConstraint object passed
148923 ** as the second argument for a MATCH constraint. The value passed as the
148924 ** first argument to this function is the right-hand operand to the MATCH
148925 ** operator.
148926 */
148927 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
148928   RtreeMatchArg *pBlob;              /* BLOB returned by geometry function */
148929   sqlite3_rtree_query_info *pInfo;   /* Callback information */
148930   int nBlob;                         /* Size of the geometry function blob */
148931   int nExpected;                     /* Expected size of the BLOB */
148932 
148933   /* Check that value is actually a blob. */
148934   if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
148935 
148936   /* Check that the blob is roughly the right size. */
148937   nBlob = sqlite3_value_bytes(pValue);
148938   if( nBlob<(int)sizeof(RtreeMatchArg)
148939    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
148940   ){
148941     return SQLITE_ERROR;
148942   }
148943 
148944   pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
148945   if( !pInfo ) return SQLITE_NOMEM;
148946   memset(pInfo, 0, sizeof(*pInfo));
148947   pBlob = (RtreeMatchArg*)&pInfo[1];
148948 
148949   memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
148950   nExpected = (int)(sizeof(RtreeMatchArg) +
148951                     (pBlob->nParam-1)*sizeof(RtreeDValue));
148952   if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
148953     sqlite3_free(pInfo);
148954     return SQLITE_ERROR;
148955   }
148956   pInfo->pContext = pBlob->cb.pContext;
148957   pInfo->nParam = pBlob->nParam;
148958   pInfo->aParam = pBlob->aParam;
148959 
148960   if( pBlob->cb.xGeom ){
148961     pCons->u.xGeom = pBlob->cb.xGeom;
148962   }else{
148963     pCons->op = RTREE_QUERY;
148964     pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
148965   }
148966   pCons->pInfo = pInfo;
148967   return SQLITE_OK;
148968 }
148969 
148970 /*
148971 ** Rtree virtual table module xFilter method.
148972 */
148973 static int rtreeFilter(
148974   sqlite3_vtab_cursor *pVtabCursor,
148975   int idxNum, const char *idxStr,
148976   int argc, sqlite3_value **argv
148977 ){
148978   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
148979   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
148980   RtreeNode *pRoot = 0;
148981   int ii;
148982   int rc = SQLITE_OK;
148983   int iCell = 0;
148984 
148985   rtreeReference(pRtree);
148986 
148987   /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
148988   freeCursorConstraints(pCsr);
148989   sqlite3_free(pCsr->aPoint);
148990   memset(pCsr, 0, sizeof(RtreeCursor));
148991   pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
148992 
148993   pCsr->iStrategy = idxNum;
148994   if( idxNum==1 ){
148995     /* Special case - lookup by rowid. */
148996     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
148997     RtreeSearchPoint *p;     /* Search point for the the leaf */
148998     i64 iRowid = sqlite3_value_int64(argv[0]);
148999     i64 iNode = 0;
149000     rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
149001     if( rc==SQLITE_OK && pLeaf!=0 ){
149002       p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
149003       assert( p!=0 );  /* Always returns pCsr->sPoint */
149004       pCsr->aNode[0] = pLeaf;
149005       p->id = iNode;
149006       p->eWithin = PARTLY_WITHIN;
149007       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
149008       p->iCell = iCell;
149009       RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
149010     }else{
149011       pCsr->atEOF = 1;
149012     }
149013   }else{
149014     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
149015     ** with the configured constraints.
149016     */
149017     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
149018     if( rc==SQLITE_OK && argc>0 ){
149019       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
149020       pCsr->nConstraint = argc;
149021       if( !pCsr->aConstraint ){
149022         rc = SQLITE_NOMEM;
149023       }else{
149024         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
149025         memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
149026         assert( (idxStr==0 && argc==0)
149027                 || (idxStr && (int)strlen(idxStr)==argc*2) );
149028         for(ii=0; ii<argc; ii++){
149029           RtreeConstraint *p = &pCsr->aConstraint[ii];
149030           p->op = idxStr[ii*2];
149031           p->iCoord = idxStr[ii*2+1]-'0';
149032           if( p->op>=RTREE_MATCH ){
149033             /* A MATCH operator. The right-hand-side must be a blob that
149034             ** can be cast into an RtreeMatchArg object. One created using
149035             ** an sqlite3_rtree_geometry_callback() SQL user function.
149036             */
149037             rc = deserializeGeometry(argv[ii], p);
149038             if( rc!=SQLITE_OK ){
149039               break;
149040             }
149041             p->pInfo->nCoord = pRtree->nDim*2;
149042             p->pInfo->anQueue = pCsr->anQueue;
149043             p->pInfo->mxLevel = pRtree->iDepth + 1;
149044           }else{
149045 #ifdef SQLITE_RTREE_INT_ONLY
149046             p->u.rValue = sqlite3_value_int64(argv[ii]);
149047 #else
149048             p->u.rValue = sqlite3_value_double(argv[ii]);
149049 #endif
149050           }
149051         }
149052       }
149053     }
149054     if( rc==SQLITE_OK ){
149055       RtreeSearchPoint *pNew;
149056       pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
149057       if( pNew==0 ) return SQLITE_NOMEM;
149058       pNew->id = 1;
149059       pNew->iCell = 0;
149060       pNew->eWithin = PARTLY_WITHIN;
149061       assert( pCsr->bPoint==1 );
149062       pCsr->aNode[0] = pRoot;
149063       pRoot = 0;
149064       RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
149065       rc = rtreeStepToLeaf(pCsr);
149066     }
149067   }
149068 
149069   nodeRelease(pRtree, pRoot);
149070   rtreeRelease(pRtree);
149071   return rc;
149072 }
149073 
149074 /*
149075 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
149076 ** extension is currently being used by a version of SQLite too old to
149077 ** support estimatedRows. In that case this function is a no-op.
149078 */
149079 static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
149080 #if SQLITE_VERSION_NUMBER>=3008002
149081   if( sqlite3_libversion_number()>=3008002 ){
149082     pIdxInfo->estimatedRows = nRow;
149083   }
149084 #endif
149085 }
149086 
149087 /*
149088 ** Rtree virtual table module xBestIndex method. There are three
149089 ** table scan strategies to choose from (in order from most to
149090 ** least desirable):
149091 **
149092 **   idxNum     idxStr        Strategy
149093 **   ------------------------------------------------
149094 **     1        Unused        Direct lookup by rowid.
149095 **     2        See below     R-tree query or full-table scan.
149096 **   ------------------------------------------------
149097 **
149098 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
149099 ** 2 is used, idxStr is formatted to contain 2 bytes for each
149100 ** constraint used. The first two bytes of idxStr correspond to
149101 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
149102 ** (argvIndex==1) etc.
149103 **
149104 ** The first of each pair of bytes in idxStr identifies the constraint
149105 ** operator as follows:
149106 **
149107 **   Operator    Byte Value
149108 **   ----------------------
149109 **      =        0x41 ('A')
149110 **     <=        0x42 ('B')
149111 **      <        0x43 ('C')
149112 **     >=        0x44 ('D')
149113 **      >        0x45 ('E')
149114 **   MATCH       0x46 ('F')
149115 **   ----------------------
149116 **
149117 ** The second of each pair of bytes identifies the coordinate column
149118 ** to which the constraint applies. The leftmost coordinate column
149119 ** is 'a', the second from the left 'b' etc.
149120 */
149121 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
149122   Rtree *pRtree = (Rtree*)tab;
149123   int rc = SQLITE_OK;
149124   int ii;
149125   i64 nRow;                       /* Estimated rows returned by this scan */
149126 
149127   int iIdx = 0;
149128   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
149129   memset(zIdxStr, 0, sizeof(zIdxStr));
149130 
149131   assert( pIdxInfo->idxStr==0 );
149132   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
149133     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
149134 
149135     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
149136       /* We have an equality constraint on the rowid. Use strategy 1. */
149137       int jj;
149138       for(jj=0; jj<ii; jj++){
149139         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
149140         pIdxInfo->aConstraintUsage[jj].omit = 0;
149141       }
149142       pIdxInfo->idxNum = 1;
149143       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
149144       pIdxInfo->aConstraintUsage[jj].omit = 1;
149145 
149146       /* This strategy involves a two rowid lookups on an B-Tree structures
149147       ** and then a linear search of an R-Tree node. This should be
149148       ** considered almost as quick as a direct rowid lookup (for which
149149       ** sqlite uses an internal cost of 0.0). It is expected to return
149150       ** a single row.
149151       */
149152       pIdxInfo->estimatedCost = 30.0;
149153       setEstimatedRows(pIdxInfo, 1);
149154       return SQLITE_OK;
149155     }
149156 
149157     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
149158       u8 op;
149159       switch( p->op ){
149160         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
149161         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
149162         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
149163         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
149164         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
149165         default:
149166           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
149167           op = RTREE_MATCH;
149168           break;
149169       }
149170       zIdxStr[iIdx++] = op;
149171       zIdxStr[iIdx++] = p->iColumn - 1 + '0';
149172       pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
149173       pIdxInfo->aConstraintUsage[ii].omit = 1;
149174     }
149175   }
149176 
149177   pIdxInfo->idxNum = 2;
149178   pIdxInfo->needToFreeIdxStr = 1;
149179   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
149180     return SQLITE_NOMEM;
149181   }
149182 
149183   nRow = pRtree->nRowEst / (iIdx + 1);
149184   pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
149185   setEstimatedRows(pIdxInfo, nRow);
149186 
149187   return rc;
149188 }
149189 
149190 /*
149191 ** Return the N-dimensional volumn of the cell stored in *p.
149192 */
149193 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
149194   RtreeDValue area = (RtreeDValue)1;
149195   int ii;
149196   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
149197     area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
149198   }
149199   return area;
149200 }
149201 
149202 /*
149203 ** Return the margin length of cell p. The margin length is the sum
149204 ** of the objects size in each dimension.
149205 */
149206 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
149207   RtreeDValue margin = (RtreeDValue)0;
149208   int ii;
149209   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
149210     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
149211   }
149212   return margin;
149213 }
149214 
149215 /*
149216 ** Store the union of cells p1 and p2 in p1.
149217 */
149218 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
149219   int ii;
149220   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
149221     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
149222       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
149223       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
149224     }
149225   }else{
149226     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
149227       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
149228       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
149229     }
149230   }
149231 }
149232 
149233 /*
149234 ** Return true if the area covered by p2 is a subset of the area covered
149235 ** by p1. False otherwise.
149236 */
149237 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
149238   int ii;
149239   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
149240   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
149241     RtreeCoord *a1 = &p1->aCoord[ii];
149242     RtreeCoord *a2 = &p2->aCoord[ii];
149243     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
149244      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
149245     ){
149246       return 0;
149247     }
149248   }
149249   return 1;
149250 }
149251 
149252 /*
149253 ** Return the amount cell p would grow by if it were unioned with pCell.
149254 */
149255 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
149256   RtreeDValue area;
149257   RtreeCell cell;
149258   memcpy(&cell, p, sizeof(RtreeCell));
149259   area = cellArea(pRtree, &cell);
149260   cellUnion(pRtree, &cell, pCell);
149261   return (cellArea(pRtree, &cell)-area);
149262 }
149263 
149264 static RtreeDValue cellOverlap(
149265   Rtree *pRtree,
149266   RtreeCell *p,
149267   RtreeCell *aCell,
149268   int nCell
149269 ){
149270   int ii;
149271   RtreeDValue overlap = RTREE_ZERO;
149272   for(ii=0; ii<nCell; ii++){
149273     int jj;
149274     RtreeDValue o = (RtreeDValue)1;
149275     for(jj=0; jj<(pRtree->nDim*2); jj+=2){
149276       RtreeDValue x1, x2;
149277       x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
149278       x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
149279       if( x2<x1 ){
149280         o = (RtreeDValue)0;
149281         break;
149282       }else{
149283         o = o * (x2-x1);
149284       }
149285     }
149286     overlap += o;
149287   }
149288   return overlap;
149289 }
149290 
149291 
149292 /*
149293 ** This function implements the ChooseLeaf algorithm from Gutman[84].
149294 ** ChooseSubTree in r*tree terminology.
149295 */
149296 static int ChooseLeaf(
149297   Rtree *pRtree,               /* Rtree table */
149298   RtreeCell *pCell,            /* Cell to insert into rtree */
149299   int iHeight,                 /* Height of sub-tree rooted at pCell */
149300   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
149301 ){
149302   int rc;
149303   int ii;
149304   RtreeNode *pNode;
149305   rc = nodeAcquire(pRtree, 1, 0, &pNode);
149306 
149307   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
149308     int iCell;
149309     sqlite3_int64 iBest = 0;
149310 
149311     RtreeDValue fMinGrowth = RTREE_ZERO;
149312     RtreeDValue fMinArea = RTREE_ZERO;
149313 
149314     int nCell = NCELL(pNode);
149315     RtreeCell cell;
149316     RtreeNode *pChild;
149317 
149318     RtreeCell *aCell = 0;
149319 
149320     /* Select the child node which will be enlarged the least if pCell
149321     ** is inserted into it. Resolve ties by choosing the entry with
149322     ** the smallest area.
149323     */
149324     for(iCell=0; iCell<nCell; iCell++){
149325       int bBest = 0;
149326       RtreeDValue growth;
149327       RtreeDValue area;
149328       nodeGetCell(pRtree, pNode, iCell, &cell);
149329       growth = cellGrowth(pRtree, &cell, pCell);
149330       area = cellArea(pRtree, &cell);
149331       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
149332         bBest = 1;
149333       }
149334       if( bBest ){
149335         fMinGrowth = growth;
149336         fMinArea = area;
149337         iBest = cell.iRowid;
149338       }
149339     }
149340 
149341     sqlite3_free(aCell);
149342     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
149343     nodeRelease(pRtree, pNode);
149344     pNode = pChild;
149345   }
149346 
149347   *ppLeaf = pNode;
149348   return rc;
149349 }
149350 
149351 /*
149352 ** A cell with the same content as pCell has just been inserted into
149353 ** the node pNode. This function updates the bounding box cells in
149354 ** all ancestor elements.
149355 */
149356 static int AdjustTree(
149357   Rtree *pRtree,                    /* Rtree table */
149358   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
149359   RtreeCell *pCell                  /* This cell was just inserted */
149360 ){
149361   RtreeNode *p = pNode;
149362   while( p->pParent ){
149363     RtreeNode *pParent = p->pParent;
149364     RtreeCell cell;
149365     int iCell;
149366 
149367     if( nodeParentIndex(pRtree, p, &iCell) ){
149368       return SQLITE_CORRUPT_VTAB;
149369     }
149370 
149371     nodeGetCell(pRtree, pParent, iCell, &cell);
149372     if( !cellContains(pRtree, &cell, pCell) ){
149373       cellUnion(pRtree, &cell, pCell);
149374       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
149375     }
149376 
149377     p = pParent;
149378   }
149379   return SQLITE_OK;
149380 }
149381 
149382 /*
149383 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
149384 */
149385 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
149386   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
149387   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
149388   sqlite3_step(pRtree->pWriteRowid);
149389   return sqlite3_reset(pRtree->pWriteRowid);
149390 }
149391 
149392 /*
149393 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
149394 */
149395 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
149396   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
149397   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
149398   sqlite3_step(pRtree->pWriteParent);
149399   return sqlite3_reset(pRtree->pWriteParent);
149400 }
149401 
149402 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
149403 
149404 
149405 /*
149406 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
149407 ** nIdx. The aIdx array contains the set of integers from 0 to
149408 ** (nIdx-1) in no particular order. This function sorts the values
149409 ** in aIdx according to the indexed values in aDistance. For
149410 ** example, assuming the inputs:
149411 **
149412 **   aIdx      = { 0,   1,   2,   3 }
149413 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
149414 **
149415 ** this function sets the aIdx array to contain:
149416 **
149417 **   aIdx      = { 0,   1,   2,   3 }
149418 **
149419 ** The aSpare array is used as temporary working space by the
149420 ** sorting algorithm.
149421 */
149422 static void SortByDistance(
149423   int *aIdx,
149424   int nIdx,
149425   RtreeDValue *aDistance,
149426   int *aSpare
149427 ){
149428   if( nIdx>1 ){
149429     int iLeft = 0;
149430     int iRight = 0;
149431 
149432     int nLeft = nIdx/2;
149433     int nRight = nIdx-nLeft;
149434     int *aLeft = aIdx;
149435     int *aRight = &aIdx[nLeft];
149436 
149437     SortByDistance(aLeft, nLeft, aDistance, aSpare);
149438     SortByDistance(aRight, nRight, aDistance, aSpare);
149439 
149440     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
149441     aLeft = aSpare;
149442 
149443     while( iLeft<nLeft || iRight<nRight ){
149444       if( iLeft==nLeft ){
149445         aIdx[iLeft+iRight] = aRight[iRight];
149446         iRight++;
149447       }else if( iRight==nRight ){
149448         aIdx[iLeft+iRight] = aLeft[iLeft];
149449         iLeft++;
149450       }else{
149451         RtreeDValue fLeft = aDistance[aLeft[iLeft]];
149452         RtreeDValue fRight = aDistance[aRight[iRight]];
149453         if( fLeft<fRight ){
149454           aIdx[iLeft+iRight] = aLeft[iLeft];
149455           iLeft++;
149456         }else{
149457           aIdx[iLeft+iRight] = aRight[iRight];
149458           iRight++;
149459         }
149460       }
149461     }
149462 
149463 #if 0
149464     /* Check that the sort worked */
149465     {
149466       int jj;
149467       for(jj=1; jj<nIdx; jj++){
149468         RtreeDValue left = aDistance[aIdx[jj-1]];
149469         RtreeDValue right = aDistance[aIdx[jj]];
149470         assert( left<=right );
149471       }
149472     }
149473 #endif
149474   }
149475 }
149476 
149477 /*
149478 ** Arguments aIdx, aCell and aSpare all point to arrays of size
149479 ** nIdx. The aIdx array contains the set of integers from 0 to
149480 ** (nIdx-1) in no particular order. This function sorts the values
149481 ** in aIdx according to dimension iDim of the cells in aCell. The
149482 ** minimum value of dimension iDim is considered first, the
149483 ** maximum used to break ties.
149484 **
149485 ** The aSpare array is used as temporary working space by the
149486 ** sorting algorithm.
149487 */
149488 static void SortByDimension(
149489   Rtree *pRtree,
149490   int *aIdx,
149491   int nIdx,
149492   int iDim,
149493   RtreeCell *aCell,
149494   int *aSpare
149495 ){
149496   if( nIdx>1 ){
149497 
149498     int iLeft = 0;
149499     int iRight = 0;
149500 
149501     int nLeft = nIdx/2;
149502     int nRight = nIdx-nLeft;
149503     int *aLeft = aIdx;
149504     int *aRight = &aIdx[nLeft];
149505 
149506     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
149507     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
149508 
149509     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
149510     aLeft = aSpare;
149511     while( iLeft<nLeft || iRight<nRight ){
149512       RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
149513       RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
149514       RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
149515       RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
149516       if( (iLeft!=nLeft) && ((iRight==nRight)
149517        || (xleft1<xright1)
149518        || (xleft1==xright1 && xleft2<xright2)
149519       )){
149520         aIdx[iLeft+iRight] = aLeft[iLeft];
149521         iLeft++;
149522       }else{
149523         aIdx[iLeft+iRight] = aRight[iRight];
149524         iRight++;
149525       }
149526     }
149527 
149528 #if 0
149529     /* Check that the sort worked */
149530     {
149531       int jj;
149532       for(jj=1; jj<nIdx; jj++){
149533         RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
149534         RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
149535         RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
149536         RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
149537         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
149538       }
149539     }
149540 #endif
149541   }
149542 }
149543 
149544 /*
149545 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
149546 */
149547 static int splitNodeStartree(
149548   Rtree *pRtree,
149549   RtreeCell *aCell,
149550   int nCell,
149551   RtreeNode *pLeft,
149552   RtreeNode *pRight,
149553   RtreeCell *pBboxLeft,
149554   RtreeCell *pBboxRight
149555 ){
149556   int **aaSorted;
149557   int *aSpare;
149558   int ii;
149559 
149560   int iBestDim = 0;
149561   int iBestSplit = 0;
149562   RtreeDValue fBestMargin = RTREE_ZERO;
149563 
149564   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
149565 
149566   aaSorted = (int **)sqlite3_malloc(nByte);
149567   if( !aaSorted ){
149568     return SQLITE_NOMEM;
149569   }
149570 
149571   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
149572   memset(aaSorted, 0, nByte);
149573   for(ii=0; ii<pRtree->nDim; ii++){
149574     int jj;
149575     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
149576     for(jj=0; jj<nCell; jj++){
149577       aaSorted[ii][jj] = jj;
149578     }
149579     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
149580   }
149581 
149582   for(ii=0; ii<pRtree->nDim; ii++){
149583     RtreeDValue margin = RTREE_ZERO;
149584     RtreeDValue fBestOverlap = RTREE_ZERO;
149585     RtreeDValue fBestArea = RTREE_ZERO;
149586     int iBestLeft = 0;
149587     int nLeft;
149588 
149589     for(
149590       nLeft=RTREE_MINCELLS(pRtree);
149591       nLeft<=(nCell-RTREE_MINCELLS(pRtree));
149592       nLeft++
149593     ){
149594       RtreeCell left;
149595       RtreeCell right;
149596       int kk;
149597       RtreeDValue overlap;
149598       RtreeDValue area;
149599 
149600       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
149601       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
149602       for(kk=1; kk<(nCell-1); kk++){
149603         if( kk<nLeft ){
149604           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
149605         }else{
149606           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
149607         }
149608       }
149609       margin += cellMargin(pRtree, &left);
149610       margin += cellMargin(pRtree, &right);
149611       overlap = cellOverlap(pRtree, &left, &right, 1);
149612       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
149613       if( (nLeft==RTREE_MINCELLS(pRtree))
149614        || (overlap<fBestOverlap)
149615        || (overlap==fBestOverlap && area<fBestArea)
149616       ){
149617         iBestLeft = nLeft;
149618         fBestOverlap = overlap;
149619         fBestArea = area;
149620       }
149621     }
149622 
149623     if( ii==0 || margin<fBestMargin ){
149624       iBestDim = ii;
149625       fBestMargin = margin;
149626       iBestSplit = iBestLeft;
149627     }
149628   }
149629 
149630   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
149631   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
149632   for(ii=0; ii<nCell; ii++){
149633     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
149634     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
149635     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
149636     nodeInsertCell(pRtree, pTarget, pCell);
149637     cellUnion(pRtree, pBbox, pCell);
149638   }
149639 
149640   sqlite3_free(aaSorted);
149641   return SQLITE_OK;
149642 }
149643 
149644 
149645 static int updateMapping(
149646   Rtree *pRtree,
149647   i64 iRowid,
149648   RtreeNode *pNode,
149649   int iHeight
149650 ){
149651   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
149652   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
149653   if( iHeight>0 ){
149654     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
149655     if( pChild ){
149656       nodeRelease(pRtree, pChild->pParent);
149657       nodeReference(pNode);
149658       pChild->pParent = pNode;
149659     }
149660   }
149661   return xSetMapping(pRtree, iRowid, pNode->iNode);
149662 }
149663 
149664 static int SplitNode(
149665   Rtree *pRtree,
149666   RtreeNode *pNode,
149667   RtreeCell *pCell,
149668   int iHeight
149669 ){
149670   int i;
149671   int newCellIsRight = 0;
149672 
149673   int rc = SQLITE_OK;
149674   int nCell = NCELL(pNode);
149675   RtreeCell *aCell;
149676   int *aiUsed;
149677 
149678   RtreeNode *pLeft = 0;
149679   RtreeNode *pRight = 0;
149680 
149681   RtreeCell leftbbox;
149682   RtreeCell rightbbox;
149683 
149684   /* Allocate an array and populate it with a copy of pCell and
149685   ** all cells from node pLeft. Then zero the original node.
149686   */
149687   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
149688   if( !aCell ){
149689     rc = SQLITE_NOMEM;
149690     goto splitnode_out;
149691   }
149692   aiUsed = (int *)&aCell[nCell+1];
149693   memset(aiUsed, 0, sizeof(int)*(nCell+1));
149694   for(i=0; i<nCell; i++){
149695     nodeGetCell(pRtree, pNode, i, &aCell[i]);
149696   }
149697   nodeZero(pRtree, pNode);
149698   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
149699   nCell++;
149700 
149701   if( pNode->iNode==1 ){
149702     pRight = nodeNew(pRtree, pNode);
149703     pLeft = nodeNew(pRtree, pNode);
149704     pRtree->iDepth++;
149705     pNode->isDirty = 1;
149706     writeInt16(pNode->zData, pRtree->iDepth);
149707   }else{
149708     pLeft = pNode;
149709     pRight = nodeNew(pRtree, pLeft->pParent);
149710     nodeReference(pLeft);
149711   }
149712 
149713   if( !pLeft || !pRight ){
149714     rc = SQLITE_NOMEM;
149715     goto splitnode_out;
149716   }
149717 
149718   memset(pLeft->zData, 0, pRtree->iNodeSize);
149719   memset(pRight->zData, 0, pRtree->iNodeSize);
149720 
149721   rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
149722                          &leftbbox, &rightbbox);
149723   if( rc!=SQLITE_OK ){
149724     goto splitnode_out;
149725   }
149726 
149727   /* Ensure both child nodes have node numbers assigned to them by calling
149728   ** nodeWrite(). Node pRight always needs a node number, as it was created
149729   ** by nodeNew() above. But node pLeft sometimes already has a node number.
149730   ** In this case avoid the all to nodeWrite().
149731   */
149732   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
149733    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
149734   ){
149735     goto splitnode_out;
149736   }
149737 
149738   rightbbox.iRowid = pRight->iNode;
149739   leftbbox.iRowid = pLeft->iNode;
149740 
149741   if( pNode->iNode==1 ){
149742     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
149743     if( rc!=SQLITE_OK ){
149744       goto splitnode_out;
149745     }
149746   }else{
149747     RtreeNode *pParent = pLeft->pParent;
149748     int iCell;
149749     rc = nodeParentIndex(pRtree, pLeft, &iCell);
149750     if( rc==SQLITE_OK ){
149751       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
149752       rc = AdjustTree(pRtree, pParent, &leftbbox);
149753     }
149754     if( rc!=SQLITE_OK ){
149755       goto splitnode_out;
149756     }
149757   }
149758   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
149759     goto splitnode_out;
149760   }
149761 
149762   for(i=0; i<NCELL(pRight); i++){
149763     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
149764     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
149765     if( iRowid==pCell->iRowid ){
149766       newCellIsRight = 1;
149767     }
149768     if( rc!=SQLITE_OK ){
149769       goto splitnode_out;
149770     }
149771   }
149772   if( pNode->iNode==1 ){
149773     for(i=0; i<NCELL(pLeft); i++){
149774       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
149775       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
149776       if( rc!=SQLITE_OK ){
149777         goto splitnode_out;
149778       }
149779     }
149780   }else if( newCellIsRight==0 ){
149781     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
149782   }
149783 
149784   if( rc==SQLITE_OK ){
149785     rc = nodeRelease(pRtree, pRight);
149786     pRight = 0;
149787   }
149788   if( rc==SQLITE_OK ){
149789     rc = nodeRelease(pRtree, pLeft);
149790     pLeft = 0;
149791   }
149792 
149793 splitnode_out:
149794   nodeRelease(pRtree, pRight);
149795   nodeRelease(pRtree, pLeft);
149796   sqlite3_free(aCell);
149797   return rc;
149798 }
149799 
149800 /*
149801 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
149802 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
149803 ** the pLeaf->pParent chain all the way up to the root node.
149804 **
149805 ** This operation is required when a row is deleted (or updated - an update
149806 ** is implemented as a delete followed by an insert). SQLite provides the
149807 ** rowid of the row to delete, which can be used to find the leaf on which
149808 ** the entry resides (argument pLeaf). Once the leaf is located, this
149809 ** function is called to determine its ancestry.
149810 */
149811 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
149812   int rc = SQLITE_OK;
149813   RtreeNode *pChild = pLeaf;
149814   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
149815     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
149816     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
149817     rc = sqlite3_step(pRtree->pReadParent);
149818     if( rc==SQLITE_ROW ){
149819       RtreeNode *pTest;           /* Used to test for reference loops */
149820       i64 iNode;                  /* Node number of parent node */
149821 
149822       /* Before setting pChild->pParent, test that we are not creating a
149823       ** loop of references (as we would if, say, pChild==pParent). We don't
149824       ** want to do this as it leads to a memory leak when trying to delete
149825       ** the referenced counted node structures.
149826       */
149827       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
149828       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
149829       if( !pTest ){
149830         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
149831       }
149832     }
149833     rc = sqlite3_reset(pRtree->pReadParent);
149834     if( rc==SQLITE_OK ) rc = rc2;
149835     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
149836     pChild = pChild->pParent;
149837   }
149838   return rc;
149839 }
149840 
149841 static int deleteCell(Rtree *, RtreeNode *, int, int);
149842 
149843 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
149844   int rc;
149845   int rc2;
149846   RtreeNode *pParent = 0;
149847   int iCell;
149848 
149849   assert( pNode->nRef==1 );
149850 
149851   /* Remove the entry in the parent cell. */
149852   rc = nodeParentIndex(pRtree, pNode, &iCell);
149853   if( rc==SQLITE_OK ){
149854     pParent = pNode->pParent;
149855     pNode->pParent = 0;
149856     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
149857   }
149858   rc2 = nodeRelease(pRtree, pParent);
149859   if( rc==SQLITE_OK ){
149860     rc = rc2;
149861   }
149862   if( rc!=SQLITE_OK ){
149863     return rc;
149864   }
149865 
149866   /* Remove the xxx_node entry. */
149867   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
149868   sqlite3_step(pRtree->pDeleteNode);
149869   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
149870     return rc;
149871   }
149872 
149873   /* Remove the xxx_parent entry. */
149874   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
149875   sqlite3_step(pRtree->pDeleteParent);
149876   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
149877     return rc;
149878   }
149879 
149880   /* Remove the node from the in-memory hash table and link it into
149881   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
149882   */
149883   nodeHashDelete(pRtree, pNode);
149884   pNode->iNode = iHeight;
149885   pNode->pNext = pRtree->pDeleted;
149886   pNode->nRef++;
149887   pRtree->pDeleted = pNode;
149888 
149889   return SQLITE_OK;
149890 }
149891 
149892 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
149893   RtreeNode *pParent = pNode->pParent;
149894   int rc = SQLITE_OK;
149895   if( pParent ){
149896     int ii;
149897     int nCell = NCELL(pNode);
149898     RtreeCell box;                            /* Bounding box for pNode */
149899     nodeGetCell(pRtree, pNode, 0, &box);
149900     for(ii=1; ii<nCell; ii++){
149901       RtreeCell cell;
149902       nodeGetCell(pRtree, pNode, ii, &cell);
149903       cellUnion(pRtree, &box, &cell);
149904     }
149905     box.iRowid = pNode->iNode;
149906     rc = nodeParentIndex(pRtree, pNode, &ii);
149907     if( rc==SQLITE_OK ){
149908       nodeOverwriteCell(pRtree, pParent, &box, ii);
149909       rc = fixBoundingBox(pRtree, pParent);
149910     }
149911   }
149912   return rc;
149913 }
149914 
149915 /*
149916 ** Delete the cell at index iCell of node pNode. After removing the
149917 ** cell, adjust the r-tree data structure if required.
149918 */
149919 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
149920   RtreeNode *pParent;
149921   int rc;
149922 
149923   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
149924     return rc;
149925   }
149926 
149927   /* Remove the cell from the node. This call just moves bytes around
149928   ** the in-memory node image, so it cannot fail.
149929   */
149930   nodeDeleteCell(pRtree, pNode, iCell);
149931 
149932   /* If the node is not the tree root and now has less than the minimum
149933   ** number of cells, remove it from the tree. Otherwise, update the
149934   ** cell in the parent node so that it tightly contains the updated
149935   ** node.
149936   */
149937   pParent = pNode->pParent;
149938   assert( pParent || pNode->iNode==1 );
149939   if( pParent ){
149940     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
149941       rc = removeNode(pRtree, pNode, iHeight);
149942     }else{
149943       rc = fixBoundingBox(pRtree, pNode);
149944     }
149945   }
149946 
149947   return rc;
149948 }
149949 
149950 static int Reinsert(
149951   Rtree *pRtree,
149952   RtreeNode *pNode,
149953   RtreeCell *pCell,
149954   int iHeight
149955 ){
149956   int *aOrder;
149957   int *aSpare;
149958   RtreeCell *aCell;
149959   RtreeDValue *aDistance;
149960   int nCell;
149961   RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
149962   int iDim;
149963   int ii;
149964   int rc = SQLITE_OK;
149965   int n;
149966 
149967   memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
149968 
149969   nCell = NCELL(pNode)+1;
149970   n = (nCell+1)&(~1);
149971 
149972   /* Allocate the buffers used by this operation. The allocation is
149973   ** relinquished before this function returns.
149974   */
149975   aCell = (RtreeCell *)sqlite3_malloc(n * (
149976     sizeof(RtreeCell)     +         /* aCell array */
149977     sizeof(int)           +         /* aOrder array */
149978     sizeof(int)           +         /* aSpare array */
149979     sizeof(RtreeDValue)             /* aDistance array */
149980   ));
149981   if( !aCell ){
149982     return SQLITE_NOMEM;
149983   }
149984   aOrder    = (int *)&aCell[n];
149985   aSpare    = (int *)&aOrder[n];
149986   aDistance = (RtreeDValue *)&aSpare[n];
149987 
149988   for(ii=0; ii<nCell; ii++){
149989     if( ii==(nCell-1) ){
149990       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
149991     }else{
149992       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
149993     }
149994     aOrder[ii] = ii;
149995     for(iDim=0; iDim<pRtree->nDim; iDim++){
149996       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
149997       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
149998     }
149999   }
150000   for(iDim=0; iDim<pRtree->nDim; iDim++){
150001     aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
150002   }
150003 
150004   for(ii=0; ii<nCell; ii++){
150005     aDistance[ii] = RTREE_ZERO;
150006     for(iDim=0; iDim<pRtree->nDim; iDim++){
150007       RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
150008                                DCOORD(aCell[ii].aCoord[iDim*2]));
150009       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
150010     }
150011   }
150012 
150013   SortByDistance(aOrder, nCell, aDistance, aSpare);
150014   nodeZero(pRtree, pNode);
150015 
150016   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
150017     RtreeCell *p = &aCell[aOrder[ii]];
150018     nodeInsertCell(pRtree, pNode, p);
150019     if( p->iRowid==pCell->iRowid ){
150020       if( iHeight==0 ){
150021         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
150022       }else{
150023         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
150024       }
150025     }
150026   }
150027   if( rc==SQLITE_OK ){
150028     rc = fixBoundingBox(pRtree, pNode);
150029   }
150030   for(; rc==SQLITE_OK && ii<nCell; ii++){
150031     /* Find a node to store this cell in. pNode->iNode currently contains
150032     ** the height of the sub-tree headed by the cell.
150033     */
150034     RtreeNode *pInsert;
150035     RtreeCell *p = &aCell[aOrder[ii]];
150036     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
150037     if( rc==SQLITE_OK ){
150038       int rc2;
150039       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
150040       rc2 = nodeRelease(pRtree, pInsert);
150041       if( rc==SQLITE_OK ){
150042         rc = rc2;
150043       }
150044     }
150045   }
150046 
150047   sqlite3_free(aCell);
150048   return rc;
150049 }
150050 
150051 /*
150052 ** Insert cell pCell into node pNode. Node pNode is the head of a
150053 ** subtree iHeight high (leaf nodes have iHeight==0).
150054 */
150055 static int rtreeInsertCell(
150056   Rtree *pRtree,
150057   RtreeNode *pNode,
150058   RtreeCell *pCell,
150059   int iHeight
150060 ){
150061   int rc = SQLITE_OK;
150062   if( iHeight>0 ){
150063     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
150064     if( pChild ){
150065       nodeRelease(pRtree, pChild->pParent);
150066       nodeReference(pNode);
150067       pChild->pParent = pNode;
150068     }
150069   }
150070   if( nodeInsertCell(pRtree, pNode, pCell) ){
150071     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
150072       rc = SplitNode(pRtree, pNode, pCell, iHeight);
150073     }else{
150074       pRtree->iReinsertHeight = iHeight;
150075       rc = Reinsert(pRtree, pNode, pCell, iHeight);
150076     }
150077   }else{
150078     rc = AdjustTree(pRtree, pNode, pCell);
150079     if( rc==SQLITE_OK ){
150080       if( iHeight==0 ){
150081         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
150082       }else{
150083         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
150084       }
150085     }
150086   }
150087   return rc;
150088 }
150089 
150090 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
150091   int ii;
150092   int rc = SQLITE_OK;
150093   int nCell = NCELL(pNode);
150094 
150095   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
150096     RtreeNode *pInsert;
150097     RtreeCell cell;
150098     nodeGetCell(pRtree, pNode, ii, &cell);
150099 
150100     /* Find a node to store this cell in. pNode->iNode currently contains
150101     ** the height of the sub-tree headed by the cell.
150102     */
150103     rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
150104     if( rc==SQLITE_OK ){
150105       int rc2;
150106       rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
150107       rc2 = nodeRelease(pRtree, pInsert);
150108       if( rc==SQLITE_OK ){
150109         rc = rc2;
150110       }
150111     }
150112   }
150113   return rc;
150114 }
150115 
150116 /*
150117 ** Select a currently unused rowid for a new r-tree record.
150118 */
150119 static int newRowid(Rtree *pRtree, i64 *piRowid){
150120   int rc;
150121   sqlite3_bind_null(pRtree->pWriteRowid, 1);
150122   sqlite3_bind_null(pRtree->pWriteRowid, 2);
150123   sqlite3_step(pRtree->pWriteRowid);
150124   rc = sqlite3_reset(pRtree->pWriteRowid);
150125   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
150126   return rc;
150127 }
150128 
150129 /*
150130 ** Remove the entry with rowid=iDelete from the r-tree structure.
150131 */
150132 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
150133   int rc;                         /* Return code */
150134   RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
150135   int iCell;                      /* Index of iDelete cell in pLeaf */
150136   RtreeNode *pRoot;               /* Root node of rtree structure */
150137 
150138 
150139   /* Obtain a reference to the root node to initialize Rtree.iDepth */
150140   rc = nodeAcquire(pRtree, 1, 0, &pRoot);
150141 
150142   /* Obtain a reference to the leaf node that contains the entry
150143   ** about to be deleted.
150144   */
150145   if( rc==SQLITE_OK ){
150146     rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
150147   }
150148 
150149   /* Delete the cell in question from the leaf node. */
150150   if( rc==SQLITE_OK ){
150151     int rc2;
150152     rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
150153     if( rc==SQLITE_OK ){
150154       rc = deleteCell(pRtree, pLeaf, iCell, 0);
150155     }
150156     rc2 = nodeRelease(pRtree, pLeaf);
150157     if( rc==SQLITE_OK ){
150158       rc = rc2;
150159     }
150160   }
150161 
150162   /* Delete the corresponding entry in the <rtree>_rowid table. */
150163   if( rc==SQLITE_OK ){
150164     sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
150165     sqlite3_step(pRtree->pDeleteRowid);
150166     rc = sqlite3_reset(pRtree->pDeleteRowid);
150167   }
150168 
150169   /* Check if the root node now has exactly one child. If so, remove
150170   ** it, schedule the contents of the child for reinsertion and
150171   ** reduce the tree height by one.
150172   **
150173   ** This is equivalent to copying the contents of the child into
150174   ** the root node (the operation that Gutman's paper says to perform
150175   ** in this scenario).
150176   */
150177   if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
150178     int rc2;
150179     RtreeNode *pChild;
150180     i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
150181     rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
150182     if( rc==SQLITE_OK ){
150183       rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
150184     }
150185     rc2 = nodeRelease(pRtree, pChild);
150186     if( rc==SQLITE_OK ) rc = rc2;
150187     if( rc==SQLITE_OK ){
150188       pRtree->iDepth--;
150189       writeInt16(pRoot->zData, pRtree->iDepth);
150190       pRoot->isDirty = 1;
150191     }
150192   }
150193 
150194   /* Re-insert the contents of any underfull nodes removed from the tree. */
150195   for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
150196     if( rc==SQLITE_OK ){
150197       rc = reinsertNodeContent(pRtree, pLeaf);
150198     }
150199     pRtree->pDeleted = pLeaf->pNext;
150200     sqlite3_free(pLeaf);
150201   }
150202 
150203   /* Release the reference to the root node. */
150204   if( rc==SQLITE_OK ){
150205     rc = nodeRelease(pRtree, pRoot);
150206   }else{
150207     nodeRelease(pRtree, pRoot);
150208   }
150209 
150210   return rc;
150211 }
150212 
150213 /*
150214 ** Rounding constants for float->double conversion.
150215 */
150216 #define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
150217 #define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
150218 
150219 #if !defined(SQLITE_RTREE_INT_ONLY)
150220 /*
150221 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
150222 ** while taking care to round toward negative or positive, respectively.
150223 */
150224 static RtreeValue rtreeValueDown(sqlite3_value *v){
150225   double d = sqlite3_value_double(v);
150226   float f = (float)d;
150227   if( f>d ){
150228     f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
150229   }
150230   return f;
150231 }
150232 static RtreeValue rtreeValueUp(sqlite3_value *v){
150233   double d = sqlite3_value_double(v);
150234   float f = (float)d;
150235   if( f<d ){
150236     f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
150237   }
150238   return f;
150239 }
150240 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
150241 
150242 
150243 /*
150244 ** The xUpdate method for rtree module virtual tables.
150245 */
150246 static int rtreeUpdate(
150247   sqlite3_vtab *pVtab,
150248   int nData,
150249   sqlite3_value **azData,
150250   sqlite_int64 *pRowid
150251 ){
150252   Rtree *pRtree = (Rtree *)pVtab;
150253   int rc = SQLITE_OK;
150254   RtreeCell cell;                 /* New cell to insert if nData>1 */
150255   int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
150256 
150257   rtreeReference(pRtree);
150258   assert(nData>=1);
150259 
150260   /* Constraint handling. A write operation on an r-tree table may return
150261   ** SQLITE_CONSTRAINT for two reasons:
150262   **
150263   **   1. A duplicate rowid value, or
150264   **   2. The supplied data violates the "x2>=x1" constraint.
150265   **
150266   ** In the first case, if the conflict-handling mode is REPLACE, then
150267   ** the conflicting row can be removed before proceeding. In the second
150268   ** case, SQLITE_CONSTRAINT must be returned regardless of the
150269   ** conflict-handling mode specified by the user.
150270   */
150271   if( nData>1 ){
150272     int ii;
150273 
150274     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
150275     assert( nData==(pRtree->nDim*2 + 3) );
150276 #ifndef SQLITE_RTREE_INT_ONLY
150277     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
150278       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
150279         cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
150280         cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
150281         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
150282           rc = SQLITE_CONSTRAINT;
150283           goto constraint;
150284         }
150285       }
150286     }else
150287 #endif
150288     {
150289       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
150290         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
150291         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
150292         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
150293           rc = SQLITE_CONSTRAINT;
150294           goto constraint;
150295         }
150296       }
150297     }
150298 
150299     /* If a rowid value was supplied, check if it is already present in
150300     ** the table. If so, the constraint has failed. */
150301     if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
150302       cell.iRowid = sqlite3_value_int64(azData[2]);
150303       if( sqlite3_value_type(azData[0])==SQLITE_NULL
150304        || sqlite3_value_int64(azData[0])!=cell.iRowid
150305       ){
150306         int steprc;
150307         sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
150308         steprc = sqlite3_step(pRtree->pReadRowid);
150309         rc = sqlite3_reset(pRtree->pReadRowid);
150310         if( SQLITE_ROW==steprc ){
150311           if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
150312             rc = rtreeDeleteRowid(pRtree, cell.iRowid);
150313           }else{
150314             rc = SQLITE_CONSTRAINT;
150315             goto constraint;
150316           }
150317         }
150318       }
150319       bHaveRowid = 1;
150320     }
150321   }
150322 
150323   /* If azData[0] is not an SQL NULL value, it is the rowid of a
150324   ** record to delete from the r-tree table. The following block does
150325   ** just that.
150326   */
150327   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
150328     rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
150329   }
150330 
150331   /* If the azData[] array contains more than one element, elements
150332   ** (azData[2]..azData[argc-1]) contain a new record to insert into
150333   ** the r-tree structure.
150334   */
150335   if( rc==SQLITE_OK && nData>1 ){
150336     /* Insert the new record into the r-tree */
150337     RtreeNode *pLeaf = 0;
150338 
150339     /* Figure out the rowid of the new row. */
150340     if( bHaveRowid==0 ){
150341       rc = newRowid(pRtree, &cell.iRowid);
150342     }
150343     *pRowid = cell.iRowid;
150344 
150345     if( rc==SQLITE_OK ){
150346       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
150347     }
150348     if( rc==SQLITE_OK ){
150349       int rc2;
150350       pRtree->iReinsertHeight = -1;
150351       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
150352       rc2 = nodeRelease(pRtree, pLeaf);
150353       if( rc==SQLITE_OK ){
150354         rc = rc2;
150355       }
150356     }
150357   }
150358 
150359 constraint:
150360   rtreeRelease(pRtree);
150361   return rc;
150362 }
150363 
150364 /*
150365 ** The xRename method for rtree module virtual tables.
150366 */
150367 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
150368   Rtree *pRtree = (Rtree *)pVtab;
150369   int rc = SQLITE_NOMEM;
150370   char *zSql = sqlite3_mprintf(
150371     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
150372     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
150373     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
150374     , pRtree->zDb, pRtree->zName, zNewName
150375     , pRtree->zDb, pRtree->zName, zNewName
150376     , pRtree->zDb, pRtree->zName, zNewName
150377   );
150378   if( zSql ){
150379     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
150380     sqlite3_free(zSql);
150381   }
150382   return rc;
150383 }
150384 
150385 /*
150386 ** This function populates the pRtree->nRowEst variable with an estimate
150387 ** of the number of rows in the virtual table. If possible, this is based
150388 ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
150389 */
150390 static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
150391   const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
150392   char *zSql;
150393   sqlite3_stmt *p;
150394   int rc;
150395   i64 nRow = 0;
150396 
150397   zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
150398   if( zSql==0 ){
150399     rc = SQLITE_NOMEM;
150400   }else{
150401     rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
150402     if( rc==SQLITE_OK ){
150403       if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
150404       rc = sqlite3_finalize(p);
150405     }else if( rc!=SQLITE_NOMEM ){
150406       rc = SQLITE_OK;
150407     }
150408 
150409     if( rc==SQLITE_OK ){
150410       if( nRow==0 ){
150411         pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
150412       }else{
150413         pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
150414       }
150415     }
150416     sqlite3_free(zSql);
150417   }
150418 
150419   return rc;
150420 }
150421 
150422 static sqlite3_module rtreeModule = {
150423   0,                          /* iVersion */
150424   rtreeCreate,                /* xCreate - create a table */
150425   rtreeConnect,               /* xConnect - connect to an existing table */
150426   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
150427   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
150428   rtreeDestroy,               /* xDestroy - Drop a table */
150429   rtreeOpen,                  /* xOpen - open a cursor */
150430   rtreeClose,                 /* xClose - close a cursor */
150431   rtreeFilter,                /* xFilter - configure scan constraints */
150432   rtreeNext,                  /* xNext - advance a cursor */
150433   rtreeEof,                   /* xEof */
150434   rtreeColumn,                /* xColumn - read data */
150435   rtreeRowid,                 /* xRowid - read data */
150436   rtreeUpdate,                /* xUpdate - write data */
150437   0,                          /* xBegin - begin transaction */
150438   0,                          /* xSync - sync transaction */
150439   0,                          /* xCommit - commit transaction */
150440   0,                          /* xRollback - rollback transaction */
150441   0,                          /* xFindFunction - function overloading */
150442   rtreeRename,                /* xRename - rename the table */
150443   0,                          /* xSavepoint */
150444   0,                          /* xRelease */
150445   0                           /* xRollbackTo */
150446 };
150447 
150448 static int rtreeSqlInit(
150449   Rtree *pRtree,
150450   sqlite3 *db,
150451   const char *zDb,
150452   const char *zPrefix,
150453   int isCreate
150454 ){
150455   int rc = SQLITE_OK;
150456 
150457   #define N_STATEMENT 9
150458   static const char *azSql[N_STATEMENT] = {
150459     /* Read and write the xxx_node table */
150460     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
150461     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
150462     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
150463 
150464     /* Read and write the xxx_rowid table */
150465     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
150466     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
150467     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
150468 
150469     /* Read and write the xxx_parent table */
150470     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
150471     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
150472     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
150473   };
150474   sqlite3_stmt **appStmt[N_STATEMENT];
150475   int i;
150476 
150477   pRtree->db = db;
150478 
150479   if( isCreate ){
150480     char *zCreate = sqlite3_mprintf(
150481 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
150482 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
150483 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
150484                                   " parentnode INTEGER);"
150485 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
150486       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
150487     );
150488     if( !zCreate ){
150489       return SQLITE_NOMEM;
150490     }
150491     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
150492     sqlite3_free(zCreate);
150493     if( rc!=SQLITE_OK ){
150494       return rc;
150495     }
150496   }
150497 
150498   appStmt[0] = &pRtree->pReadNode;
150499   appStmt[1] = &pRtree->pWriteNode;
150500   appStmt[2] = &pRtree->pDeleteNode;
150501   appStmt[3] = &pRtree->pReadRowid;
150502   appStmt[4] = &pRtree->pWriteRowid;
150503   appStmt[5] = &pRtree->pDeleteRowid;
150504   appStmt[6] = &pRtree->pReadParent;
150505   appStmt[7] = &pRtree->pWriteParent;
150506   appStmt[8] = &pRtree->pDeleteParent;
150507 
150508   rc = rtreeQueryStat1(db, pRtree);
150509   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
150510     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
150511     if( zSql ){
150512       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
150513     }else{
150514       rc = SQLITE_NOMEM;
150515     }
150516     sqlite3_free(zSql);
150517   }
150518 
150519   return rc;
150520 }
150521 
150522 /*
150523 ** The second argument to this function contains the text of an SQL statement
150524 ** that returns a single integer value. The statement is compiled and executed
150525 ** using database connection db. If successful, the integer value returned
150526 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
150527 ** code is returned and the value of *piVal after returning is not defined.
150528 */
150529 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
150530   int rc = SQLITE_NOMEM;
150531   if( zSql ){
150532     sqlite3_stmt *pStmt = 0;
150533     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
150534     if( rc==SQLITE_OK ){
150535       if( SQLITE_ROW==sqlite3_step(pStmt) ){
150536         *piVal = sqlite3_column_int(pStmt, 0);
150537       }
150538       rc = sqlite3_finalize(pStmt);
150539     }
150540   }
150541   return rc;
150542 }
150543 
150544 /*
150545 ** This function is called from within the xConnect() or xCreate() method to
150546 ** determine the node-size used by the rtree table being created or connected
150547 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
150548 ** Otherwise, an SQLite error code is returned.
150549 **
150550 ** If this function is being called as part of an xConnect(), then the rtree
150551 ** table already exists. In this case the node-size is determined by inspecting
150552 ** the root node of the tree.
150553 **
150554 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
150555 ** This ensures that each node is stored on a single database page. If the
150556 ** database page-size is so large that more than RTREE_MAXCELLS entries
150557 ** would fit in a single node, use a smaller node-size.
150558 */
150559 static int getNodeSize(
150560   sqlite3 *db,                    /* Database handle */
150561   Rtree *pRtree,                  /* Rtree handle */
150562   int isCreate,                   /* True for xCreate, false for xConnect */
150563   char **pzErr                    /* OUT: Error message, if any */
150564 ){
150565   int rc;
150566   char *zSql;
150567   if( isCreate ){
150568     int iPageSize = 0;
150569     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
150570     rc = getIntFromStmt(db, zSql, &iPageSize);
150571     if( rc==SQLITE_OK ){
150572       pRtree->iNodeSize = iPageSize-64;
150573       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
150574         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
150575       }
150576     }else{
150577       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
150578     }
150579   }else{
150580     zSql = sqlite3_mprintf(
150581         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
150582         pRtree->zDb, pRtree->zName
150583     );
150584     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
150585     if( rc!=SQLITE_OK ){
150586       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
150587     }
150588   }
150589 
150590   sqlite3_free(zSql);
150591   return rc;
150592 }
150593 
150594 /*
150595 ** This function is the implementation of both the xConnect and xCreate
150596 ** methods of the r-tree virtual table.
150597 **
150598 **   argv[0]   -> module name
150599 **   argv[1]   -> database name
150600 **   argv[2]   -> table name
150601 **   argv[...] -> column names...
150602 */
150603 static int rtreeInit(
150604   sqlite3 *db,                        /* Database connection */
150605   void *pAux,                         /* One of the RTREE_COORD_* constants */
150606   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
150607   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
150608   char **pzErr,                       /* OUT: Error message, if any */
150609   int isCreate                        /* True for xCreate, false for xConnect */
150610 ){
150611   int rc = SQLITE_OK;
150612   Rtree *pRtree;
150613   int nDb;              /* Length of string argv[1] */
150614   int nName;            /* Length of string argv[2] */
150615   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
150616 
150617   const char *aErrMsg[] = {
150618     0,                                                    /* 0 */
150619     "Wrong number of columns for an rtree table",         /* 1 */
150620     "Too few columns for an rtree table",                 /* 2 */
150621     "Too many columns for an rtree table"                 /* 3 */
150622   };
150623 
150624   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
150625   if( aErrMsg[iErr] ){
150626     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
150627     return SQLITE_ERROR;
150628   }
150629 
150630   sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
150631 
150632   /* Allocate the sqlite3_vtab structure */
150633   nDb = (int)strlen(argv[1]);
150634   nName = (int)strlen(argv[2]);
150635   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
150636   if( !pRtree ){
150637     return SQLITE_NOMEM;
150638   }
150639   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
150640   pRtree->nBusy = 1;
150641   pRtree->base.pModule = &rtreeModule;
150642   pRtree->zDb = (char *)&pRtree[1];
150643   pRtree->zName = &pRtree->zDb[nDb+1];
150644   pRtree->nDim = (argc-4)/2;
150645   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
150646   pRtree->eCoordType = eCoordType;
150647   memcpy(pRtree->zDb, argv[1], nDb);
150648   memcpy(pRtree->zName, argv[2], nName);
150649 
150650   /* Figure out the node size to use. */
150651   rc = getNodeSize(db, pRtree, isCreate, pzErr);
150652 
150653   /* Create/Connect to the underlying relational database schema. If
150654   ** that is successful, call sqlite3_declare_vtab() to configure
150655   ** the r-tree table schema.
150656   */
150657   if( rc==SQLITE_OK ){
150658     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
150659       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
150660     }else{
150661       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
150662       char *zTmp;
150663       int ii;
150664       for(ii=4; zSql && ii<argc; ii++){
150665         zTmp = zSql;
150666         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
150667         sqlite3_free(zTmp);
150668       }
150669       if( zSql ){
150670         zTmp = zSql;
150671         zSql = sqlite3_mprintf("%s);", zTmp);
150672         sqlite3_free(zTmp);
150673       }
150674       if( !zSql ){
150675         rc = SQLITE_NOMEM;
150676       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
150677         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
150678       }
150679       sqlite3_free(zSql);
150680     }
150681   }
150682 
150683   if( rc==SQLITE_OK ){
150684     *ppVtab = (sqlite3_vtab *)pRtree;
150685   }else{
150686     assert( *ppVtab==0 );
150687     assert( pRtree->nBusy==1 );
150688     rtreeRelease(pRtree);
150689   }
150690   return rc;
150691 }
150692 
150693 
150694 /*
150695 ** Implementation of a scalar function that decodes r-tree nodes to
150696 ** human readable strings. This can be used for debugging and analysis.
150697 **
150698 ** The scalar function takes two arguments: (1) the number of dimensions
150699 ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
150700 ** an r-tree node.  For a two-dimensional r-tree structure called "rt", to
150701 ** deserialize all nodes, a statement like:
150702 **
150703 **   SELECT rtreenode(2, data) FROM rt_node;
150704 **
150705 ** The human readable string takes the form of a Tcl list with one
150706 ** entry for each cell in the r-tree node. Each entry is itself a
150707 ** list, containing the 8-byte rowid/pageno followed by the
150708 ** <num-dimension>*2 coordinates.
150709 */
150710 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
150711   char *zText = 0;
150712   RtreeNode node;
150713   Rtree tree;
150714   int ii;
150715 
150716   UNUSED_PARAMETER(nArg);
150717   memset(&node, 0, sizeof(RtreeNode));
150718   memset(&tree, 0, sizeof(Rtree));
150719   tree.nDim = sqlite3_value_int(apArg[0]);
150720   tree.nBytesPerCell = 8 + 8 * tree.nDim;
150721   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
150722 
150723   for(ii=0; ii<NCELL(&node); ii++){
150724     char zCell[512];
150725     int nCell = 0;
150726     RtreeCell cell;
150727     int jj;
150728 
150729     nodeGetCell(&tree, &node, ii, &cell);
150730     sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
150731     nCell = (int)strlen(zCell);
150732     for(jj=0; jj<tree.nDim*2; jj++){
150733 #ifndef SQLITE_RTREE_INT_ONLY
150734       sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
150735                        (double)cell.aCoord[jj].f);
150736 #else
150737       sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
150738                        cell.aCoord[jj].i);
150739 #endif
150740       nCell = (int)strlen(zCell);
150741     }
150742 
150743     if( zText ){
150744       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
150745       sqlite3_free(zText);
150746       zText = zTextNew;
150747     }else{
150748       zText = sqlite3_mprintf("{%s}", zCell);
150749     }
150750   }
150751 
150752   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
150753 }
150754 
150755 /* This routine implements an SQL function that returns the "depth" parameter
150756 ** from the front of a blob that is an r-tree node.  For example:
150757 **
150758 **     SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
150759 **
150760 ** The depth value is 0 for all nodes other than the root node, and the root
150761 ** node always has nodeno=1, so the example above is the primary use for this
150762 ** routine.  This routine is intended for testing and analysis only.
150763 */
150764 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
150765   UNUSED_PARAMETER(nArg);
150766   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
150767    || sqlite3_value_bytes(apArg[0])<2
150768   ){
150769     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
150770   }else{
150771     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
150772     sqlite3_result_int(ctx, readInt16(zBlob));
150773   }
150774 }
150775 
150776 /*
150777 ** Register the r-tree module with database handle db. This creates the
150778 ** virtual table module "rtree" and the debugging/analysis scalar
150779 ** function "rtreenode".
150780 */
150781 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
150782   const int utf8 = SQLITE_UTF8;
150783   int rc;
150784 
150785   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
150786   if( rc==SQLITE_OK ){
150787     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
150788   }
150789   if( rc==SQLITE_OK ){
150790 #ifdef SQLITE_RTREE_INT_ONLY
150791     void *c = (void *)RTREE_COORD_INT32;
150792 #else
150793     void *c = (void *)RTREE_COORD_REAL32;
150794 #endif
150795     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
150796   }
150797   if( rc==SQLITE_OK ){
150798     void *c = (void *)RTREE_COORD_INT32;
150799     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
150800   }
150801 
150802   return rc;
150803 }
150804 
150805 /*
150806 ** This routine deletes the RtreeGeomCallback object that was attached
150807 ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
150808 ** or sqlite3_rtree_query_callback().  In other words, this routine is the
150809 ** destructor for an RtreeGeomCallback objecct.  This routine is called when
150810 ** the corresponding SQL function is deleted.
150811 */
150812 static void rtreeFreeCallback(void *p){
150813   RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
150814   if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
150815   sqlite3_free(p);
150816 }
150817 
150818 /*
150819 ** Each call to sqlite3_rtree_geometry_callback() or
150820 ** sqlite3_rtree_query_callback() creates an ordinary SQLite
150821 ** scalar function that is implemented by this routine.
150822 **
150823 ** All this function does is construct an RtreeMatchArg object that
150824 ** contains the geometry-checking callback routines and a list of
150825 ** parameters to this function, then return that RtreeMatchArg object
150826 ** as a BLOB.
150827 **
150828 ** The R-Tree MATCH operator will read the returned BLOB, deserialize
150829 ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
150830 ** out which elements of the R-Tree should be returned by the query.
150831 */
150832 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
150833   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
150834   RtreeMatchArg *pBlob;
150835   int nBlob;
150836 
150837   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
150838   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
150839   if( !pBlob ){
150840     sqlite3_result_error_nomem(ctx);
150841   }else{
150842     int i;
150843     pBlob->magic = RTREE_GEOMETRY_MAGIC;
150844     pBlob->cb = pGeomCtx[0];
150845     pBlob->nParam = nArg;
150846     for(i=0; i<nArg; i++){
150847 #ifdef SQLITE_RTREE_INT_ONLY
150848       pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
150849 #else
150850       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
150851 #endif
150852     }
150853     sqlite3_result_blob(ctx, pBlob, nBlob, sqlite3_free);
150854   }
150855 }
150856 
150857 /*
150858 ** Register a new geometry function for use with the r-tree MATCH operator.
150859 */
150860 SQLITE_API int sqlite3_rtree_geometry_callback(
150861   sqlite3 *db,                  /* Register SQL function on this connection */
150862   const char *zGeom,            /* Name of the new SQL function */
150863   int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
150864   void *pContext                /* Extra data associated with the callback */
150865 ){
150866   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
150867 
150868   /* Allocate and populate the context object. */
150869   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
150870   if( !pGeomCtx ) return SQLITE_NOMEM;
150871   pGeomCtx->xGeom = xGeom;
150872   pGeomCtx->xQueryFunc = 0;
150873   pGeomCtx->xDestructor = 0;
150874   pGeomCtx->pContext = pContext;
150875   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
150876       (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
150877   );
150878 }
150879 
150880 /*
150881 ** Register a new 2nd-generation geometry function for use with the
150882 ** r-tree MATCH operator.
150883 */
150884 SQLITE_API int sqlite3_rtree_query_callback(
150885   sqlite3 *db,                 /* Register SQL function on this connection */
150886   const char *zQueryFunc,      /* Name of new SQL function */
150887   int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
150888   void *pContext,              /* Extra data passed into the callback */
150889   void (*xDestructor)(void*)   /* Destructor for the extra data */
150890 ){
150891   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
150892 
150893   /* Allocate and populate the context object. */
150894   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
150895   if( !pGeomCtx ) return SQLITE_NOMEM;
150896   pGeomCtx->xGeom = 0;
150897   pGeomCtx->xQueryFunc = xQueryFunc;
150898   pGeomCtx->xDestructor = xDestructor;
150899   pGeomCtx->pContext = pContext;
150900   return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
150901       (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
150902   );
150903 }
150904 
150905 #if !SQLITE_CORE
150906 #ifdef _WIN32
150907 __declspec(dllexport)
150908 #endif
150909 SQLITE_API int sqlite3_rtree_init(
150910   sqlite3 *db,
150911   char **pzErrMsg,
150912   const sqlite3_api_routines *pApi
150913 ){
150914   SQLITE_EXTENSION_INIT2(pApi)
150915   return sqlite3RtreeInit(db);
150916 }
150917 #endif
150918 
150919 #endif
150920 
150921 /************** End of rtree.c ***********************************************/
150922 /************** Begin file icu.c *********************************************/
150923 /*
150924 ** 2007 May 6
150925 **
150926 ** The author disclaims copyright to this source code.  In place of
150927 ** a legal notice, here is a blessing:
150928 **
150929 **    May you do good and not evil.
150930 **    May you find forgiveness for yourself and forgive others.
150931 **    May you share freely, never taking more than you give.
150932 **
150933 *************************************************************************
150934 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
150935 **
150936 ** This file implements an integration between the ICU library
150937 ** ("International Components for Unicode", an open-source library
150938 ** for handling unicode data) and SQLite. The integration uses
150939 ** ICU to provide the following to SQLite:
150940 **
150941 **   * An implementation of the SQL regexp() function (and hence REGEXP
150942 **     operator) using the ICU uregex_XX() APIs.
150943 **
150944 **   * Implementations of the SQL scalar upper() and lower() functions
150945 **     for case mapping.
150946 **
150947 **   * Integration of ICU and SQLite collation sequences.
150948 **
150949 **   * An implementation of the LIKE operator that uses ICU to
150950 **     provide case-independent matching.
150951 */
150952 
150953 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
150954 
150955 /* Include ICU headers */
150956 #include <unicode/utypes.h>
150957 #include <unicode/uregex.h>
150958 #include <unicode/ustring.h>
150959 #include <unicode/ucol.h>
150960 
150961 /* #include <assert.h> */
150962 
150963 #ifndef SQLITE_CORE
150964   SQLITE_EXTENSION_INIT1
150965 #else
150966 #endif
150967 
150968 /*
150969 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
150970 ** operator.
150971 */
150972 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
150973 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
150974 #endif
150975 
150976 /*
150977 ** Version of sqlite3_free() that is always a function, never a macro.
150978 */
150979 static void xFree(void *p){
150980   sqlite3_free(p);
150981 }
150982 
150983 /*
150984 ** Compare two UTF-8 strings for equality where the first string is
150985 ** a "LIKE" expression. Return true (1) if they are the same and
150986 ** false (0) if they are different.
150987 */
150988 static int icuLikeCompare(
150989   const uint8_t *zPattern,   /* LIKE pattern */
150990   const uint8_t *zString,    /* The UTF-8 string to compare against */
150991   const UChar32 uEsc         /* The escape character */
150992 ){
150993   static const int MATCH_ONE = (UChar32)'_';
150994   static const int MATCH_ALL = (UChar32)'%';
150995 
150996   int iPattern = 0;       /* Current byte index in zPattern */
150997   int iString = 0;        /* Current byte index in zString */
150998 
150999   int prevEscape = 0;     /* True if the previous character was uEsc */
151000 
151001   while( zPattern[iPattern]!=0 ){
151002 
151003     /* Read (and consume) the next character from the input pattern. */
151004     UChar32 uPattern;
151005     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
151006     assert(uPattern!=0);
151007 
151008     /* There are now 4 possibilities:
151009     **
151010     **     1. uPattern is an unescaped match-all character "%",
151011     **     2. uPattern is an unescaped match-one character "_",
151012     **     3. uPattern is an unescaped escape character, or
151013     **     4. uPattern is to be handled as an ordinary character
151014     */
151015     if( !prevEscape && uPattern==MATCH_ALL ){
151016       /* Case 1. */
151017       uint8_t c;
151018 
151019       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
151020       ** MATCH_ALL. For each MATCH_ONE, skip one character in the
151021       ** test string.
151022       */
151023       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
151024         if( c==MATCH_ONE ){
151025           if( zString[iString]==0 ) return 0;
151026           U8_FWD_1_UNSAFE(zString, iString);
151027         }
151028         iPattern++;
151029       }
151030 
151031       if( zPattern[iPattern]==0 ) return 1;
151032 
151033       while( zString[iString] ){
151034         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
151035           return 1;
151036         }
151037         U8_FWD_1_UNSAFE(zString, iString);
151038       }
151039       return 0;
151040 
151041     }else if( !prevEscape && uPattern==MATCH_ONE ){
151042       /* Case 2. */
151043       if( zString[iString]==0 ) return 0;
151044       U8_FWD_1_UNSAFE(zString, iString);
151045 
151046     }else if( !prevEscape && uPattern==uEsc){
151047       /* Case 3. */
151048       prevEscape = 1;
151049 
151050     }else{
151051       /* Case 4. */
151052       UChar32 uString;
151053       U8_NEXT_UNSAFE(zString, iString, uString);
151054       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
151055       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
151056       if( uString!=uPattern ){
151057         return 0;
151058       }
151059       prevEscape = 0;
151060     }
151061   }
151062 
151063   return zString[iString]==0;
151064 }
151065 
151066 /*
151067 ** Implementation of the like() SQL function.  This function implements
151068 ** the build-in LIKE operator.  The first argument to the function is the
151069 ** pattern and the second argument is the string.  So, the SQL statements:
151070 **
151071 **       A LIKE B
151072 **
151073 ** is implemented as like(B, A). If there is an escape character E,
151074 **
151075 **       A LIKE B ESCAPE E
151076 **
151077 ** is mapped to like(B, A, E).
151078 */
151079 static void icuLikeFunc(
151080   sqlite3_context *context,
151081   int argc,
151082   sqlite3_value **argv
151083 ){
151084   const unsigned char *zA = sqlite3_value_text(argv[0]);
151085   const unsigned char *zB = sqlite3_value_text(argv[1]);
151086   UChar32 uEsc = 0;
151087 
151088   /* Limit the length of the LIKE or GLOB pattern to avoid problems
151089   ** of deep recursion and N*N behavior in patternCompare().
151090   */
151091   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
151092     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
151093     return;
151094   }
151095 
151096 
151097   if( argc==3 ){
151098     /* The escape character string must consist of a single UTF-8 character.
151099     ** Otherwise, return an error.
151100     */
151101     int nE= sqlite3_value_bytes(argv[2]);
151102     const unsigned char *zE = sqlite3_value_text(argv[2]);
151103     int i = 0;
151104     if( zE==0 ) return;
151105     U8_NEXT(zE, i, nE, uEsc);
151106     if( i!=nE){
151107       sqlite3_result_error(context,
151108           "ESCAPE expression must be a single character", -1);
151109       return;
151110     }
151111   }
151112 
151113   if( zA && zB ){
151114     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
151115   }
151116 }
151117 
151118 /*
151119 ** This function is called when an ICU function called from within
151120 ** the implementation of an SQL scalar function returns an error.
151121 **
151122 ** The scalar function context passed as the first argument is
151123 ** loaded with an error message based on the following two args.
151124 */
151125 static void icuFunctionError(
151126   sqlite3_context *pCtx,       /* SQLite scalar function context */
151127   const char *zName,           /* Name of ICU function that failed */
151128   UErrorCode e                 /* Error code returned by ICU function */
151129 ){
151130   char zBuf[128];
151131   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
151132   zBuf[127] = '\0';
151133   sqlite3_result_error(pCtx, zBuf, -1);
151134 }
151135 
151136 /*
151137 ** Function to delete compiled regexp objects. Registered as
151138 ** a destructor function with sqlite3_set_auxdata().
151139 */
151140 static void icuRegexpDelete(void *p){
151141   URegularExpression *pExpr = (URegularExpression *)p;
151142   uregex_close(pExpr);
151143 }
151144 
151145 /*
151146 ** Implementation of SQLite REGEXP operator. This scalar function takes
151147 ** two arguments. The first is a regular expression pattern to compile
151148 ** the second is a string to match against that pattern. If either
151149 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
151150 ** is 1 if the string matches the pattern, or 0 otherwise.
151151 **
151152 ** SQLite maps the regexp() function to the regexp() operator such
151153 ** that the following two are equivalent:
151154 **
151155 **     zString REGEXP zPattern
151156 **     regexp(zPattern, zString)
151157 **
151158 ** Uses the following ICU regexp APIs:
151159 **
151160 **     uregex_open()
151161 **     uregex_matches()
151162 **     uregex_close()
151163 */
151164 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
151165   UErrorCode status = U_ZERO_ERROR;
151166   URegularExpression *pExpr;
151167   UBool res;
151168   const UChar *zString = sqlite3_value_text16(apArg[1]);
151169 
151170   (void)nArg;  /* Unused parameter */
151171 
151172   /* If the left hand side of the regexp operator is NULL,
151173   ** then the result is also NULL.
151174   */
151175   if( !zString ){
151176     return;
151177   }
151178 
151179   pExpr = sqlite3_get_auxdata(p, 0);
151180   if( !pExpr ){
151181     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
151182     if( !zPattern ){
151183       return;
151184     }
151185     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
151186 
151187     if( U_SUCCESS(status) ){
151188       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
151189     }else{
151190       assert(!pExpr);
151191       icuFunctionError(p, "uregex_open", status);
151192       return;
151193     }
151194   }
151195 
151196   /* Configure the text that the regular expression operates on. */
151197   uregex_setText(pExpr, zString, -1, &status);
151198   if( !U_SUCCESS(status) ){
151199     icuFunctionError(p, "uregex_setText", status);
151200     return;
151201   }
151202 
151203   /* Attempt the match */
151204   res = uregex_matches(pExpr, 0, &status);
151205   if( !U_SUCCESS(status) ){
151206     icuFunctionError(p, "uregex_matches", status);
151207     return;
151208   }
151209 
151210   /* Set the text that the regular expression operates on to a NULL
151211   ** pointer. This is not really necessary, but it is tidier than
151212   ** leaving the regular expression object configured with an invalid
151213   ** pointer after this function returns.
151214   */
151215   uregex_setText(pExpr, 0, 0, &status);
151216 
151217   /* Return 1 or 0. */
151218   sqlite3_result_int(p, res ? 1 : 0);
151219 }
151220 
151221 /*
151222 ** Implementations of scalar functions for case mapping - upper() and
151223 ** lower(). Function upper() converts its input to upper-case (ABC).
151224 ** Function lower() converts to lower-case (abc).
151225 **
151226 ** ICU provides two types of case mapping, "general" case mapping and
151227 ** "language specific". Refer to ICU documentation for the differences
151228 ** between the two.
151229 **
151230 ** To utilise "general" case mapping, the upper() or lower() scalar
151231 ** functions are invoked with one argument:
151232 **
151233 **     upper('ABC') -> 'abc'
151234 **     lower('abc') -> 'ABC'
151235 **
151236 ** To access ICU "language specific" case mapping, upper() or lower()
151237 ** should be invoked with two arguments. The second argument is the name
151238 ** of the locale to use. Passing an empty string ("") or SQL NULL value
151239 ** as the second argument is the same as invoking the 1 argument version
151240 ** of upper() or lower().
151241 **
151242 **     lower('I', 'en_us') -> 'i'
151243 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
151244 **
151245 ** http://www.icu-project.org/userguide/posix.html#case_mappings
151246 */
151247 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
151248   const UChar *zInput;
151249   UChar *zOutput;
151250   int nInput;
151251   int nOutput;
151252 
151253   UErrorCode status = U_ZERO_ERROR;
151254   const char *zLocale = 0;
151255 
151256   assert(nArg==1 || nArg==2);
151257   if( nArg==2 ){
151258     zLocale = (const char *)sqlite3_value_text(apArg[1]);
151259   }
151260 
151261   zInput = sqlite3_value_text16(apArg[0]);
151262   if( !zInput ){
151263     return;
151264   }
151265   nInput = sqlite3_value_bytes16(apArg[0]);
151266 
151267   nOutput = nInput * 2 + 2;
151268   zOutput = sqlite3_malloc(nOutput);
151269   if( !zOutput ){
151270     return;
151271   }
151272 
151273   if( sqlite3_user_data(p) ){
151274     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
151275   }else{
151276     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
151277   }
151278 
151279   if( !U_SUCCESS(status) ){
151280     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
151281     return;
151282   }
151283 
151284   sqlite3_result_text16(p, zOutput, -1, xFree);
151285 }
151286 
151287 /*
151288 ** Collation sequence destructor function. The pCtx argument points to
151289 ** a UCollator structure previously allocated using ucol_open().
151290 */
151291 static void icuCollationDel(void *pCtx){
151292   UCollator *p = (UCollator *)pCtx;
151293   ucol_close(p);
151294 }
151295 
151296 /*
151297 ** Collation sequence comparison function. The pCtx argument points to
151298 ** a UCollator structure previously allocated using ucol_open().
151299 */
151300 static int icuCollationColl(
151301   void *pCtx,
151302   int nLeft,
151303   const void *zLeft,
151304   int nRight,
151305   const void *zRight
151306 ){
151307   UCollationResult res;
151308   UCollator *p = (UCollator *)pCtx;
151309   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
151310   switch( res ){
151311     case UCOL_LESS:    return -1;
151312     case UCOL_GREATER: return +1;
151313     case UCOL_EQUAL:   return 0;
151314   }
151315   assert(!"Unexpected return value from ucol_strcoll()");
151316   return 0;
151317 }
151318 
151319 /*
151320 ** Implementation of the scalar function icu_load_collation().
151321 **
151322 ** This scalar function is used to add ICU collation based collation
151323 ** types to an SQLite database connection. It is intended to be called
151324 ** as follows:
151325 **
151326 **     SELECT icu_load_collation(<locale>, <collation-name>);
151327 **
151328 ** Where <locale> is a string containing an ICU locale identifier (i.e.
151329 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
151330 ** collation sequence to create.
151331 */
151332 static void icuLoadCollation(
151333   sqlite3_context *p,
151334   int nArg,
151335   sqlite3_value **apArg
151336 ){
151337   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
151338   UErrorCode status = U_ZERO_ERROR;
151339   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
151340   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
151341   UCollator *pUCollator;    /* ICU library collation object */
151342   int rc;                   /* Return code from sqlite3_create_collation_x() */
151343 
151344   assert(nArg==2);
151345   zLocale = (const char *)sqlite3_value_text(apArg[0]);
151346   zName = (const char *)sqlite3_value_text(apArg[1]);
151347 
151348   if( !zLocale || !zName ){
151349     return;
151350   }
151351 
151352   pUCollator = ucol_open(zLocale, &status);
151353   if( !U_SUCCESS(status) ){
151354     icuFunctionError(p, "ucol_open", status);
151355     return;
151356   }
151357   assert(p);
151358 
151359   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
151360       icuCollationColl, icuCollationDel
151361   );
151362   if( rc!=SQLITE_OK ){
151363     ucol_close(pUCollator);
151364     sqlite3_result_error(p, "Error registering collation function", -1);
151365   }
151366 }
151367 
151368 /*
151369 ** Register the ICU extension functions with database db.
151370 */
151371 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
151372   struct IcuScalar {
151373     const char *zName;                        /* Function name */
151374     int nArg;                                 /* Number of arguments */
151375     int enc;                                  /* Optimal text encoding */
151376     void *pContext;                           /* sqlite3_user_data() context */
151377     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
151378   } scalars[] = {
151379     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
151380 
151381     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
151382     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
151383     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
151384     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
151385 
151386     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
151387     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
151388     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
151389     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
151390 
151391     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
151392     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
151393 
151394     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
151395   };
151396 
151397   int rc = SQLITE_OK;
151398   int i;
151399 
151400   for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
151401     struct IcuScalar *p = &scalars[i];
151402     rc = sqlite3_create_function(
151403         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
151404     );
151405   }
151406 
151407   return rc;
151408 }
151409 
151410 #if !SQLITE_CORE
151411 #ifdef _WIN32
151412 __declspec(dllexport)
151413 #endif
151414 SQLITE_API int sqlite3_icu_init(
151415   sqlite3 *db,
151416   char **pzErrMsg,
151417   const sqlite3_api_routines *pApi
151418 ){
151419   SQLITE_EXTENSION_INIT2(pApi)
151420   return sqlite3IcuInit(db);
151421 }
151422 #endif
151423 
151424 #endif
151425 
151426 /************** End of icu.c *************************************************/
151427 /************** Begin file fts3_icu.c ****************************************/
151428 /*
151429 ** 2007 June 22
151430 **
151431 ** The author disclaims copyright to this source code.  In place of
151432 ** a legal notice, here is a blessing:
151433 **
151434 **    May you do good and not evil.
151435 **    May you find forgiveness for yourself and forgive others.
151436 **    May you share freely, never taking more than you give.
151437 **
151438 *************************************************************************
151439 ** This file implements a tokenizer for fts3 based on the ICU library.
151440 */
151441 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
151442 #ifdef SQLITE_ENABLE_ICU
151443 
151444 /* #include <assert.h> */
151445 /* #include <string.h> */
151446 
151447 #include <unicode/ubrk.h>
151448 /* #include <unicode/ucol.h> */
151449 /* #include <unicode/ustring.h> */
151450 #include <unicode/utf16.h>
151451 
151452 typedef struct IcuTokenizer IcuTokenizer;
151453 typedef struct IcuCursor IcuCursor;
151454 
151455 struct IcuTokenizer {
151456   sqlite3_tokenizer base;
151457   char *zLocale;
151458 };
151459 
151460 struct IcuCursor {
151461   sqlite3_tokenizer_cursor base;
151462 
151463   UBreakIterator *pIter;      /* ICU break-iterator object */
151464   int nChar;                  /* Number of UChar elements in pInput */
151465   UChar *aChar;               /* Copy of input using utf-16 encoding */
151466   int *aOffset;               /* Offsets of each character in utf-8 input */
151467 
151468   int nBuffer;
151469   char *zBuffer;
151470 
151471   int iToken;
151472 };
151473 
151474 /*
151475 ** Create a new tokenizer instance.
151476 */
151477 static int icuCreate(
151478   int argc,                            /* Number of entries in argv[] */
151479   const char * const *argv,            /* Tokenizer creation arguments */
151480   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
151481 ){
151482   IcuTokenizer *p;
151483   int n = 0;
151484 
151485   if( argc>0 ){
151486     n = strlen(argv[0])+1;
151487   }
151488   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
151489   if( !p ){
151490     return SQLITE_NOMEM;
151491   }
151492   memset(p, 0, sizeof(IcuTokenizer));
151493 
151494   if( n ){
151495     p->zLocale = (char *)&p[1];
151496     memcpy(p->zLocale, argv[0], n);
151497   }
151498 
151499   *ppTokenizer = (sqlite3_tokenizer *)p;
151500 
151501   return SQLITE_OK;
151502 }
151503 
151504 /*
151505 ** Destroy a tokenizer
151506 */
151507 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
151508   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
151509   sqlite3_free(p);
151510   return SQLITE_OK;
151511 }
151512 
151513 /*
151514 ** Prepare to begin tokenizing a particular string.  The input
151515 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
151516 ** used to incrementally tokenize this string is returned in
151517 ** *ppCursor.
151518 */
151519 static int icuOpen(
151520   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
151521   const char *zInput,                    /* Input string */
151522   int nInput,                            /* Length of zInput in bytes */
151523   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
151524 ){
151525   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
151526   IcuCursor *pCsr;
151527 
151528   const int32_t opt = U_FOLD_CASE_DEFAULT;
151529   UErrorCode status = U_ZERO_ERROR;
151530   int nChar;
151531 
151532   UChar32 c;
151533   int iInput = 0;
151534   int iOut = 0;
151535 
151536   *ppCursor = 0;
151537 
151538   if( zInput==0 ){
151539     nInput = 0;
151540     zInput = "";
151541   }else if( nInput<0 ){
151542     nInput = strlen(zInput);
151543   }
151544   nChar = nInput+1;
151545   pCsr = (IcuCursor *)sqlite3_malloc(
151546       sizeof(IcuCursor) +                /* IcuCursor */
151547       ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
151548       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
151549   );
151550   if( !pCsr ){
151551     return SQLITE_NOMEM;
151552   }
151553   memset(pCsr, 0, sizeof(IcuCursor));
151554   pCsr->aChar = (UChar *)&pCsr[1];
151555   pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
151556 
151557   pCsr->aOffset[iOut] = iInput;
151558   U8_NEXT(zInput, iInput, nInput, c);
151559   while( c>0 ){
151560     int isError = 0;
151561     c = u_foldCase(c, opt);
151562     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
151563     if( isError ){
151564       sqlite3_free(pCsr);
151565       return SQLITE_ERROR;
151566     }
151567     pCsr->aOffset[iOut] = iInput;
151568 
151569     if( iInput<nInput ){
151570       U8_NEXT(zInput, iInput, nInput, c);
151571     }else{
151572       c = 0;
151573     }
151574   }
151575 
151576   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
151577   if( !U_SUCCESS(status) ){
151578     sqlite3_free(pCsr);
151579     return SQLITE_ERROR;
151580   }
151581   pCsr->nChar = iOut;
151582 
151583   ubrk_first(pCsr->pIter);
151584   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
151585   return SQLITE_OK;
151586 }
151587 
151588 /*
151589 ** Close a tokenization cursor previously opened by a call to icuOpen().
151590 */
151591 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
151592   IcuCursor *pCsr = (IcuCursor *)pCursor;
151593   ubrk_close(pCsr->pIter);
151594   sqlite3_free(pCsr->zBuffer);
151595   sqlite3_free(pCsr);
151596   return SQLITE_OK;
151597 }
151598 
151599 /*
151600 ** Extract the next token from a tokenization cursor.
151601 */
151602 static int icuNext(
151603   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
151604   const char **ppToken,               /* OUT: *ppToken is the token text */
151605   int *pnBytes,                       /* OUT: Number of bytes in token */
151606   int *piStartOffset,                 /* OUT: Starting offset of token */
151607   int *piEndOffset,                   /* OUT: Ending offset of token */
151608   int *piPosition                     /* OUT: Position integer of token */
151609 ){
151610   IcuCursor *pCsr = (IcuCursor *)pCursor;
151611 
151612   int iStart = 0;
151613   int iEnd = 0;
151614   int nByte = 0;
151615 
151616   while( iStart==iEnd ){
151617     UChar32 c;
151618 
151619     iStart = ubrk_current(pCsr->pIter);
151620     iEnd = ubrk_next(pCsr->pIter);
151621     if( iEnd==UBRK_DONE ){
151622       return SQLITE_DONE;
151623     }
151624 
151625     while( iStart<iEnd ){
151626       int iWhite = iStart;
151627       U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
151628       if( u_isspace(c) ){
151629         iStart = iWhite;
151630       }else{
151631         break;
151632       }
151633     }
151634     assert(iStart<=iEnd);
151635   }
151636 
151637   do {
151638     UErrorCode status = U_ZERO_ERROR;
151639     if( nByte ){
151640       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
151641       if( !zNew ){
151642         return SQLITE_NOMEM;
151643       }
151644       pCsr->zBuffer = zNew;
151645       pCsr->nBuffer = nByte;
151646     }
151647 
151648     u_strToUTF8(
151649         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
151650         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
151651         &status                                  /* Output success/failure */
151652     );
151653   } while( nByte>pCsr->nBuffer );
151654 
151655   *ppToken = pCsr->zBuffer;
151656   *pnBytes = nByte;
151657   *piStartOffset = pCsr->aOffset[iStart];
151658   *piEndOffset = pCsr->aOffset[iEnd];
151659   *piPosition = pCsr->iToken++;
151660 
151661   return SQLITE_OK;
151662 }
151663 
151664 /*
151665 ** The set of routines that implement the simple tokenizer
151666 */
151667 static const sqlite3_tokenizer_module icuTokenizerModule = {
151668   0,                           /* iVersion */
151669   icuCreate,                   /* xCreate  */
151670   icuDestroy,                  /* xCreate  */
151671   icuOpen,                     /* xOpen    */
151672   icuClose,                    /* xClose   */
151673   icuNext,                     /* xNext    */
151674 };
151675 
151676 /*
151677 ** Set *ppModule to point at the implementation of the ICU tokenizer.
151678 */
151679 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
151680   sqlite3_tokenizer_module const**ppModule
151681 ){
151682   *ppModule = &icuTokenizerModule;
151683 }
151684 
151685 #endif /* defined(SQLITE_ENABLE_ICU) */
151686 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
151687 
151688 /************** End of fts3_icu.c ********************************************/
151689